forked from valyala/fasthttp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_test.go
1842 lines (1576 loc) · 51.9 KB
/
http_test.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
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package fasthttp
import (
"bufio"
"bytes"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"strings"
"testing"
"time"
"github.com/valyala/bytebufferpool"
)
func TestResponseBodyStreamDeflate(t *testing.T) {
body := createFixedBody(1e5)
// Verifies https://github.com/valyala/fasthttp/issues/176
// when Content-Length is explicitly set.
testResponseBodyStreamDeflate(t, body, len(body))
// Verifies that 'transfer-encoding: chunked' works as expected.
testResponseBodyStreamDeflate(t, body, -1)
}
func TestResponseBodyStreamGzip(t *testing.T) {
body := createFixedBody(1e5)
// Verifies https://github.com/valyala/fasthttp/issues/176
// when Content-Length is explicitly set.
testResponseBodyStreamGzip(t, body, len(body))
// Verifies that 'transfer-encoding: chunked' works as expected.
testResponseBodyStreamGzip(t, body, -1)
}
func testResponseBodyStreamDeflate(t *testing.T, body []byte, bodySize int) {
var r Response
r.SetBodyStream(bytes.NewReader(body), bodySize)
w := &bytes.Buffer{}
bw := bufio.NewWriter(w)
if err := r.WriteDeflate(bw); err != nil {
t.Fatalf("unexpected error: %s", err)
}
if err := bw.Flush(); err != nil {
t.Fatalf("unexpected error: %s", err)
}
var resp Response
br := bufio.NewReader(w)
if err := resp.Read(br); err != nil {
t.Fatalf("unexpected error: %s", err)
}
respBody, err := resp.BodyInflate()
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
if !bytes.Equal(respBody, body) {
t.Fatalf("unexpected body: %q. Expecting %q", respBody, body)
}
}
func testResponseBodyStreamGzip(t *testing.T, body []byte, bodySize int) {
var r Response
r.SetBodyStream(bytes.NewReader(body), bodySize)
w := &bytes.Buffer{}
bw := bufio.NewWriter(w)
if err := r.WriteGzip(bw); err != nil {
t.Fatalf("unexpected error: %s", err)
}
if err := bw.Flush(); err != nil {
t.Fatalf("unexpected error: %s", err)
}
var resp Response
br := bufio.NewReader(w)
if err := resp.Read(br); err != nil {
t.Fatalf("unexpected error: %s", err)
}
respBody, err := resp.BodyGunzip()
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
if !bytes.Equal(respBody, body) {
t.Fatalf("unexpected body: %q. Expecting %q", respBody, body)
}
}
func TestResponseWriteGzipNilBody(t *testing.T) {
var r Response
w := &bytes.Buffer{}
bw := bufio.NewWriter(w)
if err := r.WriteGzip(bw); err != nil {
t.Fatalf("unexpected error: %s", err)
}
if err := bw.Flush(); err != nil {
t.Fatalf("unexpected error: %s", err)
}
}
func TestResponseWriteDeflateNilBody(t *testing.T) {
var r Response
w := &bytes.Buffer{}
bw := bufio.NewWriter(w)
if err := r.WriteDeflate(bw); err != nil {
t.Fatalf("unexpected error: %s", err)
}
if err := bw.Flush(); err != nil {
t.Fatalf("unexpected error: %s", err)
}
}
func TestResponseSwapBodySerial(t *testing.T) {
testResponseSwapBody(t)
}
func TestResponseSwapBodyConcurrent(t *testing.T) {
ch := make(chan struct{})
for i := 0; i < 10; i++ {
go func() {
testResponseSwapBody(t)
ch <- struct{}{}
}()
}
for i := 0; i < 10; i++ {
select {
case <-ch:
case <-time.After(time.Second):
t.Fatalf("timeout")
}
}
}
func testResponseSwapBody(t *testing.T) {
var b []byte
r := AcquireResponse()
for i := 0; i < 20; i++ {
bOrig := r.Body()
b = r.SwapBody(b)
if !bytes.Equal(bOrig, b) {
t.Fatalf("unexpected body returned: %q. Expecting %q", b, bOrig)
}
r.AppendBodyString("foobar")
}
s := "aaaabbbbcccc"
b = b[:0]
for i := 0; i < 10; i++ {
r.SetBodyStream(bytes.NewBufferString(s), len(s))
b = r.SwapBody(b)
if string(b) != s {
t.Fatalf("unexpected body returned: %q. Expecting %q", b, s)
}
b = r.SwapBody(b)
if len(b) > 0 {
t.Fatalf("unexpected body with non-zero size returned: %q", b)
}
}
ReleaseResponse(r)
}
func TestRequestSwapBodySerial(t *testing.T) {
testRequestSwapBody(t)
}
func TestRequestSwapBodyConcurrent(t *testing.T) {
ch := make(chan struct{})
for i := 0; i < 10; i++ {
go func() {
testRequestSwapBody(t)
ch <- struct{}{}
}()
}
for i := 0; i < 10; i++ {
select {
case <-ch:
case <-time.After(time.Second):
t.Fatalf("timeout")
}
}
}
func testRequestSwapBody(t *testing.T) {
var b []byte
r := AcquireRequest()
for i := 0; i < 20; i++ {
bOrig := r.Body()
b = r.SwapBody(b)
if !bytes.Equal(bOrig, b) {
t.Fatalf("unexpected body returned: %q. Expecting %q", b, bOrig)
}
r.AppendBodyString("foobar")
}
s := "aaaabbbbcccc"
b = b[:0]
for i := 0; i < 10; i++ {
r.SetBodyStream(bytes.NewBufferString(s), len(s))
b = r.SwapBody(b)
if string(b) != s {
t.Fatalf("unexpected body returned: %q. Expecting %q", b, s)
}
b = r.SwapBody(b)
if len(b) > 0 {
t.Fatalf("unexpected body with non-zero size returned: %q", b)
}
}
ReleaseRequest(r)
}
func TestRequestHostFromRequestURI(t *testing.T) {
hExpected := "foobar.com"
var req Request
req.SetRequestURI("http://proxy-host:123/foobar?baz")
req.SetHost(hExpected)
h := req.Host()
if string(h) != hExpected {
t.Fatalf("unexpected host set: %q. Expecting %q", h, hExpected)
}
}
func TestRequestHostFromHeader(t *testing.T) {
hExpected := "foobar.com"
var req Request
req.Header.SetHost(hExpected)
h := req.Host()
if string(h) != hExpected {
t.Fatalf("unexpected host set: %q. Expecting %q", h, hExpected)
}
}
func TestRequestContentTypeWithCharsetIssue100(t *testing.T) {
expectedContentType := "application/x-www-form-urlencoded; charset=UTF-8"
expectedBody := "0123=56789"
s := fmt.Sprintf("POST / HTTP/1.1\r\nContent-Type: %s\r\nContent-Length: %d\r\n\r\n%s",
expectedContentType, len(expectedBody), expectedBody)
br := bufio.NewReader(bytes.NewBufferString(s))
var r Request
if err := r.Read(br); err != nil {
t.Fatalf("unexpected error: %s", err)
}
body := r.Body()
if string(body) != expectedBody {
t.Fatalf("unexpected body %q. Expecting %q", body, expectedBody)
}
ct := r.Header.ContentType()
if string(ct) != expectedContentType {
t.Fatalf("unexpected content-type %q. Expecting %q", ct, expectedContentType)
}
args := r.PostArgs()
if args.Len() != 1 {
t.Fatalf("unexpected number of POST args: %d. Expecting 1", args.Len())
}
av := args.Peek("0123")
if string(av) != "56789" {
t.Fatalf("unexpected POST arg value: %q. Expecting %q", av, "56789")
}
}
func TestRequestReadMultipartFormWithFile(t *testing.T) {
s := `POST /upload HTTP/1.1
Host: localhost:10000
Content-Length: 521
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryJwfATyF8tmxSJnLg
------WebKitFormBoundaryJwfATyF8tmxSJnLg
Content-Disposition: form-data; name="f1"
value1
------WebKitFormBoundaryJwfATyF8tmxSJnLg
Content-Disposition: form-data; name="fileaaa"; filename="TODO"
Content-Type: application/octet-stream
- SessionClient with referer and cookies support.
- Client with requests' pipelining support.
- ProxyHandler similar to FSHandler.
- WebSockets. See https://tools.ietf.org/html/rfc6455 .
- HTTP/2.0. See https://tools.ietf.org/html/rfc7540 .
------WebKitFormBoundaryJwfATyF8tmxSJnLg--
tailfoobar`
br := bufio.NewReader(bytes.NewBufferString(s))
var r Request
if err := r.Read(br); err != nil {
t.Fatalf("unexpected error: %s", err)
}
tail, err := ioutil.ReadAll(br)
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
if string(tail) != "tailfoobar" {
t.Fatalf("unexpected tail %q. Expecting %q", tail, "tailfoobar")
}
f, err := r.MultipartForm()
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
defer r.RemoveMultipartFormFiles()
// verify values
if len(f.Value) != 1 {
t.Fatalf("unexpected number of values in multipart form: %d. Expecting 1", len(f.Value))
}
for k, vv := range f.Value {
if k != "f1" {
t.Fatalf("unexpected value name %q. Expecting %q", k, "f1")
}
if len(vv) != 1 {
t.Fatalf("unexpected number of values %d. Expecting 1", len(vv))
}
v := vv[0]
if v != "value1" {
t.Fatalf("unexpected value %q. Expecting %q", v, "value1")
}
}
// verify files
if len(f.File) != 1 {
t.Fatalf("unexpected number of file values in multipart form: %d. Expecting 1", len(f.File))
}
for k, vv := range f.File {
if k != "fileaaa" {
t.Fatalf("unexpected file value name %q. Expecting %q", k, "fileaaa")
}
if len(vv) != 1 {
t.Fatalf("unexpected number of file values %d. Expecting 1", len(vv))
}
v := vv[0]
if v.Filename != "TODO" {
t.Fatalf("unexpected filename %q. Expecting %q", v.Filename, "TODO")
}
ct := v.Header.Get("Content-Type")
if ct != "application/octet-stream" {
t.Fatalf("unexpected content-type %q. Expecting %q", ct, "application/octet-stream")
}
}
}
func TestRequestRequestURI(t *testing.T) {
var r Request
// Set request uri via SetRequestURI()
uri := "/foo/bar?baz"
r.SetRequestURI(uri)
if string(r.RequestURI()) != uri {
t.Fatalf("unexpected request uri %q. Expecting %q", r.RequestURI(), uri)
}
// Set request uri via Request.URI().Update()
r.Reset()
uri = "/aa/bbb?ccc=sdfsdf"
r.URI().Update(uri)
if string(r.RequestURI()) != uri {
t.Fatalf("unexpected request uri %q. Expecting %q", r.RequestURI(), uri)
}
// update query args in the request uri
qa := r.URI().QueryArgs()
qa.Reset()
qa.Set("foo", "bar")
uri = "/aa/bbb?foo=bar"
if string(r.RequestURI()) != uri {
t.Fatalf("unexpected request uri %q. Expecting %q", r.RequestURI(), uri)
}
}
func TestRequestUpdateURI(t *testing.T) {
var r Request
r.Header.SetHost("aaa.bbb")
r.SetRequestURI("/lkjkl/kjl")
// Modify request uri and host via URI() object and make sure
// the requestURI and Host header are properly updated
u := r.URI()
u.SetPath("/123/432.html")
u.SetHost("foobar.com")
a := u.QueryArgs()
a.Set("aaa", "bcse")
s := r.String()
if !strings.HasPrefix(s, "GET /123/432.html?aaa=bcse") {
t.Fatalf("cannot find %q in %q", "GET /123/432.html?aaa=bcse", s)
}
if strings.Index(s, "\r\nHost: foobar.com\r\n") < 0 {
t.Fatalf("cannot find %q in %q", "\r\nHost: foobar.com\r\n", s)
}
}
func TestRequestBodyStreamMultipleBodyCalls(t *testing.T) {
var r Request
s := "foobar baz abc"
if r.IsBodyStream() {
t.Fatalf("IsBodyStream must return false")
}
r.SetBodyStream(bytes.NewBufferString(s), len(s))
if !r.IsBodyStream() {
t.Fatalf("IsBodyStream must return true")
}
for i := 0; i < 10; i++ {
body := r.Body()
if string(body) != s {
t.Fatalf("unexpected body %q. Expecting %q. iteration %d", body, s, i)
}
}
}
func TestResponseBodyStreamMultipleBodyCalls(t *testing.T) {
var r Response
s := "foobar baz abc"
if r.IsBodyStream() {
t.Fatalf("IsBodyStream must return false")
}
r.SetBodyStream(bytes.NewBufferString(s), len(s))
if !r.IsBodyStream() {
t.Fatalf("IsBodyStream must return true")
}
for i := 0; i < 10; i++ {
body := r.Body()
if string(body) != s {
t.Fatalf("unexpected body %q. Expecting %q. iteration %d", body, s, i)
}
}
}
func TestRequestBodyWriteToPlain(t *testing.T) {
var r Request
expectedS := "foobarbaz"
r.AppendBodyString(expectedS)
testBodyWriteTo(t, &r, expectedS, true)
}
func TestResponseBodyWriteToPlain(t *testing.T) {
var r Response
expectedS := "foobarbaz"
r.AppendBodyString(expectedS)
testBodyWriteTo(t, &r, expectedS, true)
}
func TestResponseBodyWriteToStream(t *testing.T) {
var r Response
expectedS := "aaabbbccc"
buf := bytes.NewBufferString(expectedS)
if r.IsBodyStream() {
t.Fatalf("IsBodyStream must return false")
}
r.SetBodyStream(buf, len(expectedS))
if !r.IsBodyStream() {
t.Fatalf("IsBodyStream must return true")
}
testBodyWriteTo(t, &r, expectedS, false)
}
func TestRequestBodyWriteToMultipart(t *testing.T) {
expectedS := "--foobar\r\nContent-Disposition: form-data; name=\"key_0\"\r\n\r\nvalue_0\r\n--foobar--\r\n"
s := fmt.Sprintf("POST / HTTP/1.1\r\nHost: aaa\r\nContent-Type: multipart/form-data; boundary=foobar\r\nContent-Length: %d\r\n\r\n%s",
len(expectedS), expectedS)
var r Request
br := bufio.NewReader(bytes.NewBufferString(s))
if err := r.Read(br); err != nil {
t.Fatalf("unexpected error: %s", err)
}
testBodyWriteTo(t, &r, expectedS, true)
}
type bodyWriterTo interface {
BodyWriteTo(io.Writer) error
Body() []byte
}
func testBodyWriteTo(t *testing.T, bw bodyWriterTo, expectedS string, isRetainedBody bool) {
var buf bytebufferpool.ByteBuffer
if err := bw.BodyWriteTo(&buf); err != nil {
t.Fatalf("unexpected error: %s", err)
}
s := buf.B
if string(s) != expectedS {
t.Fatalf("unexpected result %q. Expecting %q", s, expectedS)
}
body := bw.Body()
if isRetainedBody {
if string(body) != expectedS {
t.Fatalf("unexpected body %q. Expecting %q", body, expectedS)
}
} else {
if len(body) > 0 {
t.Fatalf("unexpected non-zero body after BodyWriteTo: %q", body)
}
}
}
func TestRequestReadEOF(t *testing.T) {
var r Request
br := bufio.NewReader(&bytes.Buffer{})
err := r.Read(br)
if err == nil {
t.Fatalf("expecting error")
}
if err != io.EOF {
t.Fatalf("unexpected error: %s. Expecting %s", err, io.EOF)
}
// incomplete request mustn't return io.EOF
br = bufio.NewReader(bytes.NewBufferString("POST / HTTP/1.1\r\nContent-Type: aa\r\nContent-Length: 1234\r\n\r\nIncomplete body"))
err = r.Read(br)
if err == nil {
t.Fatalf("expecting error")
}
if err == io.EOF {
t.Fatalf("expecting non-EOF error")
}
}
func TestResponseReadEOF(t *testing.T) {
var r Response
br := bufio.NewReader(&bytes.Buffer{})
err := r.Read(br)
if err == nil {
t.Fatalf("expecting error")
}
if err != io.EOF {
t.Fatalf("unexpected error: %s. Expecting %s", err, io.EOF)
}
// incomplete response mustn't return io.EOF
br = bufio.NewReader(bytes.NewBufferString("HTTP/1.1 200 OK\r\nContent-Type: aaa\r\nContent-Length: 123\r\n\r\nIncomplete body"))
err = r.Read(br)
if err == nil {
t.Fatalf("expecting error")
}
if err == io.EOF {
t.Fatalf("expecting non-EOF error")
}
}
func TestResponseWriteTo(t *testing.T) {
var r Response
r.SetBodyString("foobar")
s := r.String()
var buf bytebufferpool.ByteBuffer
n, err := r.WriteTo(&buf)
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
if n != int64(len(s)) {
t.Fatalf("unexpected response length %d. Expecting %d", n, len(s))
}
if string(buf.B) != s {
t.Fatalf("unexpected response %q. Expecting %q", buf.B, s)
}
}
func TestRequestWriteTo(t *testing.T) {
var r Request
r.SetRequestURI("http://foobar.com/aaa/bbb")
s := r.String()
var buf bytebufferpool.ByteBuffer
n, err := r.WriteTo(&buf)
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
if n != int64(len(s)) {
t.Fatalf("unexpected request length %d. Expecting %d", n, len(s))
}
if string(buf.B) != s {
t.Fatalf("unexpected request %q. Expecting %q", buf.B, s)
}
}
func TestResponseSkipBody(t *testing.T) {
var r Response
// set StatusNotModified
r.Header.SetStatusCode(StatusNotModified)
r.SetBodyString("foobar")
s := r.String()
if strings.Contains(s, "\r\n\r\nfoobar") {
t.Fatalf("unexpected non-zero body in response %q", s)
}
if strings.Contains(s, "Content-Length: ") {
t.Fatalf("unexpected content-length in response %q", s)
}
if strings.Contains(s, "Content-Type: ") {
t.Fatalf("unexpected content-type in response %q", s)
}
// set StatusNoContent
r.Header.SetStatusCode(StatusNoContent)
r.SetBodyString("foobar")
s = r.String()
if strings.Contains(s, "\r\n\r\nfoobar") {
t.Fatalf("unexpected non-zero body in response %q", s)
}
if strings.Contains(s, "Content-Length: ") {
t.Fatalf("unexpected content-length in response %q", s)
}
if strings.Contains(s, "Content-Type: ") {
t.Fatalf("unexpected content-type in response %q", s)
}
// explicitly skip body
r.Header.SetStatusCode(StatusOK)
r.SkipBody = true
r.SetBodyString("foobar")
s = r.String()
if strings.Contains(s, "\r\n\r\nfoobar") {
t.Fatalf("unexpected non-zero body in response %q", s)
}
if !strings.Contains(s, "Content-Length: 6\r\n") {
t.Fatalf("expecting content-length in response %q", s)
}
if !strings.Contains(s, "Content-Type: ") {
t.Fatalf("expecting content-type in response %q", s)
}
}
func TestRequestNoContentLength(t *testing.T) {
var r Request
r.Header.SetMethod("HEAD")
r.Header.SetHost("foobar")
s := r.String()
if strings.Contains(s, "Content-Length: ") {
t.Fatalf("unexpected content-length in HEAD request %q", s)
}
r.Header.SetMethod("POST")
fmt.Fprintf(r.BodyWriter(), "foobar body")
s = r.String()
if !strings.Contains(s, "Content-Length: ") {
t.Fatalf("missing content-length header in non-GET request %q", s)
}
}
func TestRequestReadGzippedBody(t *testing.T) {
var r Request
bodyOriginal := "foo bar baz compress me better!"
body := AppendGzipBytes(nil, []byte(bodyOriginal))
s := fmt.Sprintf("POST /foobar HTTP/1.1\r\nContent-Type: foo/bar\r\nContent-Encoding: gzip\r\nContent-Length: %d\r\n\r\n%s",
len(body), body)
br := bufio.NewReader(bytes.NewBufferString(s))
if err := r.Read(br); err != nil {
t.Fatalf("unexpected error: %s", err)
}
if string(r.Header.Peek("Content-Encoding")) != "gzip" {
t.Fatalf("unexpected content-encoding: %q. Expecting %q", r.Header.Peek("Content-Encoding"), "gzip")
}
if r.Header.ContentLength() != len(body) {
t.Fatalf("unexpected content-length: %d. Expecting %d", r.Header.ContentLength(), len(body))
}
if string(r.Body()) != string(body) {
t.Fatalf("unexpected body: %q. Expecting %q", r.Body(), body)
}
bodyGunzipped, err := AppendGunzipBytes(nil, r.Body())
if err != nil {
t.Fatalf("unexpected error when uncompressing data: %s", err)
}
if string(bodyGunzipped) != bodyOriginal {
t.Fatalf("unexpected uncompressed body %q. Expecting %q", bodyGunzipped, bodyOriginal)
}
}
func TestRequestReadPostNoBody(t *testing.T) {
var r Request
s := "POST /foo/bar HTTP/1.1\r\nContent-Type: aaa/bbb\r\n\r\naaaa"
br := bufio.NewReader(bytes.NewBufferString(s))
if err := r.Read(br); err != nil {
t.Fatalf("unexpected error: %s", err)
}
if string(r.Header.RequestURI()) != "/foo/bar" {
t.Fatalf("unexpected request uri %q. Expecting %q", r.Header.RequestURI(), "/foo/bar")
}
if string(r.Header.ContentType()) != "aaa/bbb" {
t.Fatalf("unexpected content-type %q. Expecting %q", r.Header.ContentType(), "aaa/bbb")
}
if len(r.Body()) != 0 {
t.Fatalf("unexpected body found %q. Expecting empty body", r.Body())
}
if r.Header.ContentLength() != 0 {
t.Fatalf("unexpected content-length: %d. Expecting 0", r.Header.ContentLength())
}
tail, err := ioutil.ReadAll(br)
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
if string(tail) != "aaaa" {
t.Fatalf("unexpected tail %q. Expecting %q", tail, "aaaa")
}
}
func TestRequestContinueReadBody(t *testing.T) {
s := "PUT /foo/bar HTTP/1.1\r\nExpect: 100-continue\r\nContent-Length: 5\r\nContent-Type: foo/bar\r\n\r\nabcdef4343"
br := bufio.NewReader(bytes.NewBufferString(s))
var r Request
if err := r.Read(br); err != nil {
t.Fatalf("unexpected error: %s", err)
}
if !r.MayContinue() {
t.Fatalf("MayContinue must return true")
}
if err := r.ContinueReadBody(br, 0); err != nil {
t.Fatalf("error when reading request body: %s", err)
}
body := r.Body()
if string(body) != "abcde" {
t.Fatalf("unexpected body %q. Expecting %q", body, "abcde")
}
tail, err := ioutil.ReadAll(br)
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
if string(tail) != "f4343" {
t.Fatalf("unexpected tail %q. Expecting %q", tail, "f4343")
}
}
func TestRequestMayContinue(t *testing.T) {
var r Request
if r.MayContinue() {
t.Fatalf("MayContinue on empty request must return false")
}
r.Header.Set("Expect", "123sdfds")
if r.MayContinue() {
t.Fatalf("MayContinue on invalid Expect header must return false")
}
r.Header.Set("Expect", "100-continue")
if !r.MayContinue() {
t.Fatalf("MayContinue on 'Expect: 100-continue' header must return true")
}
}
func TestResponseGzipStream(t *testing.T) {
var r Response
if r.IsBodyStream() {
t.Fatalf("IsBodyStream must return false")
}
r.SetBodyStreamWriter(func(w *bufio.Writer) {
fmt.Fprintf(w, "foo")
w.Flush()
time.Sleep(time.Millisecond)
w.Write([]byte("barbaz"))
w.Flush()
time.Sleep(time.Millisecond)
fmt.Fprintf(w, "1234")
if err := w.Flush(); err != nil {
t.Fatalf("unexpected error: %s", err)
}
})
if !r.IsBodyStream() {
t.Fatalf("IsBodyStream must return true")
}
testResponseGzipExt(t, &r, "foobarbaz1234")
}
func TestResponseDeflateStream(t *testing.T) {
var r Response
if r.IsBodyStream() {
t.Fatalf("IsBodyStream must return false")
}
r.SetBodyStreamWriter(func(w *bufio.Writer) {
w.Write([]byte("foo"))
w.Flush()
fmt.Fprintf(w, "barbaz")
w.Flush()
w.Write([]byte("1234"))
if err := w.Flush(); err != nil {
t.Fatalf("unexpected error: %s", err)
}
})
if !r.IsBodyStream() {
t.Fatalf("IsBodyStream must return true")
}
testResponseDeflateExt(t, &r, "foobarbaz1234")
}
func TestResponseDeflate(t *testing.T) {
for _, s := range compressTestcases {
testResponseDeflate(t, s)
}
}
func TestResponseGzip(t *testing.T) {
for _, s := range compressTestcases {
testResponseGzip(t, s)
}
}
func testResponseDeflate(t *testing.T, s string) {
var r Response
r.SetBodyString(s)
testResponseDeflateExt(t, &r, s)
// make sure the uncompressible Content-Type isn't compressed
r.Reset()
r.Header.SetContentType("image/jpeg")
r.SetBodyString(s)
testResponseDeflateExt(t, &r, s)
}
func testResponseDeflateExt(t *testing.T, r *Response, s string) {
isCompressible := isCompressibleResponse(r, s)
var buf bytes.Buffer
var err error
bw := bufio.NewWriter(&buf)
if err = r.WriteDeflate(bw); err != nil {
t.Fatalf("unexpected error: %s", err)
}
if err = bw.Flush(); err != nil {
t.Fatalf("unexpected error: %s", err)
}
var r1 Response
br := bufio.NewReader(&buf)
if err = r1.Read(br); err != nil {
t.Fatalf("unexpected error: %s", err)
}
ce := r1.Header.Peek("Content-Encoding")
var body []byte
if isCompressible {
if string(ce) != "deflate" {
t.Fatalf("unexpected Content-Encoding %q. Expecting %q. len(s)=%d, Content-Type: %q",
ce, "deflate", len(s), r.Header.ContentType())
}
body, err = r1.BodyInflate()
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
} else {
if len(ce) > 0 {
t.Fatalf("expecting empty Content-Encoding. Got %q", ce)
}
body = r1.Body()
}
if string(body) != s {
t.Fatalf("unexpected body %q. Expecting %q", body, s)
}
}
func testResponseGzip(t *testing.T, s string) {
var r Response
r.SetBodyString(s)
testResponseGzipExt(t, &r, s)
// make sure the uncompressible Content-Type isn't compressed
r.Reset()
r.Header.SetContentType("image/jpeg")
r.SetBodyString(s)
testResponseGzipExt(t, &r, s)
}
func testResponseGzipExt(t *testing.T, r *Response, s string) {
isCompressible := isCompressibleResponse(r, s)
var buf bytes.Buffer
var err error
bw := bufio.NewWriter(&buf)
if err = r.WriteGzip(bw); err != nil {
t.Fatalf("unexpected error: %s", err)
}
if err = bw.Flush(); err != nil {
t.Fatalf("unexpected error: %s", err)
}
var r1 Response
br := bufio.NewReader(&buf)
if err = r1.Read(br); err != nil {
t.Fatalf("unexpected error: %s", err)
}
ce := r1.Header.Peek("Content-Encoding")
var body []byte
if isCompressible {
if string(ce) != "gzip" {
t.Fatalf("unexpected Content-Encoding %q. Expecting %q. len(s)=%d, Content-Type: %q",
ce, "gzip", len(s), r.Header.ContentType())
}
body, err = r1.BodyGunzip()
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
} else {
if len(ce) > 0 {
t.Fatalf("Expecting empty Content-Encoding. Got %q", ce)
}
body = r1.Body()
}
if string(body) != s {
t.Fatalf("unexpected body %q. Expecting %q", body, s)
}
}
func isCompressibleResponse(r *Response, s string) bool {
isCompressible := r.Header.isCompressibleContentType()
if isCompressible && len(s) < minCompressLen && !r.IsBodyStream() {
isCompressible = false
}
return isCompressible
}
func TestRequestMultipartForm(t *testing.T) {
var w bytes.Buffer
mw := multipart.NewWriter(&w)
for i := 0; i < 10; i++ {
k := fmt.Sprintf("key_%d", i)
v := fmt.Sprintf("value_%d", i)
if err := mw.WriteField(k, v); err != nil {
t.Fatalf("unexpected error: %s", err)
}
}
boundary := mw.Boundary()
if err := mw.Close(); err != nil {
t.Fatalf("unexpected error: %s", err)
}
formData := w.Bytes()
for i := 0; i < 5; i++ {
formData = testRequestMultipartForm(t, boundary, formData, 10)
}
// verify request unmarshalling / marshalling
s := "POST / HTTP/1.1\r\nHost: aaa\r\nContent-Type: multipart/form-data; boundary=foobar\r\nContent-Length: 213\r\n\r\n--foobar\r\nContent-Disposition: form-data; name=\"key_0\"\r\n\r\nvalue_0\r\n--foobar\r\nContent-Disposition: form-data; name=\"key_1\"\r\n\r\nvalue_1\r\n--foobar\r\nContent-Disposition: form-data; name=\"key_2\"\r\n\r\nvalue_2\r\n--foobar--\r\n"
var req Request
br := bufio.NewReader(bytes.NewBufferString(s))
if err := req.Read(br); err != nil {
t.Fatalf("unexpected error: %s", err)
}
s = req.String()
br = bufio.NewReader(bytes.NewBufferString(s))
if err := req.Read(br); err != nil {
t.Fatalf("unexpected error: %s", err)
}
testRequestMultipartForm(t, "foobar", req.Body(), 3)
}
func testRequestMultipartForm(t *testing.T, boundary string, formData []byte, partsCount int) []byte {
s := fmt.Sprintf("POST / HTTP/1.1\r\nHost: aaa\r\nContent-Type: multipart/form-data; boundary=%s\r\nContent-Length: %d\r\n\r\n%s",
boundary, len(formData), formData)
var req Request
r := bytes.NewBufferString(s)
br := bufio.NewReader(r)
if err := req.Read(br); err != nil {
t.Fatalf("unexpected error: %s", err)
}
f, err := req.MultipartForm()
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
defer req.RemoveMultipartFormFiles()