Repository navigation
Expand file tree
/
Copy pathctx_interface_gen.go
More file actions
788 lines (784 loc) · 44.8 KB
/
Copy pathctx_interface_gen.go
File metadata and controls
788 lines (784 loc) · 44.8 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
// Code generated by ifacemaker; DO NOT EDIT.
package fiber
import (
"bufio"
"context"
"crypto/tls"
"io"
"mime/multipart"
"net"
"time"
"github.com/valyala/fasthttp"
)
// Ctx represents the Context which hold the HTTP request and response.
// It has methods for the request query string, parameters, body, HTTP headers and so on.
type Ctx interface {
// App returns the *App reference to the instance of the Fiber application
App() *App
// BaseURL returns (protocol + host), such as "https://example.com". It carries no path.
BaseURL() string
// RequestCtx returns *fasthttp.RequestCtx that carries a deadline
// a cancellation signal, and other values across API boundaries.
RequestCtx() *fasthttp.RequestCtx
// Context returns a context implementation that was set by
// user earlier or returns a non-nil, empty context, if it was not set earlier.
Context() context.Context
// SetContext sets a context implementation by user.
SetContext(ctx context.Context)
// Deadline returns the time when work done on behalf of this context
// should be canceled. Ctx carries no deadline, so ok is always false.
//
// Ctx satisfies context.Context as a context that can never be canceled: it is
// pooled and reused, so it cannot honor the stability and concurrency the
// interface requires. Pass Context() to anything that is cancellation-aware or
// that outlives the handler.
Deadline() (time.Time, bool)
// Done returns a channel that's closed when work done on behalf of this
// context should be canceled. Ctx can never be canceled, so Done always
// returns nil, which context.Context explicitly permits. See Deadline.
Done() <-chan struct{}
// Err returns nil until the Done channel is closed. Done is always nil here,
// so Err always returns nil. See Deadline.
Err() error
// Request return the *fasthttp.Request object
// This allows you to use all fasthttp request methods
// https://godoc.org/github.com/valyala/fasthttp#Request
// Returns nil if the context has been released.
Request() *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
// Returns nil if the context has been released.
Response() *fasthttp.Response
// Body returns the request body, decompressing it when the request declares a
// Content-Encoding the app accepts. Req and Res both carry a Body, so on Ctx
// the request wins, as it does for Get; use Res().Body() for the response.
Body() []byte
// ContentLength returns the value of the Content-Length request header. Req and
// Res both carry one, so on Ctx the request wins, as it does for Get; use
// Res().ContentLength() for the response.
ContentLength() int
// ContentType returns the Content-Type request header, parameters included. Req
// and Res both carry one, so on Ctx the request wins, as it does for Get; use
// Res().ContentType() for the response.
ContentType() string
// Cookies returns the request cookie with the given key, or defaultValue. Only
// valid within the handler unless Immutable is set. For the cookies the response
// is set to send, use Res().GetCookies().
Cookies(key string, defaultValue ...string) string
// 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.
Get(key string, defaultValue ...string) string
// GetHeaders 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.
GetHeaders() map[string][]string
// 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.
GetReqHeaders() map[string][]string
// 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.
GetRespHeader(key string, defaultValue ...string) string
// 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.
GetRespHeaders() map[string][]string
// ClientHelloInfo returns the TLS ClientHelloInfo of the connection this request arrived on, or nil.
ClientHelloInfo() *tls.ClientHelloInfo
// Next executes the next method in the stack that matches the current route.
Next() error
// RestartRouting instead of going to the next handler. This may be useful after
// changing the request path. Note that handlers might be executed again.
RestartRouting() error
// ctxForHandlers returns the context user code is handed: the custom context
// when the app uses one, otherwise the DefaultCtx itself, as Next does.
ctxForHandlers() Ctx
setHandlerCtx(ctx CustomCtx)
// 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.
OriginalURL() string
// RequestID returns the request identifier from the response header or request header.
RequestID() string
// Req returns a convenience type whose API is limited to operations
// on the incoming request.
Req() Req
// Res returns a convenience type whose API is limited to operations
// on the outgoing response.
Res() Res
// 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.
Redirect() *Redirect
// ViewBind Add vars to default view var map binding to template engine.
// Variables are read by the Render method and may be overwritten.
ViewBind(vars Map) error
// Route returns the matched Route struct.
Route() *Route
// routeFallback builds the synthetic route for the fasthttp error handler.
// Its Method field is resolved like c.Method() (including the raw-header
// fallback for unregistered methods) so Route and Method always agree.
// Never inlined: inlining it would push Route over the inlining budget.
routeFallback() *Route
// Endpoint returns the route that will handle this request, without advancing the
// handler chain, so global middleware can read its Path or Name before calling
// Next. Returns nil when no endpoint will run: 404, 405, and while the error
// handler replays the chain for a request rejected at the protocol level. A
// route registered through Domain is reported only for a hostname its pattern
// matches, as its handlers decline every other one.
//
// It looks ahead, where the neighboring accessors look back: Route reports the
// route currently executing, which inside middleware is the middleware itself,
// and Matched reports whether an endpoint has been selected yet.
//
// It scans the remaining routes in the request's tree bucket, so calling it from
// global middleware costs a second router scan per request.
Endpoint() *Route
// FullPath returns the matched route path, including any group prefixes.
FullPath() string
// RouteName returns the name of the route currently executing, or "" when it is
// unnamed. Inside middleware that is the middleware's own route; use
// Endpoint().Name to look ahead to the one that will handle the request.
RouteName() string
// MountPath returns the prefix the sub-app owning the current route was mounted
// under, or "" for a top-level route. Path is not relative to it. One *App
// mounted twice reports its last prefix, as App.MountPath does.
MountPath() string
// Matched returns true if the current request path was matched by the router.
Matched() bool
// IsMiddleware returns true if the current request handler was registered as middleware.
IsMiddleware() bool
// IsFinal reports whether this is the last handler of a matched non-middleware
// route, so nothing further on that route runs. It describes the route, not the
// request: another route can still match, and a Use route is never final.
IsFinal() bool
// OverrideParam overwrites a route parameter value by name.
// If the parameter name does not exist in the route, this method does nothing.
OverrideParam(name, value string)
// SaveFile saves any multipart file to disk.
SaveFile(fileheader *multipart.FileHeader, path string) error
// SaveFileToStorage saves any multipart file to an external storage system.
SaveFileToStorage(fileheader *multipart.FileHeader, path string, storage Storage) error
// Error returns an *Error carrying the given status code, defaulting the message
// to the status text. Returning it hands it to the app's ErrorHandler, which
// writes the response; Error itself sets nothing.
Error(status int, message ...string) error
// Status sets the HTTP status for the response.
// This method is chainable.
//
// A status outside 100 to 999 is logged and replaced by 500.
Status(status int) Ctx
// ID returns the connection-unique identifier fasthttp assigned to this request,
// unlike RequestID, which reads a header. It is not unique across processes or
// restarts, so use it to correlate log lines within one server run.
ID() uint64
// StartTime returns the time the server began handling this request. It is the
// reference point Elapsed measures from.
StartTime() time.Time
// Elapsed returns how long this request has been handled so far, measured from
// StartTime. Called after the handler chain has run, it is the request latency.
Elapsed() time.Duration
// LocalAddr returns the server-side address of the connection this request
// arrived on. IP returns the client address as a string; this is the full
// net.Addr, so the port, network, and unix socket path survive.
LocalAddr() net.Addr
// RemoteAddr returns the address of the immediate peer, which is the proxy
// rather than the client when the app sits behind one. Use IP or IPs for the
// client address a trusted proxy forwarded.
RemoteAddr() net.Addr
// Hijack registers a handler that takes over the connection once the response is
// sent, for protocols Fiber does not speak. The connection then closes unless
// KeepHijackedConns is set, and the handler must not touch the pooled Ctx.
Hijack(handler fasthttp.HijackHandler)
// Hijacked returns true if Hijack has been called on this request, so a later
// handler can tell that the connection is already spoken for and leave the
// response alone.
Hijacked() bool
// String returns unique string representation of the ctx.
//
// The returned value may be useful for logging.
String() string
// Value makes it possible to retrieve values (Locals) under keys scoped to the request
// and therefore available to all following routes that match the request. If the context
// has been released and c.fasthttp is nil (for example, after ReleaseCtx), Value returns nil.
Value(key any) any
// configDependentPaths set paths for route recognition and prepared paths for the user,
// here the features for caseSensitive, decoded paths, strict paths are evaluated
configDependentPaths()
// Reset is a method to reset context fields by given request when to use server handlers.
Reset(fctx *fasthttp.RequestCtx)
// release is a method to reset context fields when to use ReleaseCtx()
release()
// Abandon marks this context as abandoned. An abandoned context will not be
// returned to the pool when ReleaseCtx is called.
//
// This is used by the timeout and SSE middlewares to return immediately while a
// goroutine continues using the context safely.
//
// Only call ForceRelease after Abandon if you can guarantee no other goroutine
// (including Fiber's requestHandler and ErrorHandler) will touch the context.
// Callers that cannot make that guarantee themselves can instead call
// ScheduleReclaim, which arranges a race-free ForceRelease once the handler has
// finished and the request handler has released the context.
Abandon()
// IsAbandoned returns true if Abandon() was called on this context.
IsAbandoned() bool
// ForceRelease releases an abandoned context back to the pool.
// This MUST only be called after all goroutines (including requestHandler and
// ErrorHandler) have completely finished using this context. Calling it while
// any goroutine is still running causes races.
ForceRelease()
// ScheduleReclaim arms automatic reclamation of an abandoned context, returning
// it to the pool once it is safe to do so.
//
// handlerDone must be closed once the goroutine that still uses this context
// (for the timeout middleware, the handler goroutine) has completely finished.
// cancel, if non-nil, is the CancelFunc of the context installed for that
// goroutine and is invoked as soon as it finishes.
//
// ForceRelease is performed only after BOTH handlerDone is closed AND the request
// handler has released the context (signaled from ReleaseCtx/releaseDefaultCtx),
// which makes the reclamation race-free. If handlerDone never closes — a handler
// that never returns — the context is intentionally never reclaimed, because the
// handler still owns it.
//
// It may be called more than once per request, also concurrently, as nested
// timeout middlewares do: the context is then reclaimed once every handlerDone is
// closed. Each call must come from a goroutine that still owns the context.
//
// This method calls Abandon internally, so callers do not need to call Abandon
// separately. Calling Abandon before ScheduleReclaim is still safe (idempotent).
ScheduleReclaim(handlerDone <-chan struct{}, cancel context.CancelFunc)
// signalReleased records that the request handler is done touching an abandoned,
// reclaim-armed context (event b). It is a no-op when reclamation was not armed
// and is safe to call multiple times.
signalReleased()
renderExtensions(bind any)
// Bind You can bind body, cookie, headers etc. into the map, map slice, struct easily by using Binding method.
// It gives custom binding support, detailed binding options and more.
// Replacement of: BodyParser, ParamsParser, GetReqHeaders, GetRespHeaders, AllParams, QueryParser, ReqHeaderParser
Bind() *Bind
// Methods to use with next stack.
getMethodInt() int
getIndexRoute() int
getTreePathHash() int
// pathSlashCount lazily counts the '/' bytes of the detection path and caches
// the result for the request; matching uses it to reject route candidates
// without walking their segments. app is the serving App, which can differ
// from c.app when an App value was copied. When it registers no route that
// consults the count, counting is skipped and 0 is returned — a real detection
// path always contains a '/', so 0 doubles as the "unknown" state that makes
// Route.match skip the quick-reject entirely.
pathSlashCount(app *App) int
getDetectionPath() string
getValues() *[maxParams]string
getMatched() bool
getSkipNonUseRoutes() bool
getFirstMatchIndex() int
setIndexHandler(handler int)
setIndexRoute(route int)
setMatched(matched bool)
setSkipNonUseRoutes(skip bool)
setFirstMatchIndex(index int)
setRoute(route *Route)
getPathOriginal() string
// Accepts checks if the specified extensions or content types are acceptable.
Accepts(offers ...string) string
// AcceptsCharsets checks if the specified charset is acceptable.
AcceptsCharsets(offers ...string) string
// AcceptsEncodings checks if the specified encoding is acceptable.
//
// Per RFC 9110 §12.5.3, a missing Accept-Encoding accepts any coding (the first
// offer wins), an empty one only "identity", and "identity" is acceptable unless
// the field excludes it with q=0.
AcceptsEncodings(offers ...string) string
// AcceptsLanguages checks if the specified language is acceptable using
// RFC 4647 Basic Filtering.
AcceptsLanguages(offers ...string) string
// AcceptsLanguagesExtended checks if the specified language is acceptable using
// RFC 4647 Extended Filtering.
AcceptsLanguagesExtended(offers ...string) string
// 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.
BodyRaw() []byte
// tryDecodeBodyInOrder undoes the codings last-applied first and never replaces the request body.
tryDecodeBodyInOrder(encodings []string) ([]byte, error)
// decodeContentCoding undoes one content coding of src's body within BodyLimit.
decodeContentCoding(src *fasthttp.Request, encoding string) ([]byte, error)
// BodyStream returns the request body as a stream, non-nil only when
// Config.StreamRequestBody is enabled and the body is not already buffered.
// Reading it consumes the body, so a later Body call will not see it.
BodyStream() io.Reader
// FullURL returns the full request URL (protocol + host + original URL).
FullURL() string
// UserAgent returns the User-Agent request header.
UserAgent() string
// Referer returns the Referer request header.
Referer() string
// Origin returns the Origin request header.
// 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.
Origin() string
// headerField returns a request header's first non-empty field value, matching
// the field name case-insensitively (RFC 9110 Section 5.1). fieldname.First
// also steps over a present-but-empty first line, so a value on a later line
// is found and this agrees with GetAll on whether the field is there.
headerField(name string) []byte
// AcceptLanguage returns the Accept-Language request header.
// Repeated field lines are combined into one comma-joined list (RFC 9110
// Section 5.2) and the field name matches case-insensitively (Section 5.1),
// matching what AcceptsLanguages negotiates on.
AcceptLanguage() string
// AcceptEncoding returns the Accept-Encoding request header.
// Repeated field lines are combined into one comma-joined list (RFC 9110
// Section 5.2) and the field name matches case-insensitively (Section 5.1),
// matching what AcceptsEncodings negotiates on.
AcceptEncoding() string
// HasHeader reports whether the request includes a header with the given key.
// The field name matches case-insensitively (RFC 9110 Section 5.1), so this
// agrees with GetAll on whether the field is there.
HasHeader(key string) bool
// HasHeaderValue reports whether the request header key lists value as one of
// its comma-separated members, on any of its field lines. Repeated field lines
// are one list (RFC 9110 Section 5.3) and the member matches under ASCII case
// folding, so it fits directive-style headers such as Cache-Control or
// Connection. A comma inside a quoted argument does not end a member, so
// `ext="a,no-transform,b"` is one member and does not list no-transform
// (RFC 9111 permits quoted directive arguments, escaped quotes included). An
// empty value is never present. Only valid within the handler.
HasHeaderValue(key, value string) bool
// MediaType returns the MIME type from the Content-Type header without parameters.
MediaType() string
// Charset returns the charset parameter from the Content-Type header.
Charset() string
// IsJSON reports whether the Content-Type header is JSON.
IsJSON() bool
// IsForm reports whether the Content-Type header is form-encoded.
IsForm() bool
// IsMultipart reports whether the Content-Type header is multipart form data.
IsMultipart() bool
// AcceptsJSON reports whether the Accept header allows JSON.
AcceptsJSON() bool
// AcceptsHTML reports whether the Accept header allows HTML.
AcceptsHTML() bool
// AcceptsXML reports whether the Accept header allows XML.
AcceptsXML() bool
// AcceptsEventStream reports whether the Accept header allows text/event-stream.
AcceptsEventStream() bool
// CookieNames returns the request cookie names in header order, or nil when
// there are none. A repeated name appears once per occurrence, which is how the
// shadowing AllCookies collapses is detected. The strings are copies.
CookieNames() []string
// AllCookies returns the request cookies as a name/value map, or nil when there
// are none. A repeated name resolves to its first occurrence, as Cookies does,
// so a shadowed cookie cannot be validated in one and consumed in the other.
AllCookies() map[string]string
// FormFile returns the first file by key from a MultipartForm.
// The multipart form is parsed using the application's BodyLimit to prevent
// unbounded memory usage.
FormFile(key string) (*multipart.FileHeader, error)
// 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.
// When the request is a multipart form, it is parsed using the application's
// BodyLimit so the configured limit is consistently enforced.
//
// On a form request this lowercases the case-insensitive parts of the request's
// own Content-Type, so a value obtained earlier from Get(HeaderContentType) —
// which aliases those bytes unless Immutable is set — can change during the
// call. Copy it first if you need it to outlive one.
FormValue(key string, defaultValue ...string) string
// 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.
// Freshness only applies to GET and HEAD requests; for any other method false is
// returned, as RFC 9110 defines 304 Not Modified only for those methods and
// requires If-Modified-Since to be ignored otherwise.
// The response status must be 2xx or 304; redirects and errors are never fresh.
// 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/master/index.js#L33
Fresh() bool
// IfNoneMatch returns the entity tags in the If-None-Match request header,
// verbatim and unvalidated; a comma inside a quoted opaque-tag does not split
// one. Fresh already compares them. Only valid within the handler.
IfNoneMatch() []string
// IfModifiedSince returns the time carried by the If-Modified-Since request
// header, ErrHeaderNotFound when it is absent or empty, and a parse error when
// it is none of the HTTP-date formats RFC 9110 Section 5.6.7 requires.
IfModifiedSince() (time.Time, error)
// GetAll returns every field line stored under key, where Get returns only the
// first, or nil when the header is absent. Empty lines are skipped, so its
// presence answers as HasHeader does. Only valid within the handler.
GetAll(key string) []string
// Authorization splits the Authorization header into auth-scheme and credentials
// (RFC 9110 Section 11.6.2), neither decoded nor validated. They view the request
// buffer: a credential kept past the handler becomes another request's.
Authorization() (scheme, credentials string)
// authorizationParts splits the Authorization header at the first space or tab
// (RFC 9110 Section 11.4), on raw bytes so each caller materializes only the
// strings it needs. A lone token is a scheme without credentials.
authorizationParts() (scheme, credentials []byte)
// Bearer returns the credentials of a Bearer Authorization header (RFC 6750
// Section 2.1), unverified, or "" for another scheme. It views the request
// buffer: a token kept past the handler becomes another request's.
Bearer() string
// 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 if your app is behind a proxy.
Host() string
// 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 if your app is behind a proxy.
Hostname() string
// Port returns the remote port of the request.
Port() string
// IP returns the client's IP address. When the request comes from a trusted proxy (see
// [TrustProxyConfig]) and Config.ProxyHeader is set, the value is taken from that header.
// With Config.EnableIPValidation enabled and proxy IPs or ranges configured (Proxies,
// Loopback, Private or LinkLocal), the X-Forwarded-For chain is walked right-to-left, every
// trusted proxy IP is skipped and the first non-trusted IP is returned; with validation
// enabled but only UnixSocket trusted, the first valid IP from the left is returned. With
// validation disabled (the default), the raw header value is returned as-is, which for
// X-Forwarded-For may be the whole comma-separated chain. Enable validation whenever the
// result is used as a single client identifier and the header can carry a chain, for example
// by the limiter middleware or an allowlist; a proxy that overwrites the header with one
// address, or a single-IP header, does not need it. Please use Config.TrustProxy to prevent
// header spoofing if your app is behind a proxy.
IP() string
// extractIPsFromHeader will return a slice of IPs it found given a header name in the order they appear.
// Empty elements are ignored after trimming optional whitespace.
// When IP validation is enabled, any invalid IPs will be omitted.
extractIPsFromHeader(header string) []string
// extractIPFromHeader returns the client IP from the given proxy header by walking the
// X-Forwarded-For chain from right to left and stripping trusted proxy IPs. When trusted
// proxies are configured, the rightmost non-trusted IP is returned, and an entry that is not
// an IP ends the walk; otherwise the first valid IP (left-to-right) is returned. When IP
// validation is disabled, the raw header value is returned as-is.
extractIPFromHeader(header string) string
// hasTrustedProxyConfig returns true if any trusted proxy configuration is set.
hasTrustedProxyConfig() bool
// isTrustedProxyIP checks whether the given IP string matches any configured trusted proxy.
isTrustedProxyIP(ipStr string) bool
// 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.
IPs() []string
// 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
Is(extension string) bool
// HasBody returns true if the request declares a body via Content-Length, Transfer-Encoding, or already buffered payload data.
HasBody() bool
// IsWebSocket returns true if the request includes a WebSocket upgrade handshake.
IsWebSocket() bool
// IsPreflight returns true if the request is a CORS preflight.
IsPreflight() bool
// Secure returns whether a secure connection was established.
Secure() bool
// XHR returns a Boolean property, that is true, if the request's X-Requested-With header field is XMLHttpRequest,
// indicating that the request was issued by a client library (such as jQuery).
XHR() bool
// 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.
//
// Storing through the Ctx interface heap-allocates the one-element slice the
// variadic value is packed into; SetLocal stores the same value without it.
Locals(key any, value ...any) any
// SetLocal stores value under key scoped to the request, exactly as
// Locals(key, value) does: the value is available to all following routes that
// match the request, removed after the top RequestHandler returns, and its
// Close method is called first if it implements io.Closer. Like Locals, it
// stores nothing while the context is released. A Ctx must not be used past
// its handler either way, because the pool hands the same one to the next
// request.
//
// Locals takes its value variadically, and reached through the Ctx interface
// the compiler cannot see that the callee only reads that argument, so the
// one-element "..." slice is heap-allocated on every call. SetLocal takes the
// value directly, so that slice is never built. Boxing a value that is not
// already an interface still allocates, exactly as it does for Locals.
SetLocal(key, value any)
// Method returns the HTTP request method for the context, optionally overridden by the provided argument.
// If no override is given or if the provided override is not a valid HTTP method, it returns the current method from the context.
// Otherwise, it updates the context's method and returns the overridden method as a string.
Method(override ...string) string
// IsSafe reports whether the request method is safe, meaning it is not expected
// to change server state (RFC 9110 Section 9.2.1).
IsSafe() bool
// IsIdempotent reports whether the request method is idempotent, meaning
// repeating it has the same intended effect as making it once (RFC 9110
// Section 9.2.2). Every safe method is also idempotent.
IsIdempotent() bool
// MultipartForm parse form entries from binary.
// This returns a map[string][]string, so given a key, the value will be a string slice.
//
// On a form request this lowercases the case-insensitive parts of the request's
// own Content-Type, so a value obtained earlier from Get(HeaderContentType) —
// which aliases those bytes unless Immutable is set — can change during the
// call. Copy it first if you need it to outlive one.
MultipartForm() (*multipart.Form, error)
// URI returns the parsed *fasthttp.URI of the request, giving access to all
// fasthttp URI methods. It is owned by the request and rewritten by a Path
// override, so it is only valid within the handler.
URI() *fasthttp.URI
// Path returns the path part of the request URL, normalized before routing
// (see Config.UnescapePath); OriginalURL returns the request target as sent.
// Optionally, you could override the path.
// Make copies or use the Immutable setting to use the value outside the Handler.
Path(override ...string) string
// Params is used to get the route parameters.
// Defaults to empty string "" if the param doesn't exist.
// If a default value is given, it will return that value if the param doesn't exist.
// 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.
Params(key string, defaultValue ...string) string
// Scheme contains the request protocol string: http or https for TLS requests.
// Please use Config.TrustProxy to prevent header spoofing if your app is behind a proxy.
Scheme() string
// Protocol returns the HTTP protocol of request: HTTP/1.1 and HTTP/2.
Protocol() string
// Query returns the query string parameter in the url.
// Defaults to empty string "" if the query doesn't exist.
// If a default value is given, it will return that value if the query doesn't exist.
// 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.
Query(key string, defaultValue ...string) string
// Queries returns a map of query parameters and their values.
//
// GET /?name=alex&wanna_cake=2&id=
// Queries()["name"] == "alex"
// Queries()["wanna_cake"] == "2"
// Queries()["id"] == ""
//
// GET /?field1=value1&field1=value2&field2=value3
// Queries()["field1"] == "value2"
// Queries()["field2"] == "value3"
//
// GET /?list_a=1&list_a=2&list_a=3&list_b[]=1&list_b[]=2&list_b[]=3&list_c=1,2,3
// Queries()["list_a"] == "3"
// Queries()["list_b[]"] == "3"
// Queries()["list_c"] == "1,2,3"
//
// GET /api/search?filters.author.name=John&filters.category.name=Technology&filters[customer][name]=Alice&filters[status]=pending
// Queries()["filters.author.name"] == "John"
// Queries()["filters.category.name"] == "Technology"
// Queries()["filters[customer][name]"] == "Alice"
// Queries()["filters[status]"] == "pending"
Queries() map[string]string
// Range returns a struct containing the type and a slice of ranges.
Range(size int64) (Range, error)
// Subdomains returns a slice of subdomains from the host, excluding the last `offset` components.
// If the offset is negative or exceeds the number of subdomains, an empty slice is returned.
// If the offset is zero every label (no trimming) is returned.
Subdomains(offset ...int) []string
// Stale returns the inverse of Fresh, indicating if the client's cached response is considered stale.
Stale() bool
// IsProxyTrusted checks trustworthiness of remote ip.
// If Config.TrustProxy false, it returns false.
// IsProxyTrusted can check remote ip by proxy ranges and ip map.
IsProxyTrusted() bool
// IsFromLocal will return true if request came from a loopback IP.
IsFromLocal() bool
// IsFromUnixSocket returns true if the request arrived over a Unix domain socket.
IsFromUnixSocket() bool
getBody() []byte
// bufferBodyStream applies BodyLimit to a streamed body and answers a larger one 413 while no response body was written, as the server would.
bufferBodyStream() error
// 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.
Append(field string, values ...string)
// 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, Content-Encoding, Content-Length, Connection and
// Server are replaced, and Transfer-Encoding and Date are ignored because fasthttp
// writes them itself. Set-Cookie is slotted too but does append, though Cookie
// builds that field value for you. Trailer accumulates, extending the announced set.
Add(key, val string)
// Attachment sets the HTTP response Content-Disposition header field to attachment.
Attachment(filename ...string)
// 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.
ClearCookie(key ...string)
// 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.
Cookie(cookie *Cookie)
// 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.
GetCookie(name string) (*Cookie, bool)
// 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.
GetCookies() []*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.
Download(file string, filename ...string) error
// 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.
Format(handlers ...ResFmt) error
// 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.
AutoFormat(body any) error
// 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.
Del(key string)
// 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.
JSON(data any, ctype ...string) error
// 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.
MsgPack(data any, ctype ...string) error
// 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.
CBOR(data any, ctype ...string) error
// 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.
JSONP(data any, callback ...string) error
// XML converts any interface or string to XML.
// This method also sets the content header to application/xml; charset=utf-8.
XML(data any) error
// Links joins the links followed by the property to populate the response's Link HTTP header field.
// Like Express, it adds to a Link header that is already set, such as the preload links
// SendEarlyHints writes, instead of replacing it.
Links(link ...string)
// Location sets the response Location HTTP header to the specified path parameter.
Location(path string)
// getLocationFromRoute gets the URL location from a route using parameters.
// Nil receivers and missing routes return ErrNotFound to match Route.URL semantics.
getLocationFromRoute(route *Route, params Map) (string, error)
// GetRouteURL generates URLs to named routes, with parameters. URLs are relative, for example: "/user/1831"
GetRouteURL(routeName string, params Map) (string, error)
// Render a template with data and sends a text/html response.
// We support the following engines: https://github.com/gofiber/template
// Render does not modify bind, so a Map may be reused across requests.
Render(name string, bind any, layouts ...string) error
// ResetBody discards the response body, keeping the status and headers.
// Use it before replacing a partially written body — an error page over a
// half-rendered view, a cached body over a fresh one.
ResetBody()
// Written reports whether anything has been written to the response body, so a
// handler that produced one can be told from a handler that did not. A stream
// counts without being drained; a status or header alone does not.
Written() bool
// Send sets the HTTP response body without copying it.
// From this point onward the body argument must not be changed.
Send(body []byte) error
// SendEarlyHints allows the server to hint to the browser what resources a page would need
// so the browser can preload them while waiting for the server's full response. Only Link
// headers already written to the response will be transmitted as Early Hints.
//
// This is a HTTP/2+ feature but all browsers will either understand it or safely ignore it.
//
// NOTE: Older HTTP/1.1 non-browser clients may face compatibility issues.
//
// See: https://developer.chrome.com/docs/web-platform/early-hints and
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Link#syntax
SendEarlyHints(hints []string) error
// SendFile transfers the file from the specified path.
// By default, the file is not compressed. To enable compression, set SendFile.Compress to true.
// The Content-Type response HTTP header field is set based on the file's extension.
// If the file extension is missing or invalid, the Content-Type is detected from the file's format.
SendFile(file string, config ...SendFile) error
// NoContent replies 204 No Content. SendStatus already discards the body; this
// drops the Content-Type too, since RFC 9110 Section 6.4.1 gives a 204 no
// content to describe. SendStatus(204) keeps it, so the two differ.
NoContent() error
// SendStatus sets the HTTP status code and if the response body is empty,
// it sets the correct status message in the body.
SendStatus(status int) error
// SendString sets the HTTP response body for string types.
// This means no type assertion, recommended for faster performance
SendString(body string) error
// SendStream sets response body stream and optional body size.
SendStream(stream io.Reader, size ...int) error
// SendStreamWriter sets response body stream writer
SendStreamWriter(streamWriter func(*bufio.Writer)) error
// Set sets the response's HTTP header field to the specified key, value.
Set(key, val string)
setCanonical(key, val string)
// StatusCode returns the status code set on the response, the read side of
// Status, and reports 200 until something sets another. After Next it is the
// status the chain settled on.
StatusCode() int
// Type sets the Content-Type HTTP header to the MIME type specified by the file extension.
Type(extension string, charset ...string) Ctx
// Vary adds the given header field to the Vary response header.
// This will append the header, if not already listed; otherwise, leaves it listed in the current location.
// Field names are compared case-insensitively (RFC 9110 Section 5.1); the first spelling is kept.
// Per RFC 9110 Section 12.5.5 the wildcard "*" only has meaning as the sole member of the field:
// once "*" is added (or already present), the header is collapsed to a single "*".
Vary(fields ...string)
// Write appends p into response body.
Write(p []byte) (int, error)
// Writef appends f & a into response body writer.
Writef(f string, a ...any) (int, error)
// WriteString appends s to response body.
WriteString(s string) (int, error)
// Drop closes the underlying connection without sending any response headers or body.
// This can be useful for silently terminating client connections, such as in DDoS mitigation
// or when blocking access to sensitive endpoints.
Drop() error
// End immediately flushes the current response and closes the underlying connection.
//
// Note: End does not work when using streaming (e.g. fasthttp's HijackConn or SendStream),
// because in streaming mode the connection is managed asynchronously and ctx.Conn() may return nil.
End() error
}