-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
107 lines (79 loc) · 1.78 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
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
99
100
101
102
103
104
105
106
107
package main
import (
"bufio"
"fmt"
"io"
"net"
"os"
"regexp"
"strconv"
"strings"
)
const PORT = "3000"
func main() {
l, err := net.Listen("tcp", ":"+PORT)
if err != nil {
fmt.Println("Error listening:", err.Error())
os.Exit(1)
}
defer l.Close()
fmt.Println("Listening on port: " + PORT)
for {
conn, err := l.Accept()
if err != nil {
fmt.Println("Error accepting connection:", err.Error())
continue
}
go handleRequest(conn)
}
}
func handleRequest(conn net.Conn) {
request := newRequest()
reader := bufio.NewReader(conn)
index := 0
for {
line, _ := reader.ReadString('\n')
line = strings.ReplaceAll(line[:len(line)-1], "\r", "")
if line == "" {
break
}
if index == 0 {
parseVerbAndPath(line, request)
} else {
parseHeader(line, request)
}
index++
}
contentLength, _ := strconv.Atoi(request.headers["Content-Length"])
body := make([]byte, contentLength)
io.ReadFull(reader, body)
request.body = string(body)
conn.Write([]byte(fmt.Sprintf("HTTP/1.1 200 OK\n\nHere is a response with your passed body: %v\n", request.body)))
conn.Close()
}
type request struct {
verb string
headers map[string]string
path string
body string
}
func newRequest() *request {
req := new(request)
req.headers = make(map[string]string)
return req
}
func parseVerbAndPath(line string, request *request) {
regex := regexp.MustCompile(`^(?P<verb>[A-Z]*)\s(?P<path>[^\s]*)\sHTTP\/.*$`)
matches := regex.FindStringSubmatch(line)
if matches != nil {
request.verb = matches[1]
request.path = matches[2]
}
}
func parseHeader(line string, request *request) {
regex := regexp.MustCompile(`^(?P<key>[^:]+):\s*(?P<val>.+)$`)
matches := regex.FindStringSubmatch(line)
if matches != nil {
request.headers[matches[1]] = matches[2]
}
}