Repository navigation
Expand file tree
/
Copy pathgohttp.go
More file actions
360 lines (283 loc) · 8.02 KB
/
Copy pathgohttp.go
File metadata and controls
360 lines (283 loc) · 8.02 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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
// 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"
)
type config struct {
allowLFLineEndings bool
}
func newConfig(options ...Option) config {
var config config
for _, option := range options {
option(&config)
}
return config
}
// Option represents a function that modifies the passed config instance.
type Option func(*config)
// WithLFLineEndings defines whether LF line endings are allowed for more
// tolerant parsing. Use with care!
func WithLFLineEndings(allow bool) Option {
return func(c *config) {
c.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, options ...Option) (*http.Request, error) {
config := newConfig(options...)
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, config) {
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, config) {
break
}
fieldName, fieldValue, err := parseHeaderField(line)
if err != nil {
return nil, err
}
request.Header.Add(fieldName, fieldValue)
}
if !isNewLine(line, config) {
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")
}
}
return &request, 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))
if err := writeHeaderFields(r.Header, &buf); err != nil {
return nil, err
}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, err
}
if len(body) == 0 {
return buf.Bytes(), nil
}
buf.Write(body)
return buf.Bytes(), nil
}
// ParseResponse reads a given source and parses an http.Response instance
// from it.
//
// The option WithLFLineEndings allows the header fields and the empty line
// terminating the header section to be LF instead of CRLF endings.
func ParseResponse(reader *bufio.Reader, options ...Option) (*http.Response, error) {
config := newConfig(options...)
response := http.Response{}
line, err := reader.ReadString('\n')
if err != nil {
return nil, err
}
protocol, statusCode, reasonPhrase, err := parseStatusLine(line)
if err != nil {
return nil, err
}
response.Proto = protocol
response.StatusCode = statusCode
response.Status = fmt.Sprintf("%d %s", statusCode, reasonPhrase)
response.Header = make(http.Header)
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, config) {
break
}
fieldName, fieldValue, err := parseHeaderField(line)
if err != nil {
return nil, err
}
response.Header.Add(fieldName, fieldValue)
}
if !isNewLine(line, config) {
return nil, errors.New("empty line after header section is missing")
}
length, err := determineBodyLength(response.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")
}
}
return &response, 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) {
var buf bytes.Buffer
buf.WriteString(fmt.Sprintf("%s %s\r\n", r.Proto, r.Status))
if err := writeHeaderFields(r.Header, &buf); err != nil {
return nil, err
}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, err
}
if len(body) == 0 {
return buf.Bytes(), nil
}
buf.Write(body)
return buf.Bytes(), 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, parsedUrl, protocol, nil
}
func parseStatusLine(line string) (string, int, string, error) {
data := strings.Split(line, " ")
// RFC 7230, section 3.1.2. prescribes exactly 3 tokens.
if len(data) != 3 {
return "", 0, "", errors.New("invalid status line syntax")
}
protocol := strings.TrimSuffix(data[0], "\r\n")
statusCode := strings.TrimSuffix(data[1], "\r\n")
reasonPhrase := strings.TrimSuffix(data[2], "\r\n")
parsedStatusCode, err := strconv.Atoi(statusCode)
if err != nil {
return "", 0, "", err
}
return protocol, parsedStatusCode, reasonPhrase, 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 writeHeaderFields(headers http.Header, w io.Writer) error {
for fieldName, values := range headers {
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 += ", "
}
}
headerField := fmt.Sprintf("%s: %s\r\n", fieldName, fieldValue)
if _, err := w.Write([]byte(headerField)); err != nil {
return err
}
}
if _, err := w.Write([]byte("\r\n")); err != nil {
return err
}
return 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 -1, nil
}
func isNewLine(line string, config config) bool {
if config.allowLFLineEndings {
return line == "\r\n" || line == "\n"
}
return line == "\r\n"
}