-
-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathres.go
More file actions
1623 lines (1416 loc) · 52.9 KB
/
Copy pathres.go
File metadata and controls
1623 lines (1416 loc) · 52.9 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
package fiber
import (
"bufio"
"bytes"
"fmt"
"html/template"
"io"
"io/fs"
"net/http"
"os"
pathpkg "path"
"path/filepath"
"reflect"
"slices"
"strings"
"time"
"unicode"
"unicode/utf8"
internalcookie "github.com/gofiber/fiber/v3/internal/cookie"
"github.com/gofiber/fiber/v3/internal/fieldname"
"github.com/gofiber/fiber/v3/internal/headerlist"
"github.com/gofiber/fiber/v3/internal/quotedstring"
"github.com/gofiber/utils/v2"
"github.com/valyala/bytebufferpool"
"github.com/valyala/fasthttp"
)
// SendFile defines configuration options when to transfer file with SendFile.
type SendFile struct {
// FS is the file system to serve the static files from.
// You can use interfaces compatible with fs.FS like embed.FS, os.DirFS etc.
//
// Optional. Default: nil
FS fs.FS
// When set to true, the server tries minimizing CPU usage by caching compressed files.
// This works differently than the github.com/gofiber/compression middleware.
// You have to set Content-Encoding header to compress the file.
// Available compression methods are gzip, br, and zstd.
//
// Optional. Default: false
Compress bool `json:"compress"`
// When set to true, enables byte range requests.
//
// Optional. Default: false
ByteRange bool `json:"byte_range"`
// When set to true, enables direct download.
//
// Optional. Default: false
Download bool `json:"download"`
// Expiration duration for inactive file handlers.
// Use a negative time.Duration to disable it.
//
// Optional. Default: 10 * time.Second
CacheDuration time.Duration `json:"cache_duration"`
// The value for the Cache-Control HTTP-header
// that is set on the file response. MaxAge is defined in seconds.
//
// Optional. Default: 0
MaxAge int `json:"max_age"`
}
// sendFileStore is used to keep the SendFile configuration and the handler.
type sendFileStore struct {
handler fasthttp.RequestHandler
cacheControlValue string
config SendFile
}
// configEqual compares the current SendFile config with the new one
// and returns true if they are equal.
//
// Here we don't use reflect.DeepEqual because it is quite slow compared to manual comparison.
func (sf *sendFileStore) configEqual(cfg SendFile) bool {
if !sameFS(sf.config.FS, cfg.FS) {
return false
}
if sf.config.Compress != cfg.Compress {
return false
}
if sf.config.ByteRange != cfg.ByteRange {
return false
}
if sf.config.Download != cfg.Download {
return false
}
if sf.config.CacheDuration != cfg.CacheDuration {
return false
}
if sf.config.MaxAge != cfg.MaxAge {
return false
}
return true
}
// sameFS reports whether two file systems are the same one. Values of an
// uncomparable dynamic type (fstest.MapFS) are compared by what they reference.
func sameFS(a, b fs.FS) bool {
if a == nil || b == nil {
return a == nil && b == nil
}
va, vb := reflect.ValueOf(a), reflect.ValueOf(b)
if va.Type() != vb.Type() {
return false
}
if va.Type().Comparable() {
return a == b
}
switch va.Kind() {
case reflect.Slice:
// Pointer() is &elem[0] and ignores the length, so two prefixes of one
// backing array would otherwise look like the same file system.
return va.Pointer() == vb.Pointer() && va.Len() == vb.Len()
case reflect.Map, reflect.Chan, reflect.Pointer, reflect.UnsafePointer:
return va.Pointer() == vb.Pointer()
default:
// A func's pointer is its code entry, shared by every closure over the
// same body, so two file systems capturing different roots would look
// like one. Treat them as distinct rather than serve the wrong root.
return false
}
}
// Cookie defines the values used when configuring cookies emitted by
// DefaultRes.Cookie.
type Cookie struct {
Expires time.Time `json:"expires"` // The expiration date of the cookie
Name string `json:"name"` // The name of the cookie
Value string `json:"value"` // The value of the cookie
Path string `json:"path"` // Specifies a URL path which is allowed to receive the cookie
Domain string `json:"domain"` // Specifies the domain which is allowed to receive the cookie
SameSite string `json:"same_site"` // Controls whether or not a cookie is sent with cross-site requests
MaxAge int `json:"max_age"` // The maximum age (in seconds) of the cookie
Secure bool `json:"secure"` // Indicates that the cookie should only be transmitted over a secure HTTPS connection
HTTPOnly bool `json:"http_only"` // Indicates that the cookie is accessible only through the HTTP protocol
Partitioned bool `json:"partitioned"` // Indicates if the cookie is stored in a partitioned cookie jar
SessionOnly bool `json:"session_only"` // Indicates if the cookie is a session-only cookie
}
// ResFmt associates a Content Type to a fiber.Handler for c.Format
type ResFmt struct {
Handler func(Ctx) error
MediaType string
}
// DefaultRes is the default implementation of Res used by DefaultCtx.
//
//go:generate ifacemaker --file res.go --struct DefaultRes --iface Res --pkg fiber --output res_interface_gen.go --not-exported true --iface-comment "Res is an interface for response-related Ctx methods."
type DefaultRes struct {
c *DefaultCtx
}
// App returns the *App reference to the instance of the Fiber application
func (r *DefaultRes) App() *App {
return r.c.app
}
// Append the specified value to the HTTP response header field.
// If the header is not already set, it creates the header with the specified value.
// Empty values are skipped: a sender must not generate empty list elements
// (RFC 9110 Section 5.6.1.2).
// Members are compared byte-exactly, because some lists (Link, Cache-Control)
// are not all field names. For Vary field names, use Vary, which folds case.
func (r *DefaultRes) Append(field string, values ...string) {
if len(values) == 0 {
return
}
// Consider all existing field lines combined (RFC 9110 Section 5.2) so
// the dedup check sees members added on later lines via Header.Add.
existing, multiLine := peekJoinedResponseHeader(&r.c.fasthttp.Response.Header, field)
updated := headerlist.AppendUnique(utils.UnsafeString(existing), values)
if updated == "" {
return
}
if multiLine {
// Set only rewrites the first field line; drop the extras that are
// now folded into the combined value.
r.c.fasthttp.Response.Header.Del(field)
}
r.Set(field, updated)
}
// varyAccept is the field list Format and AutoFormat add to Vary. It is
// hoisted because a fresh "..." argument list is a slice the compiler has to
// heap-allocate — Vary's result reaches the header store, so escape analysis
// marks the elements as leaking even though fasthttp copies the bytes — while
// passing an existing slice hands over its backing array. Both callers are
// methods on *DefaultRes, so the Vary they reach is the one below and not
// something a custom Res could substitute; it only reads the field list, which
// makes sharing one array across every request safe.
var varyAccept = []string{HeaderAccept}
func sanitizeFilename(filename string) string {
// unicode.IsControl matches C0, DEL and the C1 range. The first two are
// single bytes utils.IndexControl finds word-at-a-time, and C1 can only
// appear in non-ASCII input, so an all-ASCII name that clears both scans
// is clean without decoding a rune. That pair measures 24-58% faster than
// the rune loop across 13- to 90-byte names.
if utils.IndexControl(filename) == -1 && utils.IsASCII(filename) {
return utils.TrimSpace(filename)
}
for _, r := range filename {
if unicode.IsControl(r) {
b := make([]byte, 0, len(filename))
for _, rr := range filename {
if !unicode.IsControl(rr) {
b = utf8.AppendRune(b, rr)
}
}
return utils.TrimSpace(string(b))
}
}
return utils.TrimSpace(filename)
}
func fallbackFilenameIfInvalid(filename string) string {
if filename == "" || filename == "." {
return "download"
}
return filename
}
// isExtValueAttrChar reports whether c is an attr-char per RFC 8187 §3.2:
// ALPHA / DIGIT / "!" / "#" / "$" / "&" / "+" / "-" / "." / "^" / "_" /
// "`" / "|" / "~". Every other byte of an ext-value must be pct-encoded.
func isExtValueAttrChar(c byte) bool {
switch {
case c >= 'a' && c <= 'z', c >= 'A' && c <= 'Z', c >= '0' && c <= '9':
return true
}
switch c {
case '!', '#', '$', '&', '+', '-', '.', '^', '_', '`', '|', '~':
return true
default:
return false
}
}
// encodeExtValue percent-encodes s as the value-chars of an RFC 8187
// ext-value. URL path/query escaping is not sufficient here: it leaves
// bytes such as ':', '=', and '@' bare, which the ext-value grammar forbids.
func encodeExtValue(s string) string {
const hex = "0123456789ABCDEF"
b := make([]byte, 0, len(s))
for i := 0; i < len(s); i++ {
c := s[i]
if isExtValueAttrChar(c) {
b = append(b, c)
} else {
b = append(b, '%', hex[c>>4], hex[c&0x0F])
}
}
return string(b)
}
// contentDispositionAttachment builds an RFC 6266 Content-Disposition value
// for a sanitized filename: the filename parameter is a quoted-string with
// RFC 9110 §5.6.4 escaping, and non-ASCII names additionally carry an
// RFC 8187 filename* ext-value for interoperability.
func contentDispositionAttachment(fname string) string {
disp := `attachment; filename="` + quotedstring.Escape(fname) + `"`
if !utils.IsASCII(fname) {
disp += `; filename*=UTF-8''` + encodeExtValue(fname)
}
return disp
}
// Add appends the value as a new field line, where Append folds values into one
// comma-separated line. The headers fasthttp keeps in a slot of their own are
// the exception: Content-Type, Server and the rest are replaced and Date and TE
// ignored, though Set-Cookie is slotted and does append. Use Cookie for that.
func (r *DefaultRes) Add(key, val string) {
r.c.fasthttp.Response.Header.Add(key, val)
}
// Attachment sets the HTTP response Content-Disposition header field to attachment.
func (r *DefaultRes) Attachment(filename ...string) {
if len(filename) > 0 {
fname := filepath.Base(filename[0])
fname = sanitizeFilename(fname)
fname = fallbackFilenameIfInvalid(fname)
r.Type(filepath.Ext(fname))
r.setCanonical(HeaderContentDisposition, contentDispositionAttachment(fname))
return
}
r.setCanonical(HeaderContentDisposition, "attachment")
}
// ClearCookie expires a specific cookie by key on the client side.
// If no key is provided it expires all cookies that came with the request.
func (r *DefaultRes) ClearCookie(key ...string) {
request := &r.c.fasthttp.Request
response := &r.c.fasthttp.Response
if len(key) > 0 {
for i := range key {
response.Header.DelClientCookie(key[i])
}
return
}
for k := range request.Header.Cookies() {
response.Header.DelClientCookieBytes(k)
}
}
// RequestCtx returns *fasthttp.RequestCtx that carries a deadline
// a cancellation signal, and other values across API boundaries.
func (r *DefaultRes) RequestCtx() *fasthttp.RequestCtx {
return r.c.fasthttp
}
// Cookie sets a cookie by passing a cookie struct.
//
// The argument is treated as read-only: the normalization this method applies
// (default Path, SessionOnly, and the Secure implied by SameSite=None or
// Partitioned) happens on a local copy, so a caller may reuse the same *Cookie
// template across requests.
func (r *DefaultRes) Cookie(cookie *Cookie) {
c := *cookie
if c.Path == "" {
c.Path = "/"
}
if c.SessionOnly {
c.MaxAge = 0
c.Expires = time.Time{}
}
sameSite, _ := internalcookie.ParseSameSite(c.SameSite)
if sameSite.RequiresSecure {
// SameSite=None requires Secure=true per RFC and browser requirements
c.Secure = true
}
// Partitioned requires Secure=true per CHIPS spec
if c.Partitioned {
c.Secure = true
}
// Validate before fasthttp's setters can silently replace CR/LF or semicolons;
// rejection, rather than mutation, is this API's existing contract.
hc := &http.Cookie{ //nolint:gosec // G124: http.Cookie missing or has insecure Secure, HttpOnly, or SameSite attribute
Name: c.Name,
Value: c.Value,
Path: c.Path,
Domain: c.Domain,
Expires: c.Expires,
MaxAge: c.MaxAge,
Secure: c.Secure,
HttpOnly: c.HTTPOnly,
SameSite: sameSite.HTTPMode,
Partitioned: c.Partitioned,
}
if err := hc.Valid(); err != nil {
// invalid cookies are ignored, same approach as net/http
return
}
// create fasthttp cookie
fcookie := fasthttp.AcquireCookie()
fcookie.SetKey(hc.Name)
fcookie.SetValue(hc.Value)
fcookie.SetPath(hc.Path)
fcookie.SetDomain(hc.Domain)
if !c.SessionOnly {
fcookie.SetMaxAge(hc.MaxAge)
fcookie.SetExpire(hc.Expires)
}
fcookie.SetSecure(hc.Secure)
fcookie.SetHTTPOnly(hc.HttpOnly)
fcookie.SetSameSite(sameSite.FastHTTPMode)
fcookie.SetPartitioned(hc.Partitioned)
// Set resp header
r.c.fasthttp.Response.Header.SetCookie(fcookie)
fasthttp.ReleaseCookie(fcookie)
}
// GetCookie reads back a cookie this response is set to send, false when the
// name is unset or its value does not parse. Names are case-sensitive and a
// repeat resolves to the first. Writing the copy back through Cookie stamps
// Path=/ on a cookie that carried none, widening its scope — set Path first.
func (r *DefaultRes) GetCookie(name string) (*Cookie, bool) {
header := &r.c.fasthttp.Response.Header
fcookie := fasthttp.AcquireCookie()
defer fasthttp.ReleaseCookie(fcookie)
for key, value := range header.Cookies() {
if string(key) != name {
continue
}
// Parsed from the yielded value rather than looked up again by name: the
// lookup discards the parse error, turning a Set-Cookie whose attributes
// fail to parse into one that silently lost its Path and flags.
if fcookie.ParseBytes(value) != nil {
return nil, false
}
return responseCookie(fcookie, value), true
}
return nil, false
}
// GetCookies returns a copy of every cookie this response is set to send, in
// order, or nil when there are none. Repeated names are kept apart, and an
// unparsable one is skipped. For what the client sent, use Req.Cookies.
//
// Named for GetCookie beside it rather than Cookies, which would collide with
// Req.Cookies under a different signature and stop Ctx satisfying Res.
func (r *DefaultRes) GetCookies() []*Cookie {
header := &r.c.fasthttp.Response.Header
fcookie := fasthttp.AcquireCookie()
defer fasthttp.ReleaseCookie(fcookie)
var cookies []*Cookie
// Each entry is parsed where it is found: resolving the name against the
// header again answers with the first cookie of that name once per entry,
// hiding every later one behind a duplicate of the first.
for _, value := range header.Cookies() {
if fcookie.ParseBytes(value) != nil {
continue
}
cookies = append(cookies, responseCookie(fcookie, value))
}
return cookies
}
// cookieAttrPresent reports whether a Set-Cookie value carries the named
// attribute. RFC 6265 Section 4.1.1 excludes ";" from cookie-value, so splitting
// on it is safe; the first element is the name=value pair and is skipped.
func cookieAttrPresent(value []byte, attr string) bool {
_, rest, found := utils.CutByte(value, ';')
if !found {
return false
}
for len(rest) > 0 {
part := rest
if i := bytes.IndexByte(rest, ';'); i >= 0 {
part, rest = rest[:i], rest[i+1:]
} else {
rest = nil
}
name, _, _ := utils.CutByte(part, '=')
if utils.EqualFold(utils.UnsafeString(utils.TrimSpace(name)), attr) {
return true
}
}
return false
}
// responseCookie converts a parsed Set-Cookie back into the Cookie Res.Cookie
// accepts. fasthttp writes a deletion as "max-age=0" and parses it back as 0,
// so raw is consulted to tell that from an absent attribute.
func responseCookie(fcookie *fasthttp.Cookie, raw []byte) *Cookie {
cookie := &Cookie{
Name: string(fcookie.Key()),
Value: string(fcookie.Value()),
Path: string(fcookie.Path()),
Domain: string(fcookie.Domain()),
Expires: fcookie.Expire(),
MaxAge: fcookie.MaxAge(),
Secure: fcookie.Secure(),
HTTPOnly: fcookie.HTTPOnly(),
SameSite: internalcookie.FormatSameSite(fcookie.SameSite()),
Partitioned: fcookie.Partitioned(),
}
if cookie.MaxAge == 0 && cookieAttrPresent(raw, "max-age") {
cookie.MaxAge = -1
}
cookie.SessionOnly = cookie.MaxAge == 0 && cookie.Expires.IsZero()
return cookie
}
// Download transfers the file from path as an attachment.
// Typically, browsers will prompt the user for download.
// By default, the Content-Disposition header filename= parameter is the filepath (this typically appears in the browser dialog).
// Override this default with the filename parameter.
func (r *DefaultRes) Download(file string, filename ...string) error {
var fname string
if len(filename) > 0 {
fname = filepath.Base(filename[0])
} else {
fname = filepath.Base(file)
}
fname = sanitizeFilename(fname)
fname = fallbackFilenameIfInvalid(fname)
r.setCanonical(HeaderContentDisposition, contentDispositionAttachment(fname))
return r.SendFile(file)
}
// Response return the *fasthttp.Response object
// This allows you to use all fasthttp response methods
// https://godoc.org/github.com/valyala/fasthttp#Response
func (r *DefaultRes) Response() *fasthttp.Response {
return &r.c.fasthttp.Response
}
// formatDefaultMediaType is the sentinel MediaType marking a Format handler as
// the fallback. It is not a media type and is never emitted as a Content-Type.
const formatDefaultMediaType = "default"
// Format performs content-negotiation on the Accept HTTP header.
// It uses Accepts to select a proper format and calls the matching
// user-provided handler function.
// If no accepted format is found, and a format with MediaType "default" is given,
// that default handler is called. If no format is found and no default is given,
// StatusNotAcceptable is sent.
func (r *DefaultRes) Format(handlers ...ResFmt) error {
if len(handlers) == 0 {
return ErrNoHandlers
}
for i, h := range handlers {
if h.Handler == nil {
return fmt.Errorf("format handler is nil for media type %q at index %d", h.MediaType, i)
}
}
// Handlers must see the custom context when the app uses one, as Next does.
handlerCtx := r.c.ctxForHandlers()
r.Vary(varyAccept...)
// Absent means the combined Accept view (RFC 9110 Section 5.2) is empty:
// no field line, or only empty ones. The joined read matches the field name
// case-insensitively, the same way Accepts negotiates, so the two entry
// points agree on whether the client stated a preference.
acceptRaw := peekJoinedRequestHeader(&r.c.fasthttp.Request.Header, HeaderAccept)
if len(acceptRaw) == 0 {
// Without an Accept header the client accepts any media type
// (RFC 9110 Section 12.5.1), so pick the first non-default handler and
// use its media type. The literal "default" is not a media type and
// must not be emitted as a Content-Type value.
for _, h := range handlers {
if h.MediaType != formatDefaultMediaType {
r.c.fasthttp.Response.Header.SetContentType(h.MediaType)
return h.Handler(handlerCtx)
}
}
return handlers[0].Handler(handlerCtx)
}
// Using an int literal as the slice capacity allows for the slice to be
// allocated on the stack. The number was chosen arbitrarily as an
// approximation of the maximum number of content types a user might handle.
// If the user goes over, it just causes allocations, so it's not a problem.
types := make([]string, 0, 8)
var defaultHandler Handler
for _, h := range handlers {
if h.MediaType == formatDefaultMediaType {
defaultHandler = h.Handler
continue
}
types = append(types, h.MediaType)
}
accept := r.c.DefaultReq.Accepts(types...) //nolint:staticcheck // It is fine to ignore the static check
if accept == "" {
if defaultHandler == nil {
return r.SendStatus(StatusNotAcceptable)
}
return defaultHandler(handlerCtx)
}
for _, h := range handlers {
if h.MediaType == accept {
r.c.fasthttp.Response.Header.SetContentType(h.MediaType)
return h.Handler(handlerCtx)
}
}
return fmt.Errorf("%w: format: an Accept was found but no handler was called", errUnreachable)
}
// AutoFormat performs content-negotiation on the Accept HTTP header.
// It uses Accepts to select a proper format.
// The supported content types are text/html, text/plain, application/json, application/xml, application/vnd.msgpack, and application/cbor.
// When text/html is selected, the body is treated as plain text and HTML-escaped before being wrapped in a `<p>` element.
// For more flexible content negotiation, use Format.
// If the header is not specified or there is no proper format, text/plain is used.
func (r *DefaultRes) AutoFormat(body any) error {
// The response is selected based on the Accept header, so let caches know
// (RFC 9110 Section 12.5.5).
r.Vary(varyAccept...)
// Get accepted content type; text/plain when nothing matches.
accept := "txt"
if len(peekJoinedRequestHeader(&r.c.fasthttp.Request.Header, HeaderAccept)) > 0 {
if negotiated := r.c.DefaultReq.Accepts("html", "json", "txt", "xml", "msgpack", "cbor"); negotiated != "" { //nolint:staticcheck // It is fine to ignore the static check
accept = negotiated
}
}
// Set accepted content type
r.Type(accept)
// Type convert provided body
var b string
switch val := body.(type) {
case string:
b = val
case []byte:
b = r.c.app.toString(val)
default:
b = fmt.Sprintf("%v", val)
}
// Format based on the accept content type
switch accept {
case "txt":
return r.SendString(b)
case "json":
return r.JSON(body)
case "xml":
return r.XML(body)
case "html":
return r.SendString("<p>" + template.HTMLEscapeString(b) + "</p>")
case "msgpack":
return r.MsgPack(body)
case "cbor":
return r.CBOR(body)
}
// Default case
return r.SendString(b)
}
// ContentLength returns what the Content-Length response header declares: a
// length a handler or upstream set, -1 for an unknown-length stream, 0 when
// none is declared. fasthttp fills it in on serialization; see also Res.Body.
func (r *DefaultRes) ContentLength() int {
return r.c.fasthttp.Response.Header.ContentLength()
}
// ContentType returns the Content-Type response header, the read side of Type.
// With none set it reports what would be sent: fasthttp's default, or "" under
// Config.DisableDefaultContentType. Only valid within the handler.
func (r *DefaultRes) ContentType() string {
return r.c.app.toString(r.c.fasthttp.Response.Header.ContentType())
}
// Del removes every field line stored under key, whatever case it is spelled in,
// and is a no-op for a header that was never set. Del(HeaderSetCookie) withdraws
// the pending cookies, where ClearCookie expires one in the client's jar.
func (r *DefaultRes) Del(key string) {
header := &r.c.fasthttp.Response.Header
// The byte-exact fast path needs both sides canonical: the stored names (a
// proxied response can hold lower-case ones) and the caller's key, which
// fasthttp only normalizes while DisableHeaderNormalizing is off.
canonical := !r.c.app.config.DisableHeaderNormalizing && fieldname.Canonical(header)
fieldname.Del(header, key, canonical)
}
// Get (a.k.a. GetRespHeader) returns the HTTP response header specified by field.
// Field names are case-insensitive
// Returned value is only valid within the handler. Do not store any references.
// Make copies or use the Immutable setting instead.
func (r *DefaultRes) Get(key string, defaultValue ...string) string {
return defaultString(r.c.app.toString(r.c.fasthttp.Response.Header.Peek(key)), defaultValue)
}
// GetHeaders (a.k.a GetRespHeaders) returns the HTTP response headers.
// Returned value is only valid within the handler. Do not store any references.
// Make copies or use the Immutable setting instead.
func (r *DefaultRes) GetHeaders() map[string][]string {
app := r.c.app
respHeader := &r.c.fasthttp.Response.Header
// Pre-allocate map with known header count to avoid reallocations
headers := make(map[string][]string, respHeader.Len())
for k, v := range respHeader.All() {
key := app.toString(k)
headers[key] = append(headers[key], app.toString(v))
}
return headers
}
// JSON converts any interface or string to JSON.
// Array and slice values encode as JSON arrays,
// except that []byte encodes as a base64-encoded string,
// and a nil slice encodes as the null JSON value.
// If the ctype parameter is given, this method will set the
// Content-Type header equal to ctype. If ctype is not given,
// The Content-Type header will be set to application/json; charset=utf-8.
func (r *DefaultRes) JSON(data any, ctype ...string) error {
raw, err := r.c.app.config.JSONEncoder(data)
if err != nil {
return err
}
response := &r.c.fasthttp.Response
response.SetBodyRaw(raw)
if len(ctype) > 0 {
response.Header.SetContentType(ctype[0])
} else {
response.Header.SetContentType(MIMEApplicationJSONCharsetUTF8)
}
return nil
}
// MsgPack converts any interface or string to MessagePack encoded bytes.
// If the ctype parameter is given, this method will set the
// Content-Type header equal to ctype. If ctype is not given,
// The Content-Type header will be set to application/vnd.msgpack.
func (r *DefaultRes) MsgPack(data any, ctype ...string) error {
raw, err := r.c.app.config.MsgPackEncoder(data)
if err != nil {
return err
}
response := &r.c.fasthttp.Response
response.SetBodyRaw(raw)
if len(ctype) > 0 {
response.Header.SetContentType(ctype[0])
} else {
response.Header.SetContentType(MIMEApplicationMsgPack)
}
return nil
}
// CBOR converts any interface or string to CBOR encoded bytes.
// If the ctype parameter is given, this method will set the
// Content-Type header equal to ctype. If ctype is not given,
// The Content-Type header will be set to application/cbor.
func (r *DefaultRes) CBOR(data any, ctype ...string) error {
raw, err := r.c.app.config.CBOREncoder(data)
if err != nil {
return err
}
response := &r.c.fasthttp.Response
response.SetBodyRaw(raw)
if len(ctype) > 0 {
response.Header.SetContentType(ctype[0])
} else {
response.Header.SetContentType(MIMEApplicationCBOR)
}
return nil
}
// JSONP sends a JSON response with JSONP support.
// This method is identical to JSON, except that it opts-in to JSONP callback support.
// By default, the callback name is simply callback.
//
// The callback name is reduced to a JavaScript member expression: everything
// outside [A-Za-z0-9_$.[]] is dropped. Callers routinely take the name straight
// from the query string, which is what JSONP is for, and the name lands
// verbatim in a same-origin text/javascript body — so an unfiltered one would
// let a request supply arbitrary script for the app's own origin.
func (r *DefaultRes) JSONP(data any, callback ...string) error {
raw, err := r.c.app.config.JSONEncoder(data)
if err != nil {
return err
}
cb := defaultJSONPCallback
if len(callback) > 0 {
if sanitized := sanitizeJSONPCallback(callback[0]); sanitized != "" {
cb = sanitized
}
}
// Build JSONP response: callback(data);
// Use bytebufferpool to avoid string concatenation allocations
buf := bytebufferpool.Get()
buf.WriteString(cb)
buf.WriteByte('(')
buf.Write(raw)
buf.WriteString(");")
r.setCanonical(HeaderXContentTypeOptions, "nosniff")
r.c.fasthttp.Response.Header.SetContentType(MIMETextJavaScriptCharsetUTF8)
// Use SetBody (not SetBodyRaw) to copy the bytes before returning buffer to pool
r.c.fasthttp.Response.SetBody(buf.Bytes())
bytebufferpool.Put(buf)
return nil
}
const defaultJSONPCallback = "callback"
// isJSONPCallbackByte reports whether b may appear in a JSONP callback name. The
// set spells a JavaScript member expression and admits nothing that could open a
// string, comment or statement.
func isJSONPCallbackByte(b byte) bool {
return (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') ||
(b >= '0' && b <= '9') ||
b == '_' || b == '$' || b == '.' || b == '[' || b == ']'
}
// sanitizeJSONPCallback drops every byte isJSONPCallbackByte rejects, as Express
// and Django do, then requires a member expression, returning "" otherwise.
// Filtering is enough for safety, not correctness: "1.2.3" and "a[" only throw.
func sanitizeJSONPCallback(cb string) string {
i := 0
for ; i < len(cb); i++ {
if !isJSONPCallbackByte(cb[i]) {
break
}
}
if i != len(cb) {
out := make([]byte, i, len(cb))
copy(out, cb[:i])
for ; i < len(cb); i++ {
if isJSONPCallbackByte(cb[i]) {
out = append(out, cb[i])
}
}
cb = utils.UnsafeString(out)
}
if !isJSONPMemberExpression(cb) {
return ""
}
return cb
}
// isJSONPMemberExpression reports whether cb is a dotted chain of identifiers
// with optional bracket indexing — the shape a JSONP body may legally call.
func isJSONPMemberExpression(cb string) bool {
if cb == "" {
return false
}
// "let" is a keyword only where a "[" follows it, and only at the head: an
// expression statement may not begin "let [", so the body "let[a](…);" is
// read as a destructuring declaration and is a syntax error. "let(…)",
// "let.a(…)" and an inner "cb[let[a]]" are all calls and stay allowed.
if strings.HasPrefix(cb, "let[") {
return false
}
depth := 0
atStart := true // expecting the first byte of an identifier
inIndex := false // that first byte follows '[', so a number may stand there
afterClose := false // a ']' just closed an index
numeric := false // the open index began with a digit, so it is a number
isRef := true // the open token is read as a name, not written as a property
start := 0 // first byte of the open token
for i := 0; i < len(cb); i++ {
switch c := cb[i]; c {
case '.':
if atStart || numeric || (isRef && isJSReservedWord(cb[start:i])) {
return false
}
atStart, inIndex, afterClose, isRef = true, false, false, false
case '[':
if atStart || numeric || (isRef && isJSReservedWord(cb[start:i])) {
return false
}
depth++
atStart, inIndex, afterClose, isRef = true, true, false, true
start = i + 1
case ']':
if atStart || depth == 0 {
return false
}
if isRef && !numeric && isJSReservedWord(cb[start:i]) {
return false
}
depth--
afterClose, numeric, isRef = true, false, false
default:
// Only '.', '[' or another ']' may follow a closing bracket, so "cb[0]x"
// is no member expression. Without this the machine would accept it and
// emit a body that does not parse.
if afterClose {
return false
}
if atStart {
// An identifier may not start with a digit. A bracket index may, and
// then it is that number alone: "cb[0]" parses, "cb[0x]" does not.
// Only a token opened by '[' counts — "cb[a.0]" is a property named
// after a dot, where a digit is as illegal as it is at the top level.
if c >= '0' && c <= '9' {
if !inIndex {
return false
}
numeric = true
}
atStart, inIndex = false, false
} else if numeric && (c < '0' || c > '9') {
return false
}
}
}
if isRef && !numeric && isJSReservedWord(cb[start:]) {
return false
}
return depth == 0 && !atStart
}
// isJSReservedWord reports whether tok is a word JavaScript will not read as a
// name. Only the positions that are read matter — the head of the expression and
// the head inside each index — since "a.for" and "a[b.class]" name properties,
// which any word may do. Emitting "for({…})" instead just ships a syntax error to
// the browser, so those spellings fall back to the default callback.
func isJSReservedWord(tok string) bool {
// Only the words a classic script rejects wherever they stand. A JSONP body
// is loaded by a script tag, so it is parsed under the script goal in sloppy
// mode, and several words that look reserved are ordinary identifiers there.
//
// Absent on purpose: "this", "true", "false" and "null" are keywords, but
// each is a complete expression, so "this.cb" and "cb[true]" parse. "await"
// is reserved only in a module or an async function, and "yield" only in
// strict mode or a generator, so both name a callback here. "let" is
// contextual in a third way and handled where it is read.
switch tok {
case "break", "case", "catch", "class", "const", "continue",
"debugger", "default", "delete", "do", "else", "enum", "export",
"extends", "finally", "for", "function", "if", "import", "in",
"instanceof", "new", "return", "super", "switch",
"throw", "try", "typeof", "var", "void", "while", "with":
return true
default:
return false
}
}
// XML converts any interface or string to XML.
// This method also sets the content header to application/xml; charset=utf-8.
func (r *DefaultRes) XML(data any) error {
raw, err := r.c.app.config.XMLEncoder(data)
if err != nil {
return err
}
response := &r.c.fasthttp.Response
response.SetBodyRaw(raw)
response.Header.SetContentType(MIMEApplicationXMLCharsetUTF8)
return nil
}
// Links joins the links followed by the property to populate the response's Link HTTP header field.
func (r *DefaultRes) Links(link ...string) {
if len(link) == 0 {
return
}
bb := bytebufferpool.Get()
for i := range link {
if i%2 == 0 {
bb.WriteByte('<')
bb.WriteString(link[i])
bb.WriteByte('>')
} else {
bb.WriteString(`; rel="`)
// The rel value sits inside a quoted-string, so quotes and
// backslashes must be escaped (RFC 9110 Section 5.6.4).
bb.WriteString(quotedstring.Escape(link[i]))
bb.WriteString(`",`)
}
}
r.setCanonical(HeaderLink, utils.TrimRight(r.c.app.toString(bb.Bytes()), ','))
bytebufferpool.Put(bb)
}
// Location sets the response Location HTTP header to the specified path parameter.
func (r *DefaultRes) Location(path string) {
r.setCanonical(HeaderLocation, path)
}
// OriginalURL contains the original request URL.
// Returned value is only valid within the handler. Do not store any references.
// Make copies or use the Immutable setting to use the value outside the Handler.
func (r *DefaultRes) OriginalURL() string {
return r.c.OriginalURL()
}
// Redirect returns the Redirect reference.
// Use Redirect().Status() to set custom redirection status code.
// If status is not specified, status defaults to 303 See Other.
// You can use Redirect().To(), Redirect().Route() and Redirect().Back() for redirection.
func (r *DefaultRes) Redirect() *Redirect {
return r.c.Redirect()
}