-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathparser.go
51 lines (44 loc) · 926 Bytes
/
parser.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
package main
import (
"fmt"
"strconv"
"strings"
)
type Request struct {
proto string
version string
command string
headers []byte
body []byte
}
func reqParse(req string) Request {
res := strings.Split(req, "\n")
reqLine := res[0]
payload := strings.Join(res[1:], "\n")
r := strings.Split(reqLine, " ")
if len(r) < 8 {
r = append(r, " ")
}
headersLen, _ := strconv.Atoi(r[3])
bodyLen, _ := strconv.Atoi(r[4])
headers := payload[0:headersLen]
body := payload[headersLen : headersLen+bodyLen]
request := Request{
proto: r[0],
version: r[1],
command: r[2],
headers: []byte(headers),
body: []byte(body),
}
return request
}
func reqMarshal(req Request) string {
requestLine := fmt.Sprintf("%s %s %s %d %d",
req.proto,
req.version,
req.command,
len(req.headers),
len(req.body))
r := fmt.Sprintf("%s\n%s%s", requestLine, string(req.headers), string(req.body))
return r
}