Repository navigation
Expand file tree
/
Copy pathapp_test.go
More file actions
3944 lines (3368 loc) · 123 KB
/
Copy pathapp_test.go
File metadata and controls
3944 lines (3368 loc) · 123 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
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
// ⚡️ Fiber is an Express inspired web framework written in Go with ☕️
// 🤖 GitHub Repository: https://github.com/gofiber/fiber
// 📌 API Documentation: https://docs.gofiber.io
package fiber
import (
"bufio"
"bytes"
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"reflect"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"unsafe"
"github.com/gofiber/fiber/v3/internal/apptest"
"github.com/gofiber/fiber/v3/internal/fieldname"
"github.com/gofiber/utils/v2"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/valyala/fasthttp"
"github.com/valyala/fasthttp/fasthttputil"
)
type typedNilHandlerError struct {
message string
}
func (e *typedNilHandlerError) Error() string {
return e.message
}
type fileView struct {
path string
content string
loads int
}
func (v *fileView) Load() error {
contents, err := os.ReadFile(v.path)
if err != nil {
return fmt.Errorf("read template: %w", err)
}
v.content = string(contents)
v.loads++
return nil
}
func (*fileView) Render(io.Writer, string, any, ...string) error { return nil }
func testEmptyHandler(_ Ctx) error {
return nil
}
func testStatus200(t *testing.T, app *App, url, method string) {
t.Helper()
apptest.Expect(t, app, apptest.Req(method, url), 200)
}
// conventions:ignore parallel: legacy, sequential before the rule; make it parallel and delete this line
func Test_App_Test_Goroutine_Leak_Compare(t *testing.T) {
// Not parallel: this test relies on runtime.NumGoroutine() deltas,
// which are unreliable when hundreds of other tests spawn goroutines
// concurrently.
testCases := []struct {
handler Handler
name string
timeout time.Duration
sleepTime time.Duration
expectLeak bool
}{
{
name: "With timeout (potential leak)",
handler: func(c Ctx) error {
time.Sleep(300 * time.Millisecond) // Simulate time-consuming operation
return c.SendString("ok")
},
timeout: 50 * time.Millisecond, // Short timeout to ensure triggering
sleepTime: 500 * time.Millisecond, // Wait time longer than handler execution time
expectLeak: true,
},
{
name: "Without timeout (no leak)",
handler: func(c Ctx) error { return c.SendString("ok") }, // Return immediately
timeout: 0, // Disable timeout
sleepTime: 100 * time.Millisecond,
expectLeak: false,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
app := New()
initialGoroutines := runtime.NumGoroutine()
t.Logf("[%s] Initial goroutines: %d", tc.name, initialGoroutines)
app.Get("/", tc.handler)
numRequests := 10
for range numRequests {
req := httptest.NewRequest(MethodGet, "/", http.NoBody)
if tc.timeout > 0 {
_, err := app.Test(req, TestConfig{Timeout: tc.timeout, FailOnTimeout: true})
require.Error(t, err)
require.ErrorIs(t, err, os.ErrDeadlineExceeded)
} else if resp, err := app.Test(req); err != nil {
t.Errorf("unexpected error: %v", err)
} else {
require.Equal(t, 200, resp.StatusCode)
}
}
// Wait for normal goroutines to complete
time.Sleep(tc.sleepTime)
finalGoroutines := runtime.NumGoroutine()
leakedGoroutines := max(finalGoroutines-initialGoroutines, 0)
t.Logf("[%s] Final goroutines: %d (leaked: %d)", tc.name, finalGoroutines, leakedGoroutines)
if tc.expectLeak {
// We allow up to 3x the request count to account for noise; zero is tolerated.
maxLeak := numRequests * 3
if leakedGoroutines > maxLeak {
t.Errorf("[%s] Expected at most %d leaked goroutines, but got %d",
tc.name, maxLeak, leakedGoroutines)
}
return
}
// No-leak scenario: allow a small buffer for runtime noise.
// Increase slack to reduce flakes from background goroutines.
if leakedGoroutines > numRequests {
t.Errorf("[%s] Expected at most %d leaked goroutines, but got %d",
tc.name, numRequests, leakedGoroutines)
}
})
}
}
func Test_App_MethodNotAllowed(t *testing.T) {
t.Parallel()
app := New()
app.Use(func(c Ctx) error { return c.Next() })
app.Post("/", testEmptyHandler)
app.Options("/", testEmptyHandler)
resp := apptest.Expect(t, app, apptest.Req(MethodPost, "/"), 200)
require.Empty(t, resp.Header.Get(HeaderAllow))
// requireAllow requires a 405 listing allow for each of methods.
requireAllow := func(allow string, methods ...string) {
for _, method := range methods {
resp := apptest.Expect(t, app, apptest.Req(method, "/"), 405)
require.Equal(t, allow, resp.Header.Get(HeaderAllow), method)
}
}
requireAllow("POST, OPTIONS", MethodGet, MethodPatch, MethodPut)
app.Get("/", testEmptyHandler)
requireAllow("GET, HEAD, POST, OPTIONS", MethodTrace, MethodPatch)
app.Head("/", testEmptyHandler)
requireAllow("GET, HEAD, POST, OPTIONS", MethodPut)
}
func Test_App_QueryMethod_AllowHeader(t *testing.T) {
t.Parallel()
app := New()
app.Query("/", testEmptyHandler)
// OPTIONS auto-response advertises QUERY in the Allow header.
resp := apptest.Do(t, app, apptest.Req(MethodOptions, "/"))
require.Contains(t, resp.Header.Get(HeaderAllow), MethodQuery)
// A non-registered method yields 405 with QUERY listed in Allow.
resp = apptest.Expect(t, app, "/", StatusMethodNotAllowed)
require.Contains(t, resp.Header.Get(HeaderAllow), MethodQuery)
}
func Test_App_RegisterNetHTTPHandler(t *testing.T) {
t.Parallel()
tests := []struct {
name string
register func(app *App, path string, handler any, handlers ...any) Router
method string
expectBody bool
}{
{name: "Get", register: (*App).Get, method: http.MethodGet, expectBody: true},
{name: "Head", register: (*App).Head, method: http.MethodHead},
{name: "Post", register: (*App).Post, method: http.MethodPost, expectBody: true},
{name: "Put", register: (*App).Put, method: http.MethodPut, expectBody: true},
{name: "Delete", register: (*App).Delete, method: http.MethodDelete, expectBody: true},
{name: "Connect", register: (*App).Connect, method: http.MethodConnect, expectBody: true},
{name: "Options", register: (*App).Options, method: http.MethodOptions, expectBody: true},
{name: "Trace", register: (*App).Trace, method: http.MethodTrace, expectBody: true},
{name: "Patch", register: (*App).Patch, method: http.MethodPatch, expectBody: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
app := New()
handler := func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Test", r.Method)
w.WriteHeader(http.StatusAccepted)
if r.Method == http.MethodHead {
return
}
_, err := w.Write([]byte("hello from net/http " + r.Method))
assert.NoError(t, err)
}
tt.register(app, "/foo", http.HandlerFunc(handler))
req := httptest.NewRequest(tt.method, "/foo", http.NoBody)
if tt.method == http.MethodConnect {
req.URL.Scheme = "http"
req.URL.Host = "example.com"
}
resp := apptest.Expect(t, app, req, http.StatusAccepted)
require.Equal(t, tt.method, resp.Header.Get("X-Test"))
body := apptest.BodyBytes(t, resp)
if tt.expectBody {
require.Equal(t, "hello from net/http "+tt.method, string(body))
} else {
require.Empty(t, body)
}
})
}
}
func Test_App_Custom_Middleware_404_Should_Not_SetMethodNotAllowed(t *testing.T) {
t.Parallel()
app := New()
app.Use(func(c Ctx) error { return c.SendStatus(404) })
app.Post("/", testEmptyHandler)
resp := apptest.ExpectBody(t, app, "/", 404, "Not Found")
require.Equal(t, MIMETextPlainCharsetUTF8, resp.Header.Get(HeaderContentType))
require.Equal(t, strconv.Itoa(len("Not Found")), resp.Header.Get(HeaderContentLength))
g := app.Group("/with-next", func(c Ctx) error { return c.Status(404).Next() })
g.Post("/", testEmptyHandler)
resp = apptest.ExpectBody(t, app, "/with-next", 404, "Not Found")
require.Equal(t, MIMETextPlainCharsetUTF8, resp.Header.Get(HeaderContentType))
require.Equal(t, strconv.Itoa(len("Not Found")), resp.Header.Get(HeaderContentLength))
}
func Test_App_ServerErrorHandler_SmallReadBuffer(t *testing.T) {
t.Parallel()
app := New(Config{ReadBufferSize: 4096})
app.Get("/", func(_ Ctx) error { panic(errors.New("should never called")) })
request := httptest.NewRequest(MethodGet, "/", http.NoBody)
logHeaderSlice := make([]string, 5000)
request.Header.Set("Very-Long-Header", strings.Join(logHeaderSlice, "-"))
_, err := app.Test(request)
// assert on the error type, not on fasthttp's message wording
require.ErrorAs(t, err, new(*fasthttp.ErrSmallBuffer))
}
func Test_App_Errors(t *testing.T) {
t.Parallel()
app := New(Config{BodyLimit: 4})
app.Get("/", func(_ Ctx) error { return errors.New("hi, i'm an error") })
apptest.ExpectBody(t, app, "/", 500, "hi, i'm an error")
_, err := app.Test(httptest.NewRequest(MethodGet, "/", strings.NewReader("big body")))
if err != nil {
require.ErrorIs(t, err, fasthttp.ErrBodyTooLarge, "app.Test(req)")
}
}
func Test_App_BodyLimit(t *testing.T) {
t.Parallel()
const largerLimit = DefaultBodyLimit*2 + 1024 // slightly above double the default
tests := []struct {
name string
limit int
accepted int // size of a body that must get through
rejected int // size of a body that must be refused
}{
// A limit that is not positive falls back to the default.
{name: "negative", limit: -1, accepted: DefaultBodyLimit - 1, rejected: DefaultBodyLimit + 1},
{name: "more negative", limit: -512, accepted: DefaultBodyLimit - 1, rejected: DefaultBodyLimit + 1},
{name: "zero", limit: 0, accepted: DefaultBodyLimit - 1, rejected: DefaultBodyLimit + 1},
// A body larger than the default but within the custom limit gets through,
// and one above the custom limit is refused.
{name: "larger than default", limit: largerLimit, accepted: DefaultBodyLimit + 512, rejected: largerLimit + 1},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
app := New(Config{BodyLimit: tc.limit})
app.Post("/", func(c Ctx) error { return c.SendStatus(StatusOK) })
largeBody := bytes.Repeat([]byte{'a'}, tc.rejected)
req := httptest.NewRequest(MethodPost, "/", bytes.NewReader(largeBody))
_, err := app.Test(req)
require.ErrorIs(t, err, fasthttp.ErrBodyTooLarge)
smallBody := bytes.Repeat([]byte{'a'}, tc.accepted)
req = httptest.NewRequest(MethodPost, "/", bytes.NewReader(smallBody))
apptest.Expect(t, app, req, StatusOK)
})
}
}
type customConstraint struct{}
func (*customConstraint) Name() string {
return "test"
}
func (*customConstraint) Execute(param string, args ...string) bool {
if param == "test" && len(args) == 1 && args[0] == "test" {
return true
}
if len(args) == 0 && param == "c" {
return true
}
return false
}
func Test_App_CustomConstraint(t *testing.T) {
t.Parallel()
app := New()
app.RegisterCustomConstraint(&customConstraint{})
app.Get("/test/:param<test(test)>", func(c Ctx) error { return c.SendString("test") })
app.Get("/test2/:param<test>", func(c Ctx) error { return c.SendString("test") })
app.Get("/test3/:param<test()>", func(c Ctx) error { return c.SendString("test") })
for path, status := range map[string]int{
"/test/test": 200, "/test/test2": 404, "/test2/c": 200, "/test2/cc": 404, "/test3/cc": 404,
} {
apptest.Expect(t, app, path, status)
}
}
func Test_App_ErrorHandler_Custom(t *testing.T) {
t.Parallel()
app := New(Config{
ErrorHandler: func(c Ctx, _ error) error { return c.Status(200).SendString("hi, i'm a custom error") },
})
app.Get("/", func(_ Ctx) error { return errors.New("hi, i'm an error") })
apptest.ExpectBody(t, app, "/", 200, "hi, i'm a custom error")
}
func Test_App_ErrorHandler_HandlerStack(t *testing.T) {
t.Parallel()
app := New(Config{
ErrorHandler: func(c Ctx, err error) error {
require.Equal(t, "1: USE error", err.Error())
return DefaultErrorHandler(c, err)
},
})
app.Use("/", func(c Ctx) error {
err := c.Next() // call next USE
require.Equal(t, "2: USE error", err.Error())
return errors.New("1: USE error")
}, func(c Ctx) error {
err := c.Next() // call [0] GET
require.Equal(t, "0: GET error", err.Error())
return errors.New("2: USE error")
})
app.Get("/", func(_ Ctx) error { return errors.New("0: GET error") })
apptest.ExpectBody(t, app, "/", 500, "1: USE error")
}
func Test_App_ErrorHandler_RouteStack(t *testing.T) {
t.Parallel()
app := New(Config{
ErrorHandler: func(c Ctx, err error) error {
require.Equal(t, "1: USE error", err.Error())
return DefaultErrorHandler(c, err)
},
})
app.Use("/", func(c Ctx) error {
err := c.Next()
require.Equal(t, "0: GET error", err.Error())
return errors.New("1: USE error") // [2] call ErrorHandler
})
app.Get("/test", func(_ Ctx) error {
return errors.New("0: GET error") // [1] return to USE
})
apptest.ExpectBody(t, app, "/test", 500, "1: USE error")
}
// Test_DefaultErrorHandler pins the response DefaultErrorHandler writes: a
// typed nil error is an internal error, and a wrapped fiber.Error keeps its
// code but answers with the wrapping message.
func Test_DefaultErrorHandler(t *testing.T) {
t.Parallel()
internal := utils.StatusMessage(StatusInternalServerError)
wrapped := fmt.Errorf("auth failed: %w", ErrUnauthorized)
for _, tc := range []struct {
err error
name string
wantBody string
wantStatus int
}{
{name: "typed nil fiber error", err: (*Error)(nil), wantStatus: StatusInternalServerError, wantBody: internal},
{
name: "typed nil custom error", err: (*typedNilHandlerError)(nil),
wantStatus: StatusInternalServerError, wantBody: internal,
},
{name: "wrapped fiber error uses wrapped message", err: wrapped, wantStatus: StatusUnauthorized, wantBody: wrapped.Error()},
} {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
c := apptest.CtxAs[*DefaultCtx](t, New())
require.NotPanics(t, func() { require.NoError(t, DefaultErrorHandler(c, tc.err)) })
require.Equal(t, tc.wantStatus, c.fasthttp.Response.StatusCode())
require.Equal(t, tc.wantBody, string(c.fasthttp.Response.Body()))
})
}
}
func Test_App_serverErrorHandler(t *testing.T) {
t.Parallel()
tests := []struct {
err error
name string
wantBody string
wantStatus int
}{
{name: "internal error", err: errors.New("test err"), wantBody: "test err", wantStatus: StatusBadRequest},
{
name: "typed nil op error", err: (*net.OpError)(nil), wantBody: utils.StatusMessage(StatusBadGateway),
wantStatus: StatusBadGateway,
},
{
name: "network error", err: &net.DNSError{Err: "test error", Name: "test host", IsTimeout: false},
wantBody: utils.StatusMessage(StatusBadGateway), wantStatus: StatusBadGateway,
},
{
name: "unsupported method error", err: fmt.Errorf("error when reading request headers: %w", fasthttp.ErrUnsupportedRequestMethod),
wantBody: utils.StatusMessage(StatusNotImplemented), wantStatus: StatusNotImplemented,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
app := New()
c := apptest.CtxAs[*DefaultCtx](t, app)
require.NotPanics(t, func() { app.serverErrorHandler(c.fasthttp, tc.err) })
require.Equal(t, tc.wantBody, string(c.fasthttp.Response.Body()))
require.Equal(t, tc.wantStatus, c.fasthttp.Response.StatusCode())
})
}
}
func Test_App_Nested_Params(t *testing.T) {
t.Parallel()
app := New()
app.Get("/test", func(c Ctx) error { return c.Status(400).Send([]byte("Should move on")) })
app.Get("/test/:param", func(c Ctx) error { return c.Status(400).Send([]byte("Should move on")) })
app.Get("/test/:param/test", func(c Ctx) error { return c.Status(400).Send([]byte("Should move on")) })
app.Get("/test/:param/test/:param2", func(c Ctx) error { return c.Status(200).Send([]byte("Good job")) })
apptest.Expect(t, app, "/test/john/test/doe", 200)
}
func Test_App_Use_Params(t *testing.T) {
t.Parallel()
app := New()
app.Use("/prefix/:param", func(c Ctx) error {
require.Equal(t, "john", c.Params("param"))
return nil
})
app.Use("/foo/:bar?", func(c Ctx) error {
require.Equal(t, "foobar", c.Params("bar", "foobar"))
return nil
})
app.Use("/:param/*", func(c Ctx) error {
require.Equal(t, "john", c.Params("param"))
require.Equal(t, "doe", c.Params("*"))
return nil
})
apptest.Expect(t, app, "/prefix/john", 200)
apptest.Expect(t, app, "/john/doe", 200)
apptest.Expect(t, app, "/foo", 200)
require.PanicsWithValue(t, "use: invalid handler func()\n", func() {
app.Use("/:param/*", func() {
// this should panic
})
})
}
func Test_App_Use_PanicsOnDroppedArguments(t *testing.T) {
t.Parallel()
deny := func(c Ctx) error { return c.SendStatus(StatusUnauthorized) }
guardApp := New()
guardApp.Use(deny)
for kind, use := range map[string]func(app *App, args ...any){
"app": func(app *App, args ...any) { app.Use(args...) },
"group": func(app *App, args ...any) { app.Group("/g").Use(args...) },
"domain": func(app *App, args ...any) { app.Domain("example.com").Use(args...) },
} {
for _, tc := range []struct {
name string
args []any
}{
{name: "prefix, handler, sub-app", args: []any{"/admin", deny, New()}},
{name: "prefix, sub-app, handler", args: []any{"/admin", New(), deny}},
{name: "handler, sub-app", args: []any{deny, New()}},
{name: "prefixes, handler, sub-app", args: []any{[]string{"/a", "/b"}, deny, New()}},
{name: "prefix, two sub-apps", args: []any{"/admin", guardApp, New()}},
{name: "two prefixes, handler", args: []any{"/admin", "/internal", deny}},
{name: "prefix, prefixes, handler", args: []any{"/admin", []string{"/internal"}, deny}},
{name: "two lists of prefixes, handler", args: []any{[]string{"/a"}, []string{"/b"}, deny}},
} {
require.Panics(t, func() { use(New(), tc.args...) }, "%s: %s", kind, tc.name)
}
}
// separate calls keep working
sub := New()
sub.Get("/panel", func(c Ctx) error { return c.SendString("panel") })
app := New()
app.Use("/admin", deny)
app.Use("/admin", sub)
apptest.Expect(t, app, "/admin/panel", StatusUnauthorized)
}
func Test_App_Use_UnescapedPath(t *testing.T) {
t.Parallel()
app := New(Config{UnescapePath: true, CaseSensitive: true})
app.Use("/cRéeR/:param", func(c Ctx) error {
require.Equal(t, "/cRéeR/اختبار", c.Path())
return c.SendString(c.Params("param"))
})
app.Use("/abc", func(c Ctx) error {
require.Equal(t, "/AbC", c.Path())
return nil
})
apptest.ExpectBody(t, app, "/cR%C3%A9eR/%D8%A7%D8%AE%D8%AA%D8%A8%D8%A7%D8%B1", StatusOK, "اختبار")
// with lowercase letters
apptest.Expect(t, app, "/cr%C3%A9er/%D8%A7%D8%AE%D8%AA%D8%A8%D8%A7%D8%B1", StatusNotFound)
}
func Test_App_Use_CaseSensitive(t *testing.T) {
t.Parallel()
app := New(Config{CaseSensitive: true})
app.Use("/abc", func(c Ctx) error { return c.SendString(c.Path()) })
// wrong letters in the requested route -> 404
apptest.Expect(t, app, "/AbC", StatusNotFound)
// right letters in the requested route -> 200
apptest.Expect(t, app, "/abc", StatusOK)
// with case-insensitive matching the handler still sees the path as requested
app.config.CaseSensitive = false
apptest.ExpectBody(t, app, "/AbC", StatusOK, "/AbC")
}
func Test_App_Use_MultiplePrefix(t *testing.T) {
t.Parallel()
app := New()
app.Use([]string{"/john", "/doe"}, func(c Ctx) error { return c.SendString(c.Path()) })
g := app.Group("/test")
g.Use([]string{"/john", "/doe"}, func(c Ctx) error { return c.SendString(c.Path()) })
for _, path := range []string{"/john", "/doe", "/test/john", "/test/doe"} {
apptest.ExpectBody(t, app, path, StatusOK, path)
}
}
func Test_Group_Use_NoBoundary(t *testing.T) {
t.Parallel()
app := New()
grp := app.Group("/api")
grp.Use("/foo", func(c Ctx) error { return c.SendStatus(StatusOK) })
apptest.Expect(t, app, "/api/foo/bar", StatusOK)
apptest.Expect(t, app, "/api/foobar", StatusNotFound)
}
// Test_App_Use_StrictRouting pins how a trailing slash is matched, on the app
// and on a group: a Use prefix without StrictRouting ignores it, a route with
// StrictRouting does not.
func Test_App_Use_StrictRouting(t *testing.T) {
t.Parallel()
handler := func(c Ctx) error { return c.SendString(c.Path()) }
for _, tc := range []struct {
want map[string]int // path -> status
name string
strict bool // StrictRouting with Get routes, instead of Use prefixes without it
}{
{name: "Use without StrictRouting", want: map[string]int{"/abc/": StatusOK, "/abc": StatusOK, "/foo": StatusOK, "/foo/": StatusOK}},
{
name: "Get with StrictRouting", strict: true,
want: map[string]int{"/abc/": StatusNotFound, "/abc": StatusOK, "/foo": StatusNotFound, "/foo/": StatusOK},
},
} {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
app := New(Config{StrictRouting: tc.strict})
if tc.strict {
app.Get("/abc", handler)
app.Group("/foo").Get("/", handler)
} else {
app.Use("/abc", handler)
app.Group("/foo").Use("/", handler)
}
for path, status := range tc.want {
apptest.Expect(t, app, path, status)
}
})
}
}
func Test_App_Add_Method_Test(t *testing.T) {
t.Parallel()
methods := append(DefaultMethods, "JOHN") //nolint:gocritic // We want a new slice here
app := New(Config{RequestMethods: methods})
app.Add([]string{"JOHN"}, "/john", testEmptyHandler)
apptest.Expect(t, app, apptest.Req("JOHN", "/john"), StatusOK)
apptest.Expect(t, app, "/john", StatusMethodNotAllowed)
apptest.Expect(t, app, apptest.Req("UNKNOWN", "/john"), StatusNotImplemented)
// Add a new method
require.Panics(t, func() { app.Add([]string{"JANE"}, "/jane", testEmptyHandler) })
}
func Test_App_All_Method_Test(t *testing.T) {
t.Parallel()
methods := append(DefaultMethods, "JOHN") //nolint:gocritic // We want a new slice here
app := New(Config{RequestMethods: methods})
app.All("/doe", testEmptyHandler)
apptest.Expect(t, app, apptest.Req("JOHN", "/doe"), StatusOK)
// Add a new method
require.Panics(t, func() { app.Add([]string{"JANE"}, "/jane", testEmptyHandler) })
}
func Test_App_GETOnly(t *testing.T) {
t.Parallel()
app := New(Config{GETOnly: true})
app.Post("/", func(c Ctx) error { return c.SendString("Hello 👋!") })
apptest.Expect(t, app, apptest.Req(MethodPost, "/"), StatusMethodNotAllowed)
}
func Test_App_RefusedRequest_Middleware_Status(t *testing.T) {
t.Parallel()
app := New(Config{BodyLimit: 8})
observed := make(chan int, 1)
app.Use(func(c Ctx) error {
err := c.Next()
observed <- c.Response().StatusCode()
return err
})
app.Post("/", func(c Ctx) error { return c.SendString("Hello 👋!") })
req := httptest.NewRequest(MethodPost, "/", strings.NewReader(strings.Repeat("x", 64)))
_, err := app.Test(req)
require.ErrorIs(t, err, fasthttp.ErrBodyTooLarge)
require.Equal(t, StatusRequestEntityTooLarge, <-observed, "Status code seen by middleware")
}
// The replay would run a Use handler that ends the chain with the method GETOnly refused.
func Test_App_GETOnly_RefusedMethodIsNotReplayed(t *testing.T) {
t.Parallel()
app := New(Config{GETOnly: true})
var ran []string
app.Use("/api", func(c Ctx) error {
ran = append(ran, c.Method())
return c.SendString("done")
})
resp := apptest.Expect(t, app, apptest.Req(MethodPost, "/api/jobs/7/cancel"), StatusMethodNotAllowed)
require.Equal(t, "GET, HEAD", resp.Header.Get(HeaderAllow))
require.Empty(t, ran)
apptest.Expect(t, app, "/api/jobs/7", StatusOK)
require.Equal(t, []string{MethodGet}, ran)
}
// The method GETOnly refused must not reach a route when the ErrorHandler restarts routing.
func Test_App_GETOnly_RestartRoutingSkipsRoutes(t *testing.T) {
t.Parallel()
ran := make(chan string, 1)
app := New(Config{GETOnly: true, ErrorHandler: func(c Ctx, err error) error {
c.Path("/error")
if restartErr := c.RestartRouting(); restartErr != nil {
return restartErr
}
return DefaultErrorHandler(c, err)
}})
app.Post("/error", func(c Ctx) error {
ran <- c.Method()
return nil
})
apptest.ExpectBody(t, app, apptest.Req(MethodPost, "/jobs"), StatusMethodNotAllowed, "Method Not Allowed")
require.Empty(t, ran)
}
// The replay skips a guard registered as a route, and SendStatus keeps a body already written.
func Test_App_RefusedRequest_ChainBodyIsNotSent(t *testing.T) {
t.Parallel()
app := New(Config{
BodyLimit: 16,
ErrorHandler: func(c Ctx, err error) error {
var fiberErr *Error
if !errors.As(err, &fiberErr) {
return err
}
return c.SendStatus(fiberErr.Code)
},
})
app.All("/admin/*", func(c Ctx) error { return c.SendStatus(StatusUnauthorized) })
app.Use(func(c Ctx) error { return c.SendString("TOP-SECRET") })
ln := startRawServer(t, app)
const get = "GET /admin/secret.txt HTTP/1.1\r\nHost: example.com\r\n"
rawExpectStatus(t, ln, get+"\r\n", StatusUnauthorized)
resp := rawExpectStatus(t, ln, get+"Content-Length: 99999\r\n\r\n", StatusRequestEntityTooLarge)
require.Equal(t, "Request Entity Too Large", resp.body)
}
// fasthttp panics when it releases a refused request's RequestCtx that holds a timeout response, so the chain and
// the ErrorHandler get one of their own, and a timeout there is answered with its timeout response.
func Test_App_RefusedRequest_ChainTimesOut(t *testing.T) {
t.Parallel()
app := New(Config{
BodyLimit: 16,
ErrorHandler: func(c Ctx, err error) error {
if c.Path() == "/restart" {
c.Path("/slow")
return c.RestartRouting()
}
return DefaultErrorHandler(c, err)
},
})
app.Use(func(c Ctx) error {
c.Set("X-Chain", "ran")
return c.Next()
})
app.Use("/slow", func(c Ctx) error {
c.RequestCtx().TimeoutError("late")
return nil
})
ln := startRawServer(t, app)
const tooLarge = " HTTP/1.1\r\nHost: example.com\r\nContent-Length: 99999\r\n\r\n"
for _, target := range []string{"/slow", "/restart"} {
resp := rawExpectStatus(t, ln, "POST "+target+tooLarge, StatusRequestTimeout)
require.Equal(t, "late", resp.body, target)
require.Empty(t, resp.header.Get("X-Chain"), target)
}
resp := rawExpectStatus(t, ln, "POST /"+tooLarge, StatusRequestEntityTooLarge)
require.Equal(t, "ran", resp.header.Get("X-Chain"))
}
// Route handlers stay skipped for a refused request when the ErrorHandler restarts routing, also without a Use chain.
func Test_App_RefusedRequest_RestartSkipsRoutes(t *testing.T) {
t.Parallel()
app := New(Config{BodyLimit: 16, ErrorHandler: func(c Ctx, err error) error {
c.Path("/slow")
if restartErr := c.RestartRouting(); restartErr != nil {
err = restartErr
}
return DefaultErrorHandler(c, err)
}})
ran := make(chan struct{}, 1)
app.Post("/slow", func(c Ctx) error {
ran <- struct{}{}
c.RequestCtx().TimeoutError("late")
return nil
})
ln := startRawServer(t, app)
rawExpectStatus(t, ln, "POST /slow HTTP/1.1\r\nHost: example.com\r\nContent-Length: 99999\r\n\r\n", StatusRequestEntityTooLarge)
require.Empty(t, ran)
}
// A custom ErrorHandler can time out a refused request without a Use chain too, also a mounted app's one.
func Test_App_RefusedRequest_ErrorHandlerTimesOut(t *testing.T) {
t.Parallel()
timingOut := func() *App {
app := New(Config{BodyLimit: 16, ErrorHandler: func(c Ctx, _ error) error {
c.RequestCtx().TimeoutError("late")
return nil
}})
app.Post("/", func(c Ctx) error { return c.SendString("ok") })
return app
}
for _, tc := range []struct {
app func() *App
name string
target string
}{
{name: "route", app: timingOut, target: "POST /"},
{name: "method without routes", app: timingOut, target: "PURGE /"},
{name: "mounted app", target: "POST /sub", app: func() *App {
root := New(Config{BodyLimit: 16})
root.Use("/sub", timingOut())
return root
}},
{name: "domain mounted app", target: "POST /sub", app: func() *App {
root := New(Config{BodyLimit: 16})
root.Domain("example.com").Use("/sub", timingOut())
return root
}},
} {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
ln := startRawServer(t, tc.app())
resp := rawExpectStatus(t, ln, tc.target+" HTTP/1.1\r\nHost: example.com\r\nContent-Length: 99999\r\n\r\n", StatusRequestTimeout)
require.Equal(t, "late", resp.body)
})
}
}
// closedLocal is a request-local value that reports being closed.
type closedLocal chan struct{}
func (l closedLocal) Close() error {
close(l)
return nil
}
// The answer is copied back from the RequestCtx the chain ran on: its headers, a streamed body, and the locals that
// are closed with the request.
func Test_App_RefusedRequest_StreamedAnswer(t *testing.T) {
t.Parallel()
app := New(Config{
BodyLimit: 16,
ErrorHandler: func(c Ctx, err error) error {
return c.Status(StatusRequestEntityTooLarge).SendStream(strings.NewReader(err.Error()))
},
})
closed := make(closedLocal)
app.Use(func(c Ctx) error {
c.Set("X-Chain", "ran")
c.Locals("local", closed)
return c.Next()
})
ln := startRawServer(t, app)
resp := rawExpectStatus(t, ln, "POST / HTTP/1.1\r\nHost: example.com\r\nContent-Length: 99999\r\n\r\n", StatusRequestEntityTooLarge)
require.Equal(t, "Request Entity Too Large", resp.body)
require.Equal(t, "ran", resp.header.Get("X-Chain"))
require.True(t, resp.closes)
apptest.Recv(t, closed, time.Second, "the local is closed")
}
// A refused request with no Use chain and the default ErrorHandler is answered in place, with few allocations.
// AllocsPerRun panics under t.Parallel, so this test stays sequential.
func Test_App_RefusedRequest_WithoutChainAnswersInPlace(t *testing.T) {
app := New()
app.Post("/", func(c Ctx) error { return c.SendString("ok") })
app.Handler()
fctx := &fasthttp.RequestCtx{}
fctx.Request.Header.SetMethod(MethodPost)
allocs := testing.AllocsPerRun(20, func() { app.serverErrorHandler(fctx, fasthttp.ErrBodyTooLarge) })
require.Equal(t, StatusRequestEntityTooLarge, fctx.Response.StatusCode())
require.LessOrEqual(t, allocs, 8.0)
}
// A header the chain sets under a name of the request's trailer section replaces the client's line in the replay too.
func Test_App_RefusedRequest_DropsTrailers(t *testing.T) {
t.Parallel()
for name, newApp := range map[string]func(...Config) *App{"default": New, "custom ctx": ctxTestACustomApp} {
t.Run(name, func(t *testing.T) {
t.Parallel()
app := newApp()
var fiberRead, peekRead, netRead []string
app.Use(func(c Ctx) error {
c.Request().Header.Set("X-User", "guest")
return c.Next()
}, func(c Ctx) error {
fiberRead = append(fiberRead, utils.CopyString(c.Get("X-User")))
peekRead = append(peekRead, string(c.Request().Header.Peek("X-User")))
return c.Next()
}, func(_ http.ResponseWriter, r *http.Request) {
netRead = append(netRead, utils.CopyString(r.Header.Get("X-User")))
})
ln := startRawServer(t, app)
const (
head = "POST / HTTP/1.1\r\nHost: example.com\r\nX-User: admin\r\n"
tooLarge = "Content-Length: 99999999\r\n\r\n"
chunked = "Transfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n0\r\n"
)
rawExpectStatus(t, ln, head+"Trailer: X-User\r\n"+tooLarge, StatusRequestEntityTooLarge)
rawExpectStatus(t, ln, head+"Trailer: X-User\r\n"+chunked+"Host: a\r\n\r\n", StatusBadRequest)
rawExpectStatus(t, ln, head+chunked+"X-User: root\r\nHost: a\r\n\r\n", StatusBadRequest)
want := []string{"guest", "guest", "guest"}
require.Equal(t, want, fiberRead)
require.Equal(t, want, peekRead)
require.Equal(t, want, netRead)
// Past the names dropTrailers takes, the chain does not run, as for a request that is served.
names := []string{"X-User"}
for i := range fieldname.MaxTrailers {
names = append(names, "X-"+strconv.Itoa(i))
}
rawExpectStatus(t, ln, head+"Trailer: "+strings.Join(names, ", ")+"\r\n"+tooLarge, StatusRequestEntityTooLarge)
require.Len(t, netRead, len(want))
})
}
}
// An ErrorHandler that writes only a body used to answer a transport-refused
// request with 200. Seeding the status changes that, so pin it.
func Test_App_GETOnly_ErrorHandler_WithoutStatus(t *testing.T) {
t.Parallel()
app := New(Config{
GETOnly: true,
ErrorHandler: func(c Ctx, err error) error { return c.SendString(err.Error()) },
})
app.Post("/", func(c Ctx) error { return c.SendString("Hello 👋!") })
resp := apptest.Expect(t, app, apptest.Req(MethodPost, "/"), StatusMethodNotAllowed)
body := apptest.Body(t, resp)
require.Equal(t, "Method Not Allowed", body, "Body")
}
// RFC 9110 §15.5.6: a 405 lists the allowed methods, even when a custom
// ErrorHandler rewrites the response.
func Test_App_GETOnly_Allow(t *testing.T) {
t.Parallel()
for name, config := range map[string]Config{
"default error handler": {GETOnly: true},
"custom error handler": {
GETOnly: true,