Go simple multiplexer by me
Go simple multiplexer by me
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package main
import (
"fmt"
"log"
"net"
"bufio"
"strings"
)
func main() {
li, err := net.Listen("tcp", ":8080")
if err != nil {
log.Panic(err)
}
defer li.Close()
for {
conn, err := li.Accept()
if err != nil {
log.Println(err)
}
go handle(conn)
}
}
func handle(conn net.Conn) {
defer conn.Close()
rURL := request(conn)
response(conn, rURL)
}
func request(conn net.Conn) string {
i := 0
scanner := bufio.NewScanner(conn)
var RequestURL string
for scanner.Scan() {
ln := scanner.Text()
fmt.Println(ln)
if i == 0 {
m := strings.Fields(ln)[0]
RequestURL = strings.Fields(ln)[1]
fmt.Println("***METHOD:", m)
}
if ln == "" {
// according RFC at the end of each request there
// is the blank line and know this is really the END
// so we "break" out of loop
break
}
i++
}
return RequestURL
}
func returnedData(conn net.Conn, requestURL string, uniqText string) {
body := `<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8">
<title></title>
</head><body>
<strong>` + uniqText + "Requested URL: " + requestURL +
`</strong>
</body>
</html>`
fmt.Fprint(conn, "HTTP/1.1 200 OK\r\n")
fmt.Fprintf(conn, "Content-Length: %d\r\n", len(body))
fmt.Fprint(conn, "Content-Type: text/html\r\n")
fmt.Fprint(conn, "\r\n")
fmt.Fprint(conn, body)
}
func response(conn net.Conn, requestURL string) {
switch {
case requestURL == "/about":
uniq := "ABOUT "
returnedData(conn, requestURL, uniq)
case requestURL == "/customers":
uniq := "CUSTOMERS "
returnedData(conn, requestURL, uniq)
default:
uniq := "EVERYTHING ELSE "
returnedData(conn, requestURL, uniq)
}
}
This post is licensed under CC BY 4.0 by the author.
