forked from GoesToEleven/GolangTraining
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
70 lines (62 loc) · 1.1 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package main
import (
"bufio"
"fmt"
"io"
"log"
"net"
"strings"
)
func handleConn(conn net.Conn) {
defer conn.Close()
scanner := bufio.NewScanner(conn)
i := 0
for scanner.Scan() {
ln := scanner.Text()
fmt.Println(ln)
if i == 0 {
method := strings.Fields(ln)[0]
fmt.Println("METHOD", method)
} else {
// in headers now
// when line is empty, header is done
if ln == "" {
break
}
}
i++
}
// response
body := `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<strong>Hello World</strong>
</body>
</html>
`
io.WriteString(conn, "HTTP/1.1 302 OK\r\n")
fmt.Fprintf(conn, "Content-Length: %d\r\n", len(body))
fmt.Fprintf(conn, "Content-Type: text/plain\r\n")
fmt.Fprintf(conn, "Location: http://www.google.com\r\n")
io.WriteString(conn, "\r\n")
io.WriteString(conn, body)
}
func main() {
server, err := net.Listen("tcp", ":9000")
if err != nil {
log.Fatalln(err.Error())
}
defer server.Close()
for {
conn, err := server.Accept()
if err != nil {
log.Fatalln(err.Error())
}
go handleConn(conn)
}
}