/
http.go
63 lines (58 loc) · 1.41 KB
/
http.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
package utils
import (
"bytes"
)
// HTTP HTTP
type HTTP struct {
General []byte
Header map[string][]byte
Body []byte
}
// NewHTTP New
func NewHTTP() *HTTP {
return &HTTP{Header: make(map[string][]byte)}
}
// ParseRequest parse http request
func (http *HTTP) ParseRequest(content []byte) error {
if len(content) < 4 {
return nil
}
index := bytes.Index(content, []byte("\r\n\r\n"))
if index != -1 {
allHeader := content[:index]
splitHeader := bytes.Split(allHeader, []byte("\r\n"))
http.General = splitHeader[0]
for _, v := range splitHeader[1:] {
kv := bytes.Split(v, []byte(":"))
key := string(bytes.Trim(kv[0], " "))
value := bytes.Trim(kv[1], " ")
http.Header[key] = value
}
if bytes.Contains(http.General, []byte("POST")) && len(content[index:]) > 4 {
http.Body = content[index+4:]
}
}
return nil
}
// ParseResponse parse http response
func (http *HTTP) ParseResponse(content []byte) error {
if len(content) < 4 {
return nil
}
index := bytes.Index(content, []byte("\r\n\r\n"))
if index != -1 {
allHeader := content[:index]
splitHeader := bytes.Split(allHeader, []byte("\r\n"))
http.General = splitHeader[0]
for _, v := range splitHeader[1:] {
kv := bytes.Split(v, []byte(":"))
key := string(bytes.Trim(kv[0], " "))
value := bytes.Trim(kv[1], " ")
http.Header[key] = value
}
if len(content[index:]) > 4 {
http.Body = content[index+4:]
}
}
return nil
}