-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
56 lines (46 loc) · 1.01 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package main
import (
"fmt"
"net"
"os"
"strconv"
"strings"
)
const LISTEN_ADDR = ":8080"
const DEFAULT_TEXT = "Hello, World!"
func main() {
text := DEFAULT_TEXT
if len(os.Args) > 1 {
text = strings.Join(os.Args[1:], " ")
}
listener, e := net.Listen("tcp", LISTEN_ADDR)
noError("listen", e)
defer func() { noError("server close", listener.Close()) }()
buffer := make([]byte, 1024)
output := []byte(
"HTTP/1.1 200 OK\r\n" +
"Content-Type: text/plain\r\n" +
"Connection: close\r\n" +
"Content-Length: " + strconv.Itoa(len(text)) + "\r\n" +
"\r\n" +
text)
for {
conn, e := listener.Accept()
noError("accept", e)
go func() {
defer func() { noError("close", conn.Close()) }()
n, e := conn.Read(buffer)
noError("read", e)
if n > 4 && buffer[n-4] == '\r' && buffer[n-3] == '\n' &&
buffer[n-2] == '\r' && buffer[n-1] == '\n' {
_, e := conn.Write(output)
noError("write", e)
}
}()
}
}
func noError(step string, e error) {
if e != nil {
fmt.Println(step, e)
}
}