forked from gofiber/fiber
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ctx.go
1988 lines (1717 loc) · 62 KB
/
ctx.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
// ⚡️ 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"
"errors"
"fmt"
"io"
"io/fs"
"mime/multipart"
"net"
"net/http"
"path/filepath"
"strconv"
"strings"
"sync"
"text/template"
"time"
"github.com/gofiber/utils/v2"
"github.com/valyala/bytebufferpool"
"github.com/valyala/fasthttp"
)
const (
schemeHTTP = "http"
schemeHTTPS = "https"
)
// maxParams defines the maximum number of parameters per route.
const maxParams = 30
// The contextKey type is unexported to prevent collisions with context keys defined in
// other packages.
type contextKey int
// userContextKey define the key name for storing context.Context in *fasthttp.RequestCtx
const userContextKey contextKey = 0 // __local_user_context__
// DefaultCtx is the default implementation of the Ctx interface
// generation tool `go install github.com/vburenin/ifacemaker@975a95966976eeb2d4365a7fb236e274c54da64c`
// https://github.com/vburenin/ifacemaker/blob/975a95966976eeb2d4365a7fb236e274c54da64c/ifacemaker.go#L14-L30
//
//go:generate ifacemaker --file ctx.go --struct DefaultCtx --iface Ctx --pkg fiber --output ctx_interface_gen.go --not-exported true --iface-comment "Ctx represents the Context which hold the HTTP request and response.\nIt has methods for the request query string, parameters, body, HTTP headers and so on."
type DefaultCtx struct {
app *App // Reference to *App
route *Route // Reference to *Route
fasthttp *fasthttp.RequestCtx // Reference to *fasthttp.RequestCtx
bind *Bind // Default bind reference
redirect *Redirect // Default redirect reference
values [maxParams]string // Route parameter values
viewBindMap sync.Map // Default view map to bind template engine
method string // HTTP method
baseURI string // HTTP base uri
path string // HTTP path with the modifications by the configuration -> string copy from pathBuffer
detectionPath string // Route detection path -> string copy from detectionPathBuffer
treePath string // Path for the search in the tree
pathOriginal string // Original HTTP path
pathBuffer []byte // HTTP path buffer
detectionPathBuffer []byte // HTTP detectionPath buffer
flashMessages redirectionMsgs // Flash messages
indexRoute int // Index of the current route
indexHandler int // Index of the current handler
methodINT int // HTTP method INT equivalent
matched bool // Non use route matched
}
// 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
}
// compareConfig compares the current SendFile config with the new one
// and returns true if they are different.
//
// Here we don't use reflect.DeepEqual because it is quite slow compared to manual comparison.
func (sf *sendFileStore) compareConfig(cfg SendFile) bool {
if 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
}
// TLSHandler object
type TLSHandler struct {
clientHelloInfo *tls.ClientHelloInfo
}
// GetClientInfo Callback function to set ClientHelloInfo
// Must comply with the method structure of https://cs.opensource.google/go/go/+/refs/tags/go1.20:src/crypto/tls/common.go;l=554-563
// Since we overlay the method of the TLS config in the listener method
func (t *TLSHandler) GetClientInfo(info *tls.ClientHelloInfo) (*tls.Certificate, error) {
t.clientHelloInfo = info
return nil, nil //nolint:nilnil // Not returning anything useful here is probably fine
}
// Range data for c.Range
type Range struct {
Type string
Ranges []RangeSet
}
// RangeSet represents a single content range from a request.
type RangeSet struct {
Start int
End int
}
// Cookie data for c.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
}
// Views is the interface that wraps the Render function.
type Views interface {
Load() error
Render(out io.Writer, name string, binding any, layout ...string) error
}
// ResFmt associates a Content Type to a fiber.Handler for c.Format
type ResFmt struct {
Handler func(Ctx) error
MediaType string
}
// Accepts checks if the specified extensions or content types are acceptable.
func (c *DefaultCtx) Accepts(offers ...string) string {
return getOffer(c.fasthttp.Request.Header.Peek(HeaderAccept), acceptsOfferType, offers...)
}
// AcceptsCharsets checks if the specified charset is acceptable.
func (c *DefaultCtx) AcceptsCharsets(offers ...string) string {
return getOffer(c.fasthttp.Request.Header.Peek(HeaderAcceptCharset), acceptsOffer, offers...)
}
// AcceptsEncodings checks if the specified encoding is acceptable.
func (c *DefaultCtx) AcceptsEncodings(offers ...string) string {
return getOffer(c.fasthttp.Request.Header.Peek(HeaderAcceptEncoding), acceptsOffer, offers...)
}
// AcceptsLanguages checks if the specified language is acceptable.
func (c *DefaultCtx) AcceptsLanguages(offers ...string) string {
return getOffer(c.fasthttp.Request.Header.Peek(HeaderAcceptLanguage), acceptsOffer, offers...)
}
// App returns the *App reference to the instance of the Fiber application
func (c *DefaultCtx) App() *App {
return 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.
func (c *DefaultCtx) Append(field string, values ...string) {
if len(values) == 0 {
return
}
h := c.app.getString(c.fasthttp.Response.Header.Peek(field))
originalH := h
for _, value := range values {
if len(h) == 0 {
h = value
} else if h != value && !strings.HasPrefix(h, value+",") && !strings.HasSuffix(h, " "+value) &&
!strings.Contains(h, " "+value+",") {
h += ", " + value
}
}
if originalH != h {
c.Set(field, h)
}
}
// Attachment sets the HTTP response Content-Disposition header field to attachment.
func (c *DefaultCtx) Attachment(filename ...string) {
if len(filename) > 0 {
fname := filepath.Base(filename[0])
c.Type(filepath.Ext(fname))
c.setCanonical(HeaderContentDisposition, `attachment; filename="`+c.app.quoteString(fname)+`"`)
return
}
c.setCanonical(HeaderContentDisposition, "attachment")
}
// BaseURL returns (protocol + host + base path).
func (c *DefaultCtx) BaseURL() string {
// TODO: Could be improved: 53.8 ns/op 32 B/op 1 allocs/op
// Should work like https://codeigniter.com/user_guide/helpers/url_helper.html
if c.baseURI != "" {
return c.baseURI
}
c.baseURI = c.Scheme() + "://" + c.Host()
return c.baseURI
}
// BodyRaw contains the raw body submitted in a POST request.
// Returned value is only valid within the handler. Do not store any references.
// Make copies or use the Immutable setting instead.
func (c *DefaultCtx) BodyRaw() []byte {
return c.getBody()
}
func (c *DefaultCtx) tryDecodeBodyInOrder(
originalBody *[]byte,
encodings []string,
) ([]byte, uint8, error) {
var (
err error
body []byte
decodesRealized uint8
)
for index, encoding := range encodings {
decodesRealized++
switch encoding {
case StrGzip:
body, err = c.fasthttp.Request.BodyGunzip()
case StrBr, StrBrotli:
body, err = c.fasthttp.Request.BodyUnbrotli()
case StrDeflate:
body, err = c.fasthttp.Request.BodyInflate()
case StrZstd:
body, err = c.fasthttp.Request.BodyUnzstd()
default:
decodesRealized--
if len(encodings) == 1 {
body = c.fasthttp.Request.Body()
}
return body, decodesRealized, nil
}
if err != nil {
return nil, decodesRealized, err
}
// Only execute body raw update if it has a next iteration to try to decode
if index < len(encodings)-1 && decodesRealized > 0 {
if index == 0 {
tempBody := c.fasthttp.Request.Body()
*originalBody = make([]byte, len(tempBody))
copy(*originalBody, tempBody)
}
c.fasthttp.Request.SetBodyRaw(body)
}
}
return body, decodesRealized, nil
}
// Body contains the raw body submitted in a POST request.
// This method will decompress the body if the 'Content-Encoding' header is provided.
// It returns the original (or decompressed) body data which is valid only within the handler.
// Don't store direct references to the returned data.
// If you need to keep the body's data later, make a copy or use the Immutable option.
func (c *DefaultCtx) Body() []byte {
var (
err error
body, originalBody []byte
headerEncoding string
encodingOrder = []string{"", "", ""}
)
// Get Content-Encoding header
headerEncoding = utils.UnsafeString(c.Request().Header.ContentEncoding())
// If no encoding is provided, return the original body
if len(headerEncoding) == 0 {
return c.getBody()
}
// Split and get the encodings list, in order to attend the
// rule defined at: https://www.rfc-editor.org/rfc/rfc9110#section-8.4-5
encodingOrder = getSplicedStrList(headerEncoding, encodingOrder)
if len(encodingOrder) == 0 {
return c.getBody()
}
var decodesRealized uint8
body, decodesRealized, err = c.tryDecodeBodyInOrder(&originalBody, encodingOrder)
// Ensure that the body will be the original
if originalBody != nil && decodesRealized > 0 {
c.fasthttp.Request.SetBodyRaw(originalBody)
}
if err != nil {
return []byte(err.Error())
}
if c.app.config.Immutable {
return utils.CopyBytes(body)
}
return body
}
// 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 (c *DefaultCtx) ClearCookie(key ...string) {
if len(key) > 0 {
for i := range key {
c.fasthttp.Response.Header.DelClientCookie(key[i])
}
return
}
c.fasthttp.Request.Header.VisitAllCookie(func(k, _ []byte) {
c.fasthttp.Response.Header.DelClientCookieBytes(k)
})
}
// RequestCtx returns *fasthttp.RequestCtx that carries a deadline
// a cancellation signal, and other values across API boundaries.
func (c *DefaultCtx) RequestCtx() *fasthttp.RequestCtx {
return c.fasthttp
}
// Context returns a context implementation that was set by
// user earlier or returns a non-nil, empty context,if it was not set earlier.
func (c *DefaultCtx) Context() context.Context {
ctx, ok := c.fasthttp.UserValue(userContextKey).(context.Context)
if !ok {
ctx = context.Background()
c.SetContext(ctx)
}
return ctx
}
// SetContext sets a context implementation by user.
func (c *DefaultCtx) SetContext(ctx context.Context) {
c.fasthttp.SetUserValue(userContextKey, ctx)
}
// Cookie sets a cookie by passing a cookie struct.
func (c *DefaultCtx) Cookie(cookie *Cookie) {
fcookie := fasthttp.AcquireCookie()
fcookie.SetKey(cookie.Name)
fcookie.SetValue(cookie.Value)
fcookie.SetPath(cookie.Path)
fcookie.SetDomain(cookie.Domain)
// only set max age and expiry when SessionOnly is false
// i.e. cookie supposed to last beyond browser session
// refer: https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#define_the_lifetime_of_a_cookie
if !cookie.SessionOnly {
fcookie.SetMaxAge(cookie.MaxAge)
fcookie.SetExpire(cookie.Expires)
}
fcookie.SetSecure(cookie.Secure)
fcookie.SetHTTPOnly(cookie.HTTPOnly)
switch utils.ToLower(cookie.SameSite) {
case CookieSameSiteStrictMode:
fcookie.SetSameSite(fasthttp.CookieSameSiteStrictMode)
case CookieSameSiteNoneMode:
fcookie.SetSameSite(fasthttp.CookieSameSiteNoneMode)
case CookieSameSiteDisabled:
fcookie.SetSameSite(fasthttp.CookieSameSiteDisabled)
default:
fcookie.SetSameSite(fasthttp.CookieSameSiteLaxMode)
}
// CHIPS allows to partition cookie jar by top-level site.
// refer: https://developers.google.com/privacy-sandbox/3pcd/chips
fcookie.SetPartitioned(cookie.Partitioned)
c.fasthttp.Response.Header.SetCookie(fcookie)
fasthttp.ReleaseCookie(fcookie)
}
// Cookies are used for getting a cookie value by key.
// Defaults to the empty string "" if the cookie doesn't exist.
// If a default value is given, it will return that value if the cookie doesn't exist.
// The 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 (c *DefaultCtx) Cookies(key string, defaultValue ...string) string {
return defaultString(c.app.getString(c.fasthttp.Request.Header.Cookie(key)), defaultValue)
}
// 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 (c *DefaultCtx) Download(file string, filename ...string) error {
var fname string
if len(filename) > 0 {
fname = filename[0]
} else {
fname = filepath.Base(file)
}
c.setCanonical(HeaderContentDisposition, `attachment; filename="`+c.app.quoteString(fname)+`"`)
return c.SendFile(file)
}
// Request return the *fasthttp.Request object
// This allows you to use all fasthttp request methods
// https://godoc.org/github.com/valyala/fasthttp#Request
func (c *DefaultCtx) Request() *fasthttp.Request {
return &c.fasthttp.Request
}
// Response return the *fasthttp.Response object
// This allows you to use all fasthttp response methods
// https://godoc.org/github.com/valyala/fasthttp#Response
func (c *DefaultCtx) Response() *fasthttp.Response {
return &c.fasthttp.Response
}
// 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 (c *DefaultCtx) Format(handlers ...ResFmt) error {
if len(handlers) == 0 {
return ErrNoHandlers
}
c.Vary(HeaderAccept)
if c.Get(HeaderAccept) == "" {
c.Response().Header.SetContentType(handlers[0].MediaType)
return handlers[0].Handler(c)
}
// 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 == "default" {
defaultHandler = h.Handler
continue
}
types = append(types, h.MediaType)
}
accept := c.Accepts(types...)
if accept == "" {
if defaultHandler == nil {
return c.SendStatus(StatusNotAcceptable)
}
return defaultHandler(c)
}
for _, h := range handlers {
if h.MediaType == accept {
c.Response().Header.SetContentType(h.MediaType)
return h.Handler(c)
}
}
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, and application/xml.
// For more flexible content negotiation, use Format.
// If the header is not specified or there is no proper format, text/plain is used.
func (c *DefaultCtx) AutoFormat(body any) error {
// Get accepted content type
accept := c.Accepts("html", "json", "txt", "xml")
// Set accepted content type
c.Type(accept)
// Type convert provided body
var b string
switch val := body.(type) {
case string:
b = val
case []byte:
b = c.app.getString(val)
default:
b = fmt.Sprintf("%v", val)
}
// Format based on the accept content type
switch accept {
case "html":
return c.SendString("<p>" + b + "</p>")
case "json":
return c.JSON(body)
case "txt":
return c.SendString(b)
case "xml":
return c.XML(body)
}
return c.SendString(b)
}
// FormFile returns the first file by key from a MultipartForm.
func (c *DefaultCtx) FormFile(key string) (*multipart.FileHeader, error) {
return c.fasthttp.FormFile(key)
}
// FormValue returns the first value by key from a MultipartForm.
// Search is performed in QueryArgs, PostArgs, MultipartForm and FormFile in this particular order.
// Defaults to the empty string "" if the form value doesn't exist.
// If a default value is given, it will return that value if the form value does not exist.
// Returned value is only valid within the handler. Do not store any references.
// Make copies or use the Immutable setting instead.
func (c *DefaultCtx) FormValue(key string, defaultValue ...string) string {
return defaultString(c.app.getString(c.fasthttp.FormValue(key)), defaultValue)
}
// Fresh returns true when the response is still “fresh” in the client's cache,
// otherwise false is returned to indicate that the client cache is now stale
// and the full response should be sent.
// When a client sends the Cache-Control: no-cache request header to indicate an end-to-end
// reload request, this module will return false to make handling these requests transparent.
// https://github.com/jshttp/fresh/blob/10e0471669dbbfbfd8de65bc6efac2ddd0bfa057/index.js#L33
func (c *DefaultCtx) Fresh() bool {
// fields
modifiedSince := c.Get(HeaderIfModifiedSince)
noneMatch := c.Get(HeaderIfNoneMatch)
// unconditional request
if modifiedSince == "" && noneMatch == "" {
return false
}
// Always return stale when Cache-Control: no-cache
// to support end-to-end reload requests
// https://tools.ietf.org/html/rfc2616#section-14.9.4
cacheControl := c.Get(HeaderCacheControl)
if cacheControl != "" && isNoCache(cacheControl) {
return false
}
// if-none-match
if noneMatch != "" && noneMatch != "*" {
etag := c.app.getString(c.fasthttp.Response.Header.Peek(HeaderETag))
if etag == "" {
return false
}
if c.app.isEtagStale(etag, c.app.getBytes(noneMatch)) {
return false
}
if modifiedSince != "" {
lastModified := c.app.getString(c.fasthttp.Response.Header.Peek(HeaderLastModified))
if lastModified != "" {
lastModifiedTime, err := http.ParseTime(lastModified)
if err != nil {
return false
}
modifiedSinceTime, err := http.ParseTime(modifiedSince)
if err != nil {
return false
}
return lastModifiedTime.Compare(modifiedSinceTime) != 1
}
}
}
return true
}
// Get returns the HTTP request 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 (c *DefaultCtx) Get(key string, defaultValue ...string) string {
return GetReqHeader(c, key, defaultValue...)
}
// GetReqHeader returns the HTTP request header specified by filed.
// This function is generic and can handle different headers type values.
func GetReqHeader[V GenericType](c Ctx, key string, defaultValue ...V) V {
var v V
return genericParseType[V](c.App().getString(c.Request().Header.Peek(key)), v, defaultValue...)
}
// 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 (c *DefaultCtx) GetRespHeader(key string, defaultValue ...string) string {
return defaultString(c.app.getString(c.fasthttp.Response.Header.Peek(key)), defaultValue)
}
// 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 (c *DefaultCtx) GetRespHeaders() map[string][]string {
headers := make(map[string][]string)
c.Response().Header.VisitAll(func(k, v []byte) {
key := c.app.getString(k)
headers[key] = append(headers[key], c.app.getString(v))
})
return headers
}
// GetReqHeaders returns the HTTP request headers.
// Returned value is only valid within the handler. Do not store any references.
// Make copies or use the Immutable setting instead.
func (c *DefaultCtx) GetReqHeaders() map[string][]string {
headers := make(map[string][]string)
c.Request().Header.VisitAll(func(k, v []byte) {
key := c.app.getString(k)
headers[key] = append(headers[key], c.app.getString(v))
})
return headers
}
// Host contains the host derived from the X-Forwarded-Host or Host HTTP header.
// Returned value is only valid within the handler. Do not store any references.
// In a network context, `Host` refers to the combination of a hostname and potentially a port number used for connecting,
// while `Hostname` refers specifically to the name assigned to a device on a network, excluding any port information.
// Example: URL: https://example.com:8080 -> Host: example.com:8080
// Make copies or use the Immutable setting instead.
// Please use Config.TrustProxy to prevent header spoofing, in case when your app is behind the proxy.
func (c *DefaultCtx) Host() string {
if c.IsProxyTrusted() {
if host := c.Get(HeaderXForwardedHost); len(host) > 0 {
commaPos := strings.Index(host, ",")
if commaPos != -1 {
return host[:commaPos]
}
return host
}
}
return c.app.getString(c.fasthttp.Request.URI().Host())
}
// Hostname contains the hostname derived from the X-Forwarded-Host or Host HTTP header using the c.Host() method.
// Returned value is only valid within the handler. Do not store any references.
// Example: URL: https://example.com:8080 -> Hostname: example.com
// Make copies or use the Immutable setting instead.
// Please use Config.TrustProxy to prevent header spoofing, in case when your app is behind the proxy.
func (c *DefaultCtx) Hostname() string {
addr, _ := parseAddr(c.Host())
return addr
}
// Port returns the remote port of the request.
func (c *DefaultCtx) Port() string {
tcpaddr, ok := c.fasthttp.RemoteAddr().(*net.TCPAddr)
if !ok {
panic(errors.New("failed to type-assert to *net.TCPAddr"))
}
return strconv.Itoa(tcpaddr.Port)
}
// IP returns the remote IP address of the request.
// If ProxyHeader and IP Validation is configured, it will parse that header and return the first valid IP address.
// Please use Config.TrustProxy to prevent header spoofing, in case when your app is behind the proxy.
func (c *DefaultCtx) IP() string {
if c.IsProxyTrusted() && len(c.app.config.ProxyHeader) > 0 {
return c.extractIPFromHeader(c.app.config.ProxyHeader)
}
return c.fasthttp.RemoteIP().String()
}
// extractIPsFromHeader will return a slice of IPs it found given a header name in the order they appear.
// When IP validation is enabled, any invalid IPs will be omitted.
func (c *DefaultCtx) extractIPsFromHeader(header string) []string {
// TODO: Reuse the c.extractIPFromHeader func somehow in here
headerValue := c.Get(header)
// We can't know how many IPs we will return, but we will try to guess with this constant division.
// Counting ',' makes function slower for about 50ns in general case.
const maxEstimatedCount = 8
estimatedCount := len(headerValue) / maxEstimatedCount
if estimatedCount > maxEstimatedCount {
estimatedCount = maxEstimatedCount // Avoid big allocation on big header
}
ipsFound := make([]string, 0, estimatedCount)
i := 0
j := -1
iploop:
for {
var v4, v6 bool
// Manually splitting string without allocating slice, working with parts directly
i, j = j+1, j+2
if j > len(headerValue) {
break
}
for j < len(headerValue) && headerValue[j] != ',' {
if headerValue[j] == ':' {
v6 = true
} else if headerValue[j] == '.' {
v4 = true
}
j++
}
for i < j && (headerValue[i] == ' ' || headerValue[i] == ',') {
i++
}
s := utils.TrimRight(headerValue[i:j], ' ')
if c.app.config.EnableIPValidation {
// Skip validation if IP is clearly not IPv4/IPv6, otherwise validate without allocations
if (!v6 && !v4) || (v6 && !utils.IsIPv6(s)) || (v4 && !utils.IsIPv4(s)) {
continue iploop
}
}
ipsFound = append(ipsFound, s)
}
return ipsFound
}
// extractIPFromHeader will attempt to pull the real client IP from the given header when IP validation is enabled.
// currently, it will return the first valid IP address in header.
// when IP validation is disabled, it will simply return the value of the header without any inspection.
// Implementation is almost the same as in extractIPsFromHeader, but without allocation of []string.
func (c *DefaultCtx) extractIPFromHeader(header string) string {
if c.app.config.EnableIPValidation {
headerValue := c.Get(header)
i := 0
j := -1
iploop:
for {
var v4, v6 bool
// Manually splitting string without allocating slice, working with parts directly
i, j = j+1, j+2
if j > len(headerValue) {
break
}
for j < len(headerValue) && headerValue[j] != ',' {
if headerValue[j] == ':' {
v6 = true
} else if headerValue[j] == '.' {
v4 = true
}
j++
}
for i < j && headerValue[i] == ' ' {
i++
}
s := utils.TrimRight(headerValue[i:j], ' ')
if c.app.config.EnableIPValidation {
if (!v6 && !v4) || (v6 && !utils.IsIPv6(s)) || (v4 && !utils.IsIPv4(s)) {
continue iploop
}
}
return s
}
return c.fasthttp.RemoteIP().String()
}
// default behavior if IP validation is not enabled is just to return whatever value is
// in the proxy header. Even if it is empty or invalid
return c.Get(c.app.config.ProxyHeader)
}
// IPs returns a string slice of IP addresses specified in the X-Forwarded-For request header.
// When IP validation is enabled, only valid IPs are returned.
func (c *DefaultCtx) IPs() []string {
return c.extractIPsFromHeader(HeaderXForwardedFor)
}
// Is returns the matching content type,
// if the incoming request's Content-Type HTTP header field matches the MIME type specified by the type parameter
func (c *DefaultCtx) Is(extension string) bool {
extensionHeader := utils.GetMIME(extension)
if extensionHeader == "" {
return false
}
return strings.HasPrefix(
utils.TrimLeft(utils.UnsafeString(c.fasthttp.Request.Header.ContentType()), ' '),
extensionHeader,
)
}
// 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.
func (c *DefaultCtx) JSON(data any, ctype ...string) error {
raw, err := c.app.config.JSONEncoder(data)
if err != nil {
return err
}
c.fasthttp.Response.SetBodyRaw(raw)
if len(ctype) > 0 {
c.fasthttp.Response.Header.SetContentType(ctype[0])
} else {
c.fasthttp.Response.Header.SetContentType(MIMEApplicationJSON)
}
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 (c *DefaultCtx) CBOR(data any, ctype ...string) error {
raw, err := c.app.config.CBOREncoder(data)
if err != nil {
return err
}
c.fasthttp.Response.SetBodyRaw(raw)
if len(ctype) > 0 {
c.fasthttp.Response.Header.SetContentType(ctype[0])
} else {
c.fasthttp.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.
func (c *DefaultCtx) JSONP(data any, callback ...string) error {
raw, err := c.app.config.JSONEncoder(data)
if err != nil {
return err
}
var result, cb string
if len(callback) > 0 {
cb = callback[0]
} else {
cb = "callback"
}
result = cb + "(" + c.app.getString(raw) + ");"
c.setCanonical(HeaderXContentTypeOptions, "nosniff")
c.fasthttp.Response.Header.SetContentType(MIMETextJavaScriptCharsetUTF8)
return c.SendString(result)
}
// XML converts any interface or string to XML.
// This method also sets the content header to application/xml.
func (c *DefaultCtx) XML(data any) error {
raw, err := c.app.config.XMLEncoder(data)
if err != nil {
return err
}
c.fasthttp.Response.SetBodyRaw(raw)
c.fasthttp.Response.Header.SetContentType(MIMEApplicationXML)
return nil
}
// Links joins the links followed by the property to populate the response's Link HTTP header field.
func (c *DefaultCtx) 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="` + link[i] + `",`)
}
}
c.setCanonical(HeaderLink, utils.TrimRight(c.app.getString(bb.Bytes()), ','))
bytebufferpool.Put(bb)
}
// Locals makes it possible to pass any values under keys scoped to the request
// and therefore available to all following routes that match the request.
//
// All the values are removed from ctx after returning from the top
// RequestHandler. Additionally, Close method is called on each value
// implementing io.Closer before removing the value from ctx.
func (c *DefaultCtx) Locals(key any, value ...any) any {
if len(value) == 0 {
return c.fasthttp.UserValue(key)
}
c.fasthttp.SetUserValue(key, value[0])
return value[0]
}
// Locals function utilizing Go's generics feature.
// This function allows for manipulating and retrieving local values within a
// request context with a more specific data type.
//
// All the values are removed from ctx after returning from the top
// RequestHandler. Additionally, Close method is called on each value
// implementing io.Closer before removing the value from ctx.
func Locals[V any](c Ctx, key any, value ...V) V {
var v V
var ok bool
if len(value) == 0 {
v, ok = c.Locals(key).(V)
} else {
v, ok = c.Locals(key, value[0]).(V)
}
if !ok {
return v // return zero of type V
}
return v
}
// Location sets the response Location HTTP header to the specified path parameter.
func (c *DefaultCtx) Location(path string) {
c.setCanonical(HeaderLocation, path)
}
// Method returns the HTTP request method for the context, optionally overridden by the provided argument.