Repository navigation
Expand file tree
/
Copy pathgohttp.go
More file actions
231 lines (185 loc) · 5.38 KB
/
Copy pathgohttp.go
File metadata and controls
231 lines (185 loc) · 5.38 KB
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
// Package gohttp provides convenience functions for parsing net/http
// objects from a source and serializing them back to byte slices.
package gohttp
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"strings"
"unicode"
)
var (
allowLFLineEndings = false
)
// AllowLFLineEndings defines whether LF line endings are allowed for more
// tolerant parsing. Use with care!
func AllowLFLineEndings(allow bool) {
allowLFLineEndings = allow
}
// ParseRequest reads a given source and parses an http.Request instance
// from it.
//
// If the user allows LF line endings, the header fields and the empty
// line terminating the header section may be LF instead of CRLF endings.
func ParseRequest(reader *bufio.Reader) (*http.Request, error) {
request := http.Request{}
// RFC 7230, section 3.5. states that a robust parser implementation
// should ignore at least one empty line prior to the request line.
for {
line, err := reader.ReadString('\n')
if err != nil {
return nil, err
}
if !isNewLine(line) {
method, targetUrl, protocol, err := parseRequestLine(line)
if err != nil {
return nil, err
}
request.Method = method
request.URL = targetUrl
request.Proto = protocol
break
}
}
request.Header = make(http.Header)
var line string
var err error
for {
line, err = reader.ReadString('\n')
if err != nil && !errors.Is(err, io.EOF) {
return nil, err
}
if errors.Is(err, io.EOF) {
break
}
if isNewLine(line) {
break
}
fieldName, fieldValue, err := parseHeaderField(line)
if err != nil {
return nil, err
}
request.Header.Add(fieldName, fieldValue)
}
if !isNewLine(line) {
return nil, errors.New("empty line after header section is missing")
}
length, err := determineBodyLength(request.Header, reader)
if err != nil {
return nil, err
}
if length > 0 {
var body = make([]byte, length)
n, err := reader.Read(body)
if err != nil {
return nil, err
}
if n != length {
return nil, errors.New("wrong body length")
}
fmt.Println(string(body))
}
return nil, nil
}
// SerializeRequest converts an http.Request instance into a byte slice.
//
// SerializeRequest uses CRLF line endings when serializing the request
// instance, regardless whether the user allows LF line endings or not.
func SerializeRequest(r *http.Request) ([]byte, error) {
var buf bytes.Buffer
buf.WriteString(fmt.Sprintf("%s %s %s\r\n", r.Method, r.URL.String(), r.Proto))
for fieldName, values := range r.Header {
var fieldValue string
// Assemble the field value components (RFC 7230, section 3.2.6).
for i := 0; i < len(values); i++ {
fieldValue += values[i]
if i < len(values)-1 {
fieldValue += ", "
}
}
buf.WriteString(fmt.Sprintf("%s: %s\r\n", fieldName, fieldValue))
}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, err
}
if len(body) == 0 {
return buf.Bytes(), nil
}
buf.WriteString("\r\n")
buf.Write(body)
return buf.Bytes(), nil
}
// ParseResponse reads a given source and parses an http.Response instance
// from it.
//
// If the user allows LF line endings, the header fields and the empty
// line terminating the header section may be LF instead of CRLF endings.
func ParseResponse(r *bufio.Reader) (*http.Response, error) {
return nil, nil
}
// SerializeResponse converts an http.Response instance into a byte slice.
//
// SerializeResponse uses CRLF line endings when serializing the response
// instance, regardless whether the user allows LF line endings or not.
func SerializeResponse(r *http.Response) ([]byte, error) {
return nil, nil
}
func parseRequestLine(line string) (string, *url.URL, string, error) {
data := strings.Split(line, " ")
// RFC 7230, section 3.1.1 prescribes exactly 3 tokens.
if len(data) != 3 {
return "", nil, "", errors.New("invalid request line syntax")
}
method := strings.TrimSuffix(data[0], "\n")
targetUrl := strings.TrimSuffix(data[1], "\n")
protocol := strings.TrimSuffix(data[2], "\n")
parsedUrl, err := url.Parse(targetUrl)
if err != nil {
return "", nil, "", err
}
return method, pars
5E2E
edUrl, protocol, nil
}
func parseHeaderField(line string) (string, string, error) {
tokens := strings.SplitN(line, ":", 2)
// RFC 7230, sections 3.2. and 3.2.4. prescribe exactly 2 tokens.
if len(tokens) != 2 {
return "", "", errors.New("invalid header field syntax")
}
name := strings.TrimSpace(tokens[0])
value := strings.TrimSpace(strings.TrimSuffix(tokens[1], "\n"))
return name, value, nil
}
func determineBodyLength(headers http.Header, reader *bufio.Reader) (int, error) {
// If the Transfer-Encoding header is set, the length of the message
// chunk is contained within the body (RFC 7230, section 3.3.3.).
if transferEncoding := headers.Get("Transfer-Encoding"); transferEncoding != "" {
firstBodyLine, err := reader.ReadString('\n')
if err != nil {
return 0, err
}
// Parse the hex code as int.
// Use TrimRightFunc and not strings.TrimSpace to make sure the hex is at the beginning.
length, err := strconv.ParseInt(strings.TrimRightFunc(firstBodyLine, unicode.IsSpace), 16, 64)
if err != nil {
return 0, err
}
return int(length), nil
}
if contentLength := headers.Get("Content-Length"); contentLength != "" {
return strconv.Atoi(contentLength)
}
return 0, nil
}
func isNewLine(line string) bool {
if allowLFLineEndings {
return line == "\r\n" || line == "\n"
}
return line == "\r\n"
}