File tree Expand file tree Collapse file tree 1 file changed +75
-0
lines changed
016_building-a-tcp-server-for-http/04_hands-on Expand file tree Collapse file tree 1 file changed +75
-0
lines changed Original file line number Diff line number Diff line change 1+ package main
2+
3+ import (
4+ "bufio"
5+ "fmt"
6+ "log"
7+ "net"
8+ "strings"
9+ )
10+
11+ func main () {
12+ li , err := net .Listen ("tcp" , ":8080" )
13+ if err != nil {
14+ log .Fatalln (err .Error ())
15+ }
16+ defer li .Close ()
17+
18+ for {
19+ conn , err := li .Accept ()
20+ if err != nil {
21+ log .Fatalln (err .Error ())
22+ continue
23+ }
24+ go handle (conn )
25+ }
26+ }
27+
28+ func handle (conn net.Conn ) {
29+ defer conn .Close ()
30+
31+ // read request
32+ m , u := request (conn )
33+
34+ fmt .Println ("Method and Url: " , m , u )
35+ // write response
36+
37+ if u == "/hello" {
38+ respond (conn , `<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title></title></head><body><strong>Hello</strong></body></html>` )
39+ }
40+ {
41+ respond (conn , `<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title></title></head><body><strong>KUR</strong></body></html>` )
42+ }
43+
44+ }
45+
46+ func request (conn net.Conn ) (string , string ) {
47+ i := 0
48+ method := ""
49+ url := ""
50+
51+ scanner := bufio .NewScanner (conn )
52+ for scanner .Scan () {
53+ ln := scanner .Text ()
54+
55+ fmt .Println (ln )
56+ if i == 0 {
57+ method = strings .Fields (ln )[0 ]
58+ url = strings .Fields (ln )[1 ]
59+ }
60+ if ln == "" {
61+ break
62+ }
63+ i ++
64+ }
65+ return method , url
66+ }
67+
68+ func respond (conn net.Conn , body string ) {
69+
70+ fmt .Fprint (conn , "HTTP/1.1 200 OK\r \n " )
71+ fmt .Fprintf (conn , "Content-Length: %d\r \n " , len (body ))
72+ fmt .Fprint (conn , "Content-Type: text/html\r \n " )
73+ fmt .Fprint (conn , "\r \n " )
74+ fmt .Fprint (conn , body )
75+ }
You can’t perform that action at this time.
0 commit comments