-
Notifications
You must be signed in to change notification settings - Fork 0
/
request.go
90 lines (80 loc) · 1.8 KB
/
request.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
package httpong
import (
"fmt"
"io"
"net"
"regexp"
"strconv"
"strings"
)
type Req struct {
Body string
ContentType string
Method string
Path string
}
// read request from client
func ReadReq(conn net.Conn) (req Req) {
// var arr []byte
size := 4 << 10
a := make([]byte, size)
// conn.SetDeadline(time.Now().Add(1 * time.Second))
// conn.SetReadDeadline(time.Now().Add(1 * time.Second))
_, err := conn.Read(a)
if err == io.EOF {
fmt.Println("break")
}
// r := bytes.NewReader(a)
// fmt.Println("read", readBytes)
fmt.Printf("%v\n", string(a))
fmt.Println("method", getHTTPMethod(string(a)))
fmt.Println("path:", getPath(string(a)))
fmt.Println("content-length", getContentLength(string(a)))
fmt.Println("body", getBody(string(a)))
req = Req{
Body: getBody(string(a)),
Path: getPath(string(a)),
Method: getHTTPMethod(string(a)),
ContentType: getContentType(string(a)),
}
return req
}
// return http method
func getHTTPMethod(l string) string {
pattern := `^(\w+)`
re := regexp.MustCompile(pattern)
matches := re.FindString(l)
return matches
}
func getContentLength(l string) int {
pattern := `Content-Length: (\d+)`
re := regexp.MustCompile(pattern)
matches := re.FindStringSubmatch(l)
if len(matches) == 0 {
return 0
}
length, _ := strconv.Atoi(matches[1])
return length
}
func getContentType(l string) string {
pattern := `Content-Type: (\w+)`
re := regexp.MustCompile(pattern)
matches := re.FindStringSubmatch(l)
if len(matches) == 0 {
return ""
}
return matches[1]
}
func getBody(l string) string {
pattern := `\r\n\r\n(.*)`
re := regexp.MustCompile(pattern)
matches := re.FindStringSubmatch(l)
if len(matches) == 0 {
return ""
}
return matches[1]
}
func getPath(l string) string {
path := strings.Split(l, " ")[1]
return path
}