Root

github.com/gofiber/fiber/v3

import "github.com/gofiber/fiber/v3"

Package fiber is an Express inspired web framework built on top of Fasthttp, the fastest HTTP engine for Go. Designed to ease things up for fast development with zero memory allocation and performance in mind.

Constants

Default Config values

Source: app.go:662

const (
	DefaultBodyLimit       = 4 * 1024 * 1024
	DefaultMaxRanges       = 16
	DefaultConcurrency     = 256 * 1024
	DefaultReadBufferSize  = 8192
	DefaultWriteBufferSize = 8192
)

BindError source constants for BindError.Source.

Source: bind.go:49

const (
	BindSourceURI        = "uri"
	BindSourceQuery      = "query"
	BindSourceHeader     = "header"
	BindSourceCookie     = "cookie"
	BindSourceBody       = "body"
	BindSourceRespHeader = "respHeader"
)

HTTP methods were copied from net/http.

Source: constants.go:9

const (
	MethodGet     = "GET"     // RFC 7231, 4.3.1
	MethodHead    = "HEAD"    // RFC 7231, 4.3.2
	MethodPost    = "POST"    // RFC 7231, 4.3.3
	MethodPut     = "PUT"     // RFC 7231, 4.3.4
	MethodPatch   = "PATCH"   // RFC 5789
	MethodDelete  = "DELETE"  // RFC 7231, 4.3.5
	MethodConnect = "CONNECT" // RFC 7231, 4.3.6
	MethodOptions = "OPTIONS" // RFC 7231, 4.3.7
	MethodTrace   = "TRACE"   // RFC 7231, 4.3.8
	MethodQuery   = "QUERY"   // RFC 10008

)

MIME types that are commonly used

Source: constants.go:24

const (
	MIMETextXML               = "text/xml"
	MIMETextHTML              = "text/html"
	MIMETextPlain             = "text/plain"
	MIMETextJavaScript        = "text/javascript"
	MIMETextCSS               = "text/css"
	MIMETextEventStream       = "text/event-stream"
	MIMEApplicationXML        = "application/xml"
	MIMEApplicationJSON       = "application/json"
	MIMEApplicationJavaScript = "application/javascript"
	MIMEApplicationCBOR       = "application/cbor"
	MIMEApplicationForm       = "application/x-www-form-urlencoded"
	MIMEOctetStream           = "application/octet-stream"
	MIMEMultipartForm         = "multipart/form-data"
	MIMEApplicationMsgPack    = "application/vnd.msgpack"

	MIMETextXMLCharsetUTF8         = "text/xml; charset=utf-8"
	MIMETextHTMLCharsetUTF8        = "text/html; charset=utf-8"
	MIMETextPlainCharsetUTF8       = "text/plain; charset=utf-8"
	MIMETextJavaScriptCharsetUTF8  = "text/javascript; charset=utf-8"
	MIMETextCSSCharsetUTF8         = "text/css; charset=utf-8"
	MIMEApplicationXMLCharsetUTF8  = "application/xml; charset=utf-8"
	MIMEApplicationJSONCharsetUTF8 = "application/json; charset=utf-8"
)

HTTP status codes were copied from net/http with the following updates: - Rename StatusNonAuthoritativeInfo to StatusNonAuthoritativeInformation - Add StatusSwitchProxy (306) NOTE: Keep this list in sync with statusMessage

Source: constants.go:53

const (
	StatusContinue           = 100 // RFC 9110, 15.2.1
	StatusSwitchingProtocols = 101 // RFC 9110, 15.2.2
	StatusProcessing         = 102 // RFC 2518, 10.1
	StatusEarlyHints         = 103 // RFC 8297

	StatusOK                          = 200 // RFC 9110, 15.3.1
	StatusCreated                     = 201 // RFC 9110, 15.3.2
	StatusAccepted                    = 202 // RFC 9110, 15.3.3
	StatusNonAuthoritativeInformation = 203 // RFC 9110, 15.3.4
	StatusNoContent                   = 204 // RFC 9110, 15.3.5
	StatusResetContent                = 205 // RFC 9110, 15.3.6
	StatusPartialContent              = 206 // RFC 9110, 15.3.7
	StatusMultiStatus                 = 207 // RFC 4918, 11.1
	StatusAlreadyReported             = 208 // RFC 5842, 7.1
	StatusIMUsed                      = 226 // RFC 3229, 10.4.1

	StatusMultipleChoices   = 300 // RFC 9110, 15.4.1
	StatusMovedPermanently  = 301 // RFC 9110, 15.4.2
	StatusFound             = 302 // RFC 9110, 15.4.3
	StatusSeeOther          = 303 // RFC 9110, 15.4.4
	StatusNotModified       = 304 // RFC 9110, 15.4.5
	StatusUseProxy          = 305 // RFC 9110, 15.4.6
	StatusSwitchProxy       = 306 // RFC 9110, 15.4.7 (Unused)
	StatusTemporaryRedirect = 307 // RFC 9110, 15.4.8
	StatusPermanentRedirect = 308 // RFC 9110, 15.4.9

	StatusBadRequest                   = 400 // RFC 9110, 15.5.1
	StatusUnauthorized                 = 401 // RFC 9110, 15.5.2
	StatusPaymentRequired              = 402 // RFC 9110, 15.5.3
	StatusForbidden                    = 403 // RFC 9110, 15.5.4
	StatusNotFound                     = 404 // RFC 9110, 15.5.5
	StatusMethodNotAllowed             = 405 // RFC 9110, 15.5.6
	StatusNotAcceptable                = 406 // RFC 9110, 15.5.7
	StatusProxyAuthRequired            = 407 // RFC 9110, 15.5.8
	StatusRequestTimeout               = 408 // RFC 9110, 15.5.9
	StatusConflict                     = 409 // RFC 9110, 15.5.10
	StatusGone                         = 410 // RFC 9110, 15.5.11
	StatusLengthRequired               = 411 // RFC 9110, 15.5.12
	StatusPreconditionFailed           = 412 // RFC 9110, 15.5.13
	StatusRequestEntityTooLarge        = 413 // RFC 9110, 15.5.14
	StatusRequestURITooLong            = 414 // RFC 9110, 15.5.15
	StatusUnsupportedMediaType         = 415 // RFC 9110, 15.5.16
	StatusRequestedRangeNotSatisfiable = 416 // RFC 9110, 15.5.17
	StatusExpectationFailed            = 417 // RFC 9110, 15.5.18
	StatusTeapot                       = 418 // RFC 9110, 15.5.19 (Unused)
	StatusMisdirectedRequest           = 421 // RFC 9110, 15.5.20
	StatusUnprocessableEntity          = 422 // RFC 9110, 15.5.21
	StatusLocked                       = 423 // RFC 4918, 11.3
	StatusFailedDependency             = 424 // RFC 4918, 11.4
	StatusTooEarly                     = 425 // RFC 8470, 5.2.
	StatusUpgradeRequired              = 426 // RFC 9110, 15.5.22
	StatusPreconditionRequired         = 428 // RFC 6585, 3
	StatusTooManyRequests              = 429 // RFC 6585, 4
	StatusRequestHeaderFieldsTooLarge  = 431 // RFC 6585, 5
	StatusUnavailableForLegalReasons   = 451 // RFC 7725, 3

	StatusInternalServerError           = 500 // RFC 9110, 15.6.1
	StatusNotImplemented                = 501 // RFC 9110, 15.6.2
	StatusBadGateway                    = 502 // RFC 9110, 15.6.3
	StatusServiceUnavailable            = 503 // RFC 9110, 15.6.4
	StatusGatewayTimeout                = 504 // RFC 9110, 15.6.5
	StatusHTTPVersionNotSupported       = 505 // RFC 9110, 15.6.6
	StatusVariantAlsoNegotiates         = 506 // RFC 2295, 8.1
	StatusInsufficientStorage           = 507 // RFC 4918, 11.5
	StatusLoopDetected                  = 508 // RFC 5842, 7.2
	StatusNotExtended                   = 510 // RFC 2774, 7
	StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6
)

HTTP Headers were copied from net/http.

Source: constants.go:169

const (
	HeaderAuthorization                      = "Authorization"
	HeaderProxyAuthenticate                  = "Proxy-Authenticate"
	HeaderProxyAuthorization                 = "Proxy-Authorization"
	HeaderWWWAuthenticate                    = "WWW-Authenticate"
	HeaderAge                                = "Age"
	HeaderCacheControl                       = "Cache-Control"
	HeaderClearSiteData                      = "Clear-Site-Data"
	HeaderExpires                            = "Expires"
	HeaderPragma                             = "Pragma"
	HeaderWarning                            = "Warning"
	HeaderAcceptCH                           = "Accept-CH"
	HeaderAcceptCHLifetime                   = "Accept-CH-Lifetime"
	HeaderContentDPR                         = "Content-DPR"
	HeaderDPR                                = "DPR"
	HeaderEarlyData                          = "Early-Data"
	HeaderSaveData                           = "Save-Data"
	HeaderViewportWidth                      = "Viewport-Width"
	HeaderWidth                              = "Width"
	HeaderETag                               = "ETag"
	HeaderIfMatch                            = "If-Match"
	HeaderIfModifiedSince                    = "If-Modified-Since"
	HeaderIfNoneMatch                        = "If-None-Match"
	HeaderIfUnmodifiedSince                  = "If-Unmodified-Since"
	HeaderLastModified                       = "Last-Modified"
	HeaderVary                               = "Vary"
	HeaderConnection                         = "Connection"
	HeaderKeepAlive                          = "Keep-Alive"
	HeaderAccept                             = "Accept"
	HeaderAcceptCharset                      = "Accept-Charset"
	HeaderAcceptEncoding                     = "Accept-Encoding"
	HeaderAcceptLanguage                     = "Accept-Language"
	HeaderCookie                             = "Cookie"
	HeaderExpect                             = "Expect"
	HeaderMaxForwards                        = "Max-Forwards"
	HeaderSetCookie                          = "Set-Cookie"
	HeaderSetCookie2                         = "Set-Cookie2"
	HeaderAccessControlAllowCredentials      = "Access-Control-Allow-Credentials"
	HeaderAccessControlAllowHeaders          = "Access-Control-Allow-Headers"
	HeaderAccessControlAllowMethods          = "Access-Control-Allow-Methods"
	HeaderAccessControlAllowOrigin           = "Access-Control-Allow-Origin"
	HeaderAccessControlExposeHeaders         = "Access-Control-Expose-Headers"
	HeaderAccessControlMaxAge                = "Access-Control-Max-Age"
	HeaderAccessControlRequestHeaders        = "Access-Control-Request-Headers"
	HeaderAccessControlRequestMethod         = "Access-Control-Request-Method"
	HeaderOrigin                             = "Origin"
	HeaderTimingAllowOrigin                  = "Timing-Allow-Origin"
	HeaderXPermittedCrossDomainPolicies      = "X-Permitted-Cross-Domain-Policies"
	HeaderDNT                                = "DNT"
	HeaderTk                                 = "Tk"
	HeaderContentDisposition                 = "Content-Disposition"
	HeaderContentEncoding                    = "Content-Encoding"
	HeaderContentLanguage                    = "Content-Language"
	HeaderContentLength                      = "Content-Length"
	HeaderContentLocation                    = "Content-Location"
	HeaderContentType                        = "Content-Type"
	HeaderForwarded                          = "Forwarded"
	HeaderVia                                = "Via"
	HeaderXForwardedFor                      = "X-Forwarded-For"
	HeaderXForwardedHost                     = "X-Forwarded-Host"
	HeaderXForwardedProto                    = "X-Forwarded-Proto"
	HeaderXForwardedProtocol                 = "X-Forwarded-Protocol"
	HeaderXForwardedSsl                      = "X-Forwarded-Ssl"
	HeaderXUrlScheme                         = "X-Url-Scheme"
	HeaderLocation                           = "Location"
	HeaderFrom                               = "From"
	HeaderHost                               = "Host"
	HeaderReferer                            = "Referer"
	HeaderReferrerPolicy                     = "Referrer-Policy"
	HeaderUserAgent                          = "User-Agent"
	HeaderAllow                              = "Allow"
	HeaderServer                             = "Server"
	HeaderAcceptRanges                       = "Accept-Ranges"
	HeaderContentRange                       = "Content-Range"
	HeaderIfRange                            = "If-Range"
	HeaderRange                              = "Range"
	HeaderContentSecurityPolicy              = "Content-Security-Policy"
	HeaderContentSecurityPolicyReportOnly    = "Content-Security-Policy-Report-Only"
	HeaderCrossOriginResourcePolicy          = "Cross-Origin-Resource-Policy"
	HeaderExpectCT                           = "Expect-CT"
	HeaderPermissionsPolicy                  = "Permissions-Policy"
	HeaderPublicKeyPins                      = "Public-Key-Pins"
	HeaderPublicKeyPinsReportOnly            = "Public-Key-Pins-Report-Only"
	HeaderStrictTransportSecurity            = "Strict-Transport-Security"
	HeaderUpgradeInsecureRequests            = "Upgrade-Insecure-Requests"
	HeaderXContentTypeOptions                = "X-Content-Type-Options"
	HeaderXDownloadOptions                   = "X-Download-Options"
	HeaderXFrameOptions                      = "X-Frame-Options"
	HeaderXPoweredBy                         = "X-Powered-By"
	HeaderXXSSProtection                     = "X-XSS-Protection"
	HeaderLastEventID                        = "Last-Event-ID"
	HeaderNEL                                = "NEL"
	HeaderPingFrom                           = "Ping-From"
	HeaderPingTo                             = "Ping-To"
	HeaderReportTo                           = "Report-To"
	HeaderTE                                 = "TE"
	HeaderTrailer                            = "Trailer"
	HeaderTransferEncoding                   = "Transfer-Encoding"
	HeaderSecFetchSite                       = "Sec-Fetch-Site"
	HeaderSecWebSocketAccept                 = "Sec-WebSocket-Accept"
	HeaderSecWebSocketExtensions             = "Sec-WebSocket-Extensions"
	HeaderSecWebSocketKey                    = "Sec-WebSocket-Key"
	HeaderSecWebSocketProtocol               = "Sec-WebSocket-Protocol"
	HeaderSecWebSocketVersion                = "Sec-WebSocket-Version"
	HeaderAcceptPatch                        = "Accept-Patch"
	HeaderAcceptPushPolicy                   = "Accept-Push-Policy"
	HeaderAcceptSignature                    = "Accept-Signature"
	HeaderAltSvc                             = "Alt-Svc"
	HeaderDate                               = "Date"
	HeaderDeprecation                        = "Deprecation"
	HeaderIndex                              = "Index"
	HeaderLargeAllocation                    = "Large-Allocation"
	HeaderLink                               = "Link"
	HeaderPushPolicy                         = "Push-Policy"
	HeaderRetryAfter                         = "Retry-After"
	HeaderServerTiming                       = "Server-Timing"
	HeaderSignature                          = "Signature"
	HeaderSignedHeaders                      = "Signed-Headers"
	HeaderSourceMap                          = "SourceMap"
	HeaderSunset                             = "Sunset"
	HeaderUpgrade                            = "Upgrade"
	HeaderXDNSPrefetchControl                = "X-DNS-Prefetch-Control"
	HeaderXPingback                          = "X-Pingback"
	HeaderXRequestID                         = "X-Request-ID"
	HeaderXRequestedWith                     = "X-Requested-With"
	HeaderXResponseTime                      = "X-Response-Time"
	HeaderXRobotsTag                         = "X-Robots-Tag"
	HeaderXUACompatible                      = "X-UA-Compatible"
	HeaderAccessControlAllowPrivateNetwork   = "Access-Control-Allow-Private-Network"
	HeaderAccessControlRequestPrivateNetwork = "Access-Control-Request-Private-Network"
)

Network types that are commonly used

Source: constants.go:302

const (
	NetworkTCP  = "tcp"
	NetworkTCP4 = "tcp4"
	NetworkTCP6 = "tcp6"
	NetworkUnix = "unix"
)

Compression types

Source: constants.go:310

const (
	StrGzip     = "gzip"
	StrCompress = "compress"
	StrIdentity = "identity"
	StrBr       = "br"
	StrDeflate  = "deflate"
	StrBrotli   = "brotli"
	StrZstd     = "zstd"
)

Source: constants.go:322

const (
	CookieSameSiteDisabled   = internalcookie.SameSiteDisabled // not in RFC, just control "SameSite" attribute will not be set.
	CookieSameSiteLaxMode    = internalcookie.SameSiteLax
	CookieSameSiteStrictMode = internalcookie.SameSiteStrict
	CookieSameSiteNoneMode   = internalcookie.SameSiteNone
)

Route Constraints

Source: constants.go:330

const (
	ConstraintInt             = "int"
	ConstraintBool            = "bool"
	ConstraintFloat           = "float"
	ConstraintAlpha           = "alpha"
	ConstraintGUID            = "guid"
	ConstraintMinLen          = "minLen"
	ConstraintMaxLen          = "maxLen"
	ConstraintLen             = "len"
	ConstraintBetweenLen      = "betweenLen"
	ConstraintMinLenLower     = "minlen"
	ConstraintMaxLenLower     = "maxlen"
	ConstraintBetweenLenLower = "betweenlen"
	ConstraintMin             = "min"
	ConstraintMax             = "max"
	ConstraintRange           = "range"
	ConstraintDatetime        = "datetime"
	ConstraintRegex           = "regex"
)

FlashCookieName Cookie name to send flash messages when to use redirection.

Source: redirect.go:47

const (
	FlashCookieName = "fiber_flash"
)

Version of current fiber package

Source: app.go:40

const Version = "3.7.0"

Source: hooks.go:57

const (
	// StartupMessageLevelInfo represents informational startup message entries.
	StartupMessageLevelInfo StartupMessageLevel = iota
	// StartupMessageLevelWarning represents warning startup message entries.
	StartupMessageLevelWarning
	// StartupMessageLevelError represents error startup message entries.
	StartupMessageLevelError
)

Variables

Errors

Source: constants.go:124

var (
	ErrBadRequest                   = NewError(StatusBadRequest)                   // 400
	ErrUnauthorized                 = NewError(StatusUnauthorized)                 // 401
	ErrPaymentRequired              = NewError(StatusPaymentRequired)              // 402
	ErrForbidden                    = NewError(StatusForbidden)                    // 403
	ErrNotFound                     = NewError(StatusNotFound)                     // 404
	ErrMethodNotAllowed             = NewError(StatusMethodNotAllowed)             // 405
	ErrNotAcceptable                = NewError(StatusNotAcceptable)                // 406
	ErrProxyAuthRequired            = NewError(StatusProxyAuthRequired)            // 407
	ErrRequestTimeout               = NewError(StatusRequestTimeout)               // 408
	ErrConflict                     = NewError(StatusConflict)                     // 409
	ErrGone                         = NewError(StatusGone)                         // 410
	ErrLengthRequired               = NewError(StatusLengthRequired)               // 411
	ErrPreconditionFailed           = NewError(StatusPreconditionFailed)           // 412
	ErrRequestEntityTooLarge        = NewError(StatusRequestEntityTooLarge)        // 413
	ErrRequestURITooLong            = NewError(StatusRequestURITooLong)            // 414
	ErrUnsupportedMediaType         = NewError(StatusUnsupportedMediaType)         // 415
	ErrRequestedRangeNotSatisfiable = NewError(StatusRequestedRangeNotSatisfiable) // 416
	ErrExpectationFailed            = NewError(StatusExpectationFailed)            // 417
	ErrTeapot                       = NewError(StatusTeapot)                       // 418
	ErrMisdirectedRequest           = NewError(StatusMisdirectedRequest)           // 421
	ErrUnprocessableEntity          = NewError(StatusUnprocessableEntity)          // 422
	ErrLocked                       = NewError(StatusLocked)                       // 423
	ErrFailedDependency             = NewError(StatusFailedDependency)             // 424
	ErrTooEarly                     = NewError(StatusTooEarly)                     // 425
	ErrUpgradeRequired              = NewError(StatusUpgradeRequired)              // 426
	ErrPreconditionRequired         = NewError(StatusPreconditionRequired)         // 428
	ErrTooManyRequests              = NewError(StatusTooManyRequests)              // 429
	ErrRequestHeaderFieldsTooLarge  = NewError(StatusRequestHeaderFieldsTooLarge)  // 431
	ErrUnavailableForLegalReasons   = NewError(StatusUnavailableForLegalReasons)   // 451

	ErrInternalServerError           = NewError(StatusInternalServerError)           // 500
	ErrNotImplemented                = NewError(StatusNotImplemented)                // 501
	ErrBadGateway                    = NewError(StatusBadGateway)                    // 502
	ErrServiceUnavailable            = NewError(StatusServiceUnavailable)            // 503
	ErrGatewayTimeout                = NewError(StatusGatewayTimeout)                // 504
	ErrHTTPVersionNotSupported       = NewError(StatusHTTPVersionNotSupported)       // 505
	ErrVariantAlsoNegotiates         = NewError(StatusVariantAlsoNegotiates)         // 506
	ErrInsufficientStorage           = NewError(StatusInsufficientStorage)           // 507
	ErrLoopDetected                  = NewError(StatusLoopDetected)                  // 508
	ErrNotExtended                   = NewError(StatusNotExtended)                   // 510
	ErrNetworkAuthenticationRequired = NewError(StatusNetworkAuthenticationRequired) // 511
)

General errors

Source: error.go:16

var (
	ErrGracefulTimeout = errors.New("shutdown: graceful timeout has been reached, exiting")
	// ErrNotRunning indicates that a Shutdown method was called when the server was not running.
	ErrNotRunning = errors.New("shutdown: server is not running")
	// ErrHandlerExited is returned by App.Test if a handler panics or calls runtime.Goexit().
	ErrHandlerExited = errors.New("runtime.Goexit() called in handler or server panic")
	// ErrNoViewEngineConfigured indicates that a helper requiring a view engine was invoked without one configured.
	ErrNoViewEngineConfigured = errors.New("fiber: no view engine configured")
	// ErrAutoCertWithCertFile indicates AutoCertManager cannot be used with CertFile/CertKeyFile.
	ErrAutoCertWithCertFile = errors.New("tls: AutoCertManager cannot be combined with CertFile/CertKeyFile")
	// ErrRouteNotRepresentable indicates a route whose path no relative URL can
	// name, so Route.URL, GetRouteURL and Redirect().Route cannot compose one.
	// A path starting with two or more slashes is such a route: the URL that
	// would reach it opens an authority instead.
	ErrRouteNotRepresentable = errors.New("router: route path cannot be expressed as a relative URL")
)

Range errors

Source: error.go:42

var (
	// ErrRangeMalformed is returned for a syntactically invalid Range header,
	// which RFC 9110 Section 14.2 allows a server to reject; it carries a
	// 400 Bad Request status so propagating it does not surface as a 500.
	ErrRangeMalformed = NewError(StatusBadRequest, "range: malformed range header string")
	// ErrRangeUnsupported is returned for a Range header whose range unit is
	// not "bytes". RFC 9110 Section 14.2 requires an origin server to IGNORE
	// a Range header field with a range unit it does not understand, so
	// callers receiving this error should serve the full representation
	// instead of returning an error response. It still carries a
	// 400 Bad Request status as a safety net, so blind propagation does not
	// surface as a 500.
	ErrRangeUnsupported   = NewError(StatusBadRequest, "range: unsupported range unit")
	ErrRangeTooLarge      = NewError(StatusRequestedRangeNotSatisfiable, "range: too many ranges")
	ErrRangeUnsatisfiable = errors.New("range: unsatisfiable range")
)

File errors

Source: error.go:102

var (
	ErrFileHeaderNil = errors.New("file: file header is nil")
	ErrFileOpen      = errors.New("file: failed to open file")
	ErrFileRead      = errors.New("file: failed to read file")
	ErrFileStore     = errors.New("file: failed to store file")
)

DefaultColors Default color codes

Source: color.go:56

var DefaultColors = Colors{
	Black:   "\u001b[90m",
	Red:     "\u001b[91m",
	Green:   "\u001b[92m",
	Yellow:  "\u001b[93m",
	Blue:    "\u001b[94m",
	Magenta: "\u001b[95m",
	Cyan:    "\u001b[96m",
	White:   "\u001b[97m",
	Reset:   "\u001b[0m",
}

HTTP methods enabled by default

Source: app.go:683

var DefaultMethods = []string{
	// contains filtered or unexported fields
}

Default TrustProxyConfig

Source: app.go:617

var DefaultTrustProxyConfig = TrustProxyConfig{}

ErrCertFileAndKeyRequired indicates that only one of CertFile and CertKeyFile was set.

Source: listen.go:49

var ErrCertFileAndKeyRequired = errors.New("tls: CertFile and CertKeyFile must both be set to serve TLS")

Binder errors

Source: error.go:56

var ErrCustomBinderNotFound = errors.New("binder: custom binder not found, please be sure to enter the right name")

Header errors

Source: error.go:112

var (
	// ErrHeaderNotFound is returned by request header accessors that parse a
	// value, to tell an absent header apart from one that failed to parse.
	ErrHeaderNotFound = errors.New("header: field not present in the request")
)

Format errors

Source: error.go:61

var (
	// ErrNoHandlers is returned when c.Format is called with no arguments.
	ErrNoHandlers = errors.New("format: at least one handler is required, but none were set")
)

Fiber redirection errors

Source: error.go:34

var (
	ErrRedirectBackNoFallback = NewError(StatusInternalServerError, "Referer not found, you have to enter fallback URL for redirection.")
)

Source: shared_state.go:17

var ErrSharedStorageNotConfigured = errors.New("fiber: shared storage is not configured")

Source: app.go:1484

var ErrTestGotEmptyResponse = errors.New("test: got empty response")

Functions

func AcquireBind() *Bind

Source: bind.go:103

AcquireBind returns Bind reference from bind pool.

func AcquireRedirect() *Redirect

Source: redirect.go:109

AcquireRedirect return default Redirect reference from the redirect pool

func Convert[T any](value string, converter func(string) (T, error), defaultValue ...T) (T, error)

Source: helpers.go:1222

Convert a string value to a specified type, handling errors and optional default values.

func DefaultErrorHandler(c Ctx, err error) error

Source: app.go:700

DefaultErrorHandler that process return errors from handlers

func DomainParam(c Ctx, key string, defaultValue ...string) string

Source: domain.go:233

DomainParam returns the value of a domain parameter from the context. Domain parameters are set when a route registered via App.Domain or Group.Domain matches the incoming request hostname.

app.Domain("example.com").Get("/", func(c fiber.Ctx) error {
    return c.SendString("Welcome!")
})

app.Domain(":user.example.com").Get("/", func(c fiber.Ctx) error {
    user := fiber.DomainParam(c, "user")
    return c.SendString("Hello, " + user)
})

func GetReqHeader[V GenericType](c Ctx, key string, defaultValue ...V) V

Source: req.go:715

GetReqHeader returns the HTTP request header specified by filed. This function is generic and can handle different headers type values. If the generic type cannot be matched to a supported type, the function returns the default value (if provided) or the zero value of type V.

func GetService[T Service](s *State, key string) (T, bool)

Source: state.go:363

GetService returns a service present in the application's State.

func GetState[T any](s *State, key string) (T, bool)

Source: state.go:103

GetState retrieves a value from the State and casts it to the desired type. It returns the casted value and a boolean indicating if the cast was successful.

func GetStateWithDefault[T any](s *State, key string, defaultVal T) T

Source: state.go:129

GetStateWithDefault retrieves a value from the State, casting it to the desired type. If the key is not present, it returns the provided default value.

func GetTrimmedParam(param string) string

Source: path.go:1692

GetTrimmedParam trims the ':' & '?' from a string

func IsChild() bool

Source: prefork.go:24

IsChild determines if the current process is a child of Prefork

func IsMethodIdempotent(m string) bool

Source: helpers.go:1208

IsMethodIdempotent reports whether the HTTP method is considered idempotent. See https://datatracker.ietf.org/doc/html/rfc9110#section-9.2.2

func IsMethodSafe(m string) bool

Source: helpers.go:1193

IsMethodSafe reports whether the HTTP method is considered safe. See https://datatracker.ietf.org/doc/html/rfc9110#section-9.2.1

func Locals[V any](c Ctx, key any, value ...V) V

Source: req.go:1247

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 MustGetService[T Service](s *State, key string) T

Source: state.go:370

MustGetService returns a service present in the application's State. It panics if the service is not found.

func MustGetState[T any](s *State, key string) T

Source: state.go:117

MustGetState retrieves a value from the State and casts it to the desired type. It panics if the key is not found or if the type assertion fails.

func New(config ...Config) *App

Source: app.go:743

New creates a new Fiber named instance.

app := fiber.New()

You can pass optional configuration options by passing a Config struct:

app := fiber.New(fiber.Config{
    ServerHeader: "Fiber",
})

func NewDefaultCtx(app *App) *DefaultCtx

Source: ctx_interface.go:59

NewDefaultCtx constructs the default context implementation bound to the provided application.

func NewError(code int, message ...string) *Error

Source: app.go:1317

NewError creates a new Error instance with an optional message

func NewErrorf(code int, message ...any) *Error

Source: app.go:1332

NewErrorf creates a new Error instance with an optional message. Additional arguments are formatted using fmt.Sprintf when provided. If the first argument in the message slice is not a string, the function falls back to using fmt.Sprint on the first element to generate the message.

func NewWithCustomCtx(newCtxFunc func(app *App) CustomCtx, config ...Config) *App

Source: app.go:874

NewWithCustomCtx creates a new Fiber instance and applies the provided function to generate a custom context type. It mirrors the behavior of calling New() followed by app.setCtxFunc(fn).

func Params[V GenericType](c Ctx, key string, defaultValue ...V) V

Source: req.go:1456

Params is used to get the route parameters. This function is generic and can handle different route parameters type values. If the generic type cannot be matched to a supported type, the function returns the default value (if provided) or the zero value of type V.

Example:

http://example.com/user/:user -> http://example.com/user/john Params[string](c, "user") -> returns john

http://example.com/id/:id -> http://example.com/user/114 Params[int](c, "id") -> returns 114 as integer.

http://example.com/id/:number -> http://example.com/id/john Params[int](c, "number", 0) -> returns 0 because can't parse 'john' as integer.

func Query[V GenericType](c Ctx, key string, defaultValue ...V) V

Source: req.go:1615

Query Retrieves the value of a query parameter from the request's URI. The function is generic and can handle query parameter values of different types. It takes the following parameters: - c: The context object representing the current request. - key: The name of the query parameter. - defaultValue: (Optional) The default value to return if the query parameter is not found or cannot be parsed. The function performs the following steps:

  1. Type-asserts the context object to *DefaultCtx.
  2. Retrieves the raw query parameter value from the request's URI.
  3. Parses the raw value into the appropriate type based on the generic type parameter V. If parsing fails, the function checks if a default value is provided. If so, it returns the default value.
  4. Returns the parsed value.

If the generic type cannot be matched to a supported type, the function returns the default value (if provided) or the zero value of type V.

Example usage:

GET /?search=john&age=8
name := Query[string](c, "search") // Returns "john"
age := Query[int](c, "age") // Returns 8
unknown := Query[string](c, "unknown", "default") // Returns "default" since the query parameter "unknown" is not found

func ReleaseBind(b *Bind)

Source: bind.go:113

ReleaseBind returns b acquired via Bind to bind pool.

func ReleaseRedirect(r *Redirect)

Source: redirect.go:122

ReleaseRedirect returns c acquired via Redirect to redirect pool.

It is forbidden accessing req and/or its members after returning it to redirect pool.

func RemoveEscapeChar(word string) string

Source: path.go:1708

RemoveEscapeChar removes escape characters

func RemoveEscapeCharBytes(word []byte) []byte

Source: path.go:1722

RemoveEscapeCharBytes removes escape characters

func RoutePatternMatch(path, pattern string, cfg ...Config) bool

Source: path.go:196

RoutePatternMatch reports whether path matches the provided Fiber route pattern.

Patterns use the same syntax as routes registered on an App, including parameters (for example :id), wildcards (*, +), and optional segments. The optional Config argument can be used to control case sensitivity and strict routing behavior. This helper allows checking potential matches without registering a route.

path is a rooted path, as c.Path() returns one. The empty string is read as "/", so RoutePatternMatch("", "/") is true; any other string without a leading slash matches no pattern. Request routing differs in one respect: it roots the request target it is handed before matching, so "OPTIONS *" is routed as "/*", whereas RoutePatternMatch("*", "/*") is false.

With UnescapePath set in the Config, path is taken as already decoded, as c.Path() returns it, so pass the Config of the app it comes from.

func StoreInContext(c Ctx, key, value any)

Source: helpers.go:80

StoreInContext stores key/value in both Fiber locals and request context.

This is useful when values need to be available via both c.Locals() and context.Context lookups throughout middleware and handlers.

func ValueFromContext[T any](ctx, key any) (T, bool)

Source: helpers.go:72

ValueFromContext retrieves a value stored under key from supported context types.

Supported context types:

  • Ctx (including CustomCtx implementations)
  • *fasthttp.RequestCtx
  • context.Context
  • any value exposing UserValue(key any) any or Value(key any) any

Types

type App

Source: app.go:78

App denotes the Fiber application. App is safe for concurrent use, except for route mutation methods that explicitly document otherwise.

type App struct {
	// contains filtered or unexported fields
}

func (app *App) AcquireCtx(fctx *fasthttp.RequestCtx) CustomCtx

Source: ctx_interface.go:72

AcquireCtx retrieves a new Ctx from the pool.

func (app *App) Add(methods []string, path string, handler any, handlers ...any) Router

Source: app.go:1224

Add allows you to specify multiple HTTP methods to register a route. The provided handlers are executed in order, starting with handler and then the variadic handlers.

func (app *App) All(path string, handler any, handlers ...any) Router

Source: app.go:1232

All will register the handler on all HTTP methods

func (app *App) Config() Config

Source: app.go:1363

Config returns the app config as value ( read-only ).

func (app *App) Connect(path string, handler any, handlers ...any) Router

Source: app.go:1194

Connect registers a route for CONNECT methods that establishes a tunnel to the server identified by the target resource.

func (app *App) Delete(path string, handler any, handlers ...any) Router

Source: app.go:1188

Delete registers a route for DELETE methods that deletes the specified resource.

func (app *App) Domain(host string) Router

Source: app.go:1275

Domain creates a new router scoped to the given hostname pattern. Routes registered through the returned Router only match requests whose hostname (from c.Hostname()) matches the pattern. When TrustProxy is enabled and the proxy is trusted, the hostname may be derived from the X-Forwarded-Host header. The pattern can contain parameters prefixed with ":" whose values are accessible via DomainParam.

Domain routing has zero performance impact on routes that don't use it because the hostname check is applied as a handler wrapper, not a core router change.

To prevent header spoofing, configure Config.TrustProxy together with Config.TrustProxyConfig (trusted proxy IPs/ranges) and, where appropriate, Config.ProxyHeader; see: https://docs.gofiber.io/api/fiber#trustproxy

// Static domain
app.Domain("api.example.com").Get("/users", listUsers)

// Domain with parameter
app.Domain(":user.example.com").Get("/", func(c fiber.Ctx) error {
    user := fiber.DomainParam(c, "user")
    return c.SendString("Hello, " + user)
})

func (app *App) ErrorHandler(ctx Ctx, err error) error

Source: app.go:1720

ErrorHandler is the application's method in charge of finding the appropriate handler for the given request. It searches any mounted sub fibers by their prefixes and if it finds a match, it uses that error handler. Otherwise, it uses the configured error handler for the app, which if not set is the DefaultErrorHandler.

func (app *App) Get(path string, handler any, handlers ...any) Router

Source: app.go:1165

Get registers a route for GET methods that requests a representation of the specified resource. Requests using GET should only retrieve data.

func (app *App) GetBytes(b []byte) []byte

Source: app.go:894

GetBytes returns b unchanged when Immutable is off or b is read-only (rodata). Otherwise, it returns a detached copy.

func (app *App) GetRoute(name string) Route

Source: app.go:1058

GetRoute Get route by name

func (app *App) GetRoutes(filterUseOption ...bool) []Route

Source: app.go:1071

GetRoutes Get all routes. When filterUseOption equal to true, it will filter the routes registered by the middleware.

func (app *App) GetString(s string) string

Source: app.go:882

GetString returns s unchanged when Immutable is off or s is read-only (rodata). Otherwise, it returns a detached copy (strings.Clone).

func (app *App) Group(prefix string, handlers ...any) Router

Source: app.go:1240

Group is used for Routes with common prefix to define a new sub-router with optional middleware.

api := app.Group("/api")
api.Get("/users", handler)

func (app *App) Handler() fasthttp.RequestHandler

Source: app.go:1368

Handler returns the server handler.

func (app *App) HandlersCount() uint32

Source: app.go:1387

HandlersCount returns the amount of registered handlers.

func (app *App) Head(path string, handler any, handlers ...any) Router

Source: app.go:1171

Head registers a route for HEAD methods that asks for a response identical to that of a GET request, but without the response body.

func (app *App) Hooks() *Hooks

Source: app.go:1468

Hooks returns the hook struct to register hooks.

func (app *App) Listen(addr string, config ...ListenConfig) error

Source: listen.go:236

Listen serves HTTP requests from the given addr. You should enter custom ListenConfig to customize startup. (TLS, mTLS, prefork...)

app.Listen(":8080")
app.Listen("127.0.0.1:8080")
app.Listen(":8080", ListenConfig{EnablePrefork: true})

func (app *App) Listener(ln net.Listener, config ...ListenConfig) error

Source: listen.go:445

Listener serves HTTP requests from the given listener. You should enter custom ListenConfig to customize startup. (prefork, startup message, graceful shutdown...)

The listener is served exactly as supplied, so every TLS field of the config is ignored — including CertClientFile. Wrap it with tls.NewListener yourself to serve TLS or require a client certificate.

func (app *App) MountPath() string

Source: mount.go:724

MountPath returns the route pattern where the current app instance was mounted as a sub-application.

func (app *App) Name(name string) Router

Source: app.go:1020

Name Assign name to specific route.

func (app *App) Options(path string, handler any, handlers ...any) Router

Source: app.go:1200

Options registers a route for OPTIONS methods that is used to describe the communication options for the target resource.

func (app *App) Patch(path string, handler any, handlers ...any) Router

Source: app.go:1212

Patch registers a route for PATCH methods that is used to apply partial modifications to a resource.

func (app *App) Post(path string, handler any, handlers ...any) Router

Source: app.go:1177

Post registers a route for POST methods that is used to submit an entity to the specified resource, often causing a change in state or side effects on the server.

func (app *App) Put(path string, handler any, handlers ...any) Router

Source: app.go:1183

Put registers a route for PUT methods that replaces all current representations of the target resource with the request payload.

func (app *App) Query(path string, handler any, handlers ...any) Router

Source: app.go:1218

Query registers a route for QUERY methods that performs a safe, idempotent query with a request body.

func (app *App) RebuildTree() *App

Source: router.go:1734

RebuildTree rebuilds the prefix tree from the previously registered routes. This method is useful when you want to register routes dynamically after the app has started. It is not recommended to use this method on production environments because rebuilding the tree is performance-intensive and not thread-safe in runtime. Since building the tree is only done in the startupProcess of the app, this method does not make sure that the routeTree is being safely changed, as it would add a great deal of overhead in the request. Latest benchmark results showed a degradation from 82.79 ns/op to 94.48 ns/op and can be found in: https://github.com/gofiber/fiber/issues/2769#issuecomment-2227385283

func (app *App) RegisterCustomBinder(customBinder CustomBinder)

Source: app.go:947

RegisterCustomBinder Allows to register custom binders to use as Bind().Custom("name"). They should be compatible with CustomBinder interface.

func (app *App) RegisterCustomConstraint(constraint CustomConstraint)

Source: app.go:941

RegisterCustomConstraint allows to register custom constraint.

func (app *App) ReleaseCtx(c CustomCtx)

Source: ctx_interface.go:130

ReleaseCtx releases the ctx back into the pool. If the context was abandoned (e.g., by timeout middleware), this is a no-op. Call ForceRelease only when you can guarantee no goroutines (including the requestHandler and ErrorHandler) still touch the context; the timeout middleware intentionally leaves abandoned contexts unreleased to avoid races.

func (app *App) ReloadViews() error

Source: app.go:953

ReloadViews reloads the configured view engine by invoking its Load method. It returns an error if no view engine is configured or if reloading fails.

func (app *App) RemoveRoute(path string, methods ...string)

Source: router.go:1241

RemoveRoute is used to remove a route from the stack by path. If no methods are specified, it will remove the route for all methods defined in the app. You should call RebuildTree after using this to ensure consistency of the tree.

func (app *App) RemoveRouteByName(name string, methods ...string)

Source: router.go:1259

RemoveRouteByName is used to remove a route from the stack by name. If no methods are specified, it will remove the route for all methods defined in the app. You should call RebuildTree after using this to ensure consistency of the tree.

func (app *App) RemoveRouteFunc(matchFunc func(r *Route) bool, methods ...string)

Source: router.go:1268

RemoveRouteFunc is used to remove a route from the stack by a custom match function. If no methods are specified, it will remove the route for all methods defined in the app. You should call RebuildTree after using this to ensure consistency of the tree. Note: The route.Path is original path, not the normalized path.

func (app *App) Render(out io.Writer, name string, binding any, layouts ...string) error

Source: app.go:991

Render writes a template through the configured view engine.

func (app *App) Route(prefix string, fn func(router Router), name ...string) Router

Source: app.go:1295

Route is used to define routes with a common prefix inside the supplied function. It mirrors the legacy helper and reuses the Group method to create a sub-router.

func (app *App) RouteChain(path string) Register

Source: app.go:1285

RouteChain creates a Registering instance that lets you declare a stack of handlers for the same route. Handlers defined via the returned Register are scoped to the provided path.

func (app *App) Server() *fasthttp.Server

Source: app.go:1463

Server returns the underlying fasthttp server

func (app *App) SetTLSHandler(tlsHandler *TLSHandler)

Source: app.go:1012

SetTLSHandler Can be used to set ClientHelloInfo when using TLS with Listener.

func (app *App) SharedState() *SharedState

Source: app.go:1480

SharedState returns storage-backed shared state. SharedState is prefork-safe when Config.SharedStorage is configured.

func (app *App) Shutdown() error

Source: app.go:1404

Shutdown gracefully shuts down the server without interrupting any active connections. Shutdown works by first closing all open listeners and then waiting indefinitely for all connections to return to idle before shutting down.

Make sure the program doesn't exit and waits instead for Shutdown to return.

Important: app.Listen() must be called in a separate goroutine; otherwise, shutdown hooks will not work as Listen() is a blocking operation. Example:

go app.Listen(":3000")
// ...
app.Shutdown()

Shutdown does not close keepalive connections so its recommended to set ReadTimeout to something else than 0.

func (app *App) ShutdownWithContext(ctx context.Context) error

Source: app.go:1426

ShutdownWithContext shuts down the server and stops waiting once ctx is done; connections still active are not closed.

Make sure the program doesn't exit and waits instead for ShutdownWithTimeout to return.

ShutdownWithContext does not close keepalive connections so its recommended to set ReadTimeout to something else than 0.

func (app *App) ShutdownWithTimeout(timeout time.Duration) error

Source: app.go:1415

ShutdownWithTimeout gracefully shuts down the server without interrupting any active connections. If the timeout is exceeded, it stops waiting and returns context.DeadlineExceeded; connections still active are not closed. ShutdownWithTimeout works by first closing all open listeners and then waiting for all connections to return to idle before shutting down.

Make sure the program doesn't exit and waits instead for ShutdownWithTimeout to return.

ShutdownWithTimeout does not close keepalive connections so its recommended to set ReadTimeout to something else than 0.

func (app *App) Stack() [][]*Route

Source: app.go:1382

Stack returns the raw router stack.

func (app *App) State() *State

Source: app.go:1474

State returns the in-process state struct to store global data between handlers. State is process-local and is not shared across prefork workers.

func (app *App) Test(req *http.Request, config ...TestConfig) (*http.Response, error)

Source: app.go:1503

Test is used for internal debugging by passing a *http.Request. Config is optional and defaults to a 1s error on timeout, 0 timeout will disable it completely.

func (app *App) Trace(path string, handler any, handlers ...any) Router

Source: app.go:1206

Trace registers a route for TRACE methods that performs a message loop-back test along the path to the target resource.

func (app *App) Use(args ...any) Router

Source: app.go:1109

Use registers a middleware route that will match requests with the provided prefix (which is optional and defaults to "/"). Also, you can pass another app instance as a sub-router along a routing path. It's very useful to split up a large API as many independent routers and compose them as a single service using Use. The fiber's error handler and any of the fiber's sub apps are added to the application's error handlers to be invoked on errors that happen within the prefix route.

	app.Use(func(c fiber.Ctx) error {
	     return c.Next()
	})
	app.Use("/api", func(c fiber.Ctx) error {
	     return c.Next()
	})
	app.Use("/api", handler, func(c fiber.Ctx) error {
	     return c.Next()
	})
 	subApp := fiber.New()
	app.Use("/mounted-path", subApp)

This method will match all HTTP verbs: GET, POST, PUT, HEAD etc...

type Bind

Source: bind.go:41

Bind provides helper methods for binding request data to Go values. By default (manual mode), parsing failures are returned as *BindError; use errors.As to extract source and field details. With WithAutoHandling(), parsing failures set HTTP 400 and return *Error instead.

type Bind struct {
	// contains filtered or unexported fields
}

func (b *Bind) All(out any) error

Source: bind.go:516

All binds values from URI params, the request body, the query string, headers, and cookies into the provided struct in precedence order. Returns *BindError on parse failure (manual mode) or *Error with status 400 (auto-handling mode).

func (b *Bind) Body(out any) error

Source: bind.go:399

Body binds the request body into the struct, map[string]string and map[string][]string. Returns *BindError on parse failure (manual mode) or *Error with status 400 (auto-handling mode). It supports decoding the following content types based on the Content-Type header: application/json, application/vnd.msgpack, application/xml, text/xml, application/cbor, application/x-www-form-urlencoded, multipart/form-data Custom binders are checked first, so the first one whose MIMETypes() holds the request's content type runs instead of the built-in decoder for that type. If neither matches the content type, it will return an ErrUnprocessableEntity error.

func (b *Bind) CBOR(out any) error

Source: bind.go:314

CBOR binds the body string into the struct. Returns *BindError on parse failure (manual mode) or *Error with status 400 (auto-handling mode).

func (b *Bind) Custom(name string, dest any) error

Source: bind.go:222

Custom To use custom binders, you have to use this method. You can register them from RegisterCustomBinder method of Fiber instance. They're checked by name, if it's not found, it will return an error. NOTE: WithAutoHandling/WithAutoHandling is still valid for Custom binders.

func (b *Bind) Form(out any) error

Source: bind.go:345

Form binds the form into the struct, map[string]string and map[string][]string. Returns *BindError on parse failure (manual mode) or *Error with status 400 (auto-handling mode). If Content-Type is "application/x-www-form-urlencoded" or "multipart/form-data", it will bind the form values. Multipart file fields are supported using *multipart.FileHeader, []*multipart.FileHeader, or *[]*multipart.FileHeader.

func (b *Bind) Header(out any) error

Source: bind.go:238

Header binds the request header strings into the struct, map[string]string and map[string][]string. Returns *BindError on parse failure (manual mode) or *Error with status 400 (auto-handling mode).

func (b *Bind) JSON(out any) error

Source: bind.go:299

JSON binds the body string into the struct. Returns *BindError on parse failure (manual mode) or *Error with status 400 (auto-handling mode).

func (b *Bind) MsgPack(out any) error

Source: bind.go:378

MsgPack binds the body string into the struct. Returns *BindError on parse failure (manual mode) or *Error with status 400 (auto-handling mode).

func (b *Bind) Query(out any) error

Source: bind.go:284

Query binds the query string into the struct, map[string]string and map[string][]string. Returns *BindError on parse failure (manual mode) or *Error with status 400 (auto-handling mode).

func (b *Bind) RespHeader(out any) error

Source: bind.go:253

RespHeader binds the response header strings into the struct, map[string]string and map[string][]string. Returns *BindError on parse failure (manual mode) or *Error with status 400 (auto-handling mode).

func (b *Bind) SkipValidation(skip bool) *Bind

Source: bind.go:151

SkipValidation enables or disables struct validation. The setting stays on the Bind that c.Bind() returns, so it applies to every later bind of the request until SkipValidation is called again, and ends with the request.

func (b *Bind) URI(out any) error

Source: bind.go:364

URI binds the route parameters into the struct, map[string]string and map[string][]string. Returns *BindError on parse failure (manual mode) or *Error with status 400 (auto-handling mode).

func (b *Bind) WithAutoHandling() *Bind

Source: bind.go:142

WithAutoHandling If you want to handle binder errors automatically, you can use WithAutoHandling. If there's an error, it will return the error and set HTTP status to 400 Bad Request. You must still return on error explicitly

func (b *Bind) WithoutAutoHandling() *Bind

Source: bind.go:133

WithoutAutoHandling If you want to handle binder errors manually, you can use WithoutAutoHandling. It's default behavior of binder.

func (b *Bind) XML(out any) error

Source: bind.go:328

XML binds the body string into the struct. Returns *BindError on parse failure (manual mode) or *Error with status 400 (auto-handling mode).

type BindError

Source: bind.go:60

BindError wraps a binding failure with the source and field that failed. Use errors.As(err, &be) to extract it when you need to branch on source (e.g. 404 for URI vs 400 for body).

type BindError struct {
	Err    error  // underlying error; use errors.As to inspect
	Source string // binding source: uri, query, body, header, cookie, or respHeader (see BindSource* constants)
	Field  string // struct field or tag key that failed (best-effort, may be empty)
}
Fields
  • Err error

    underlying error; use errors.As to inspect

  • Source string

    binding source: uri, query, body, header, cookie, or respHeader (see BindSource* constants)

  • Field string

    struct field or tag key that failed (best-effort, may be empty)

func (e *BindError) Error() string

Source: bind.go:66

func (e *BindError) Unwrap() error

Source: bind.go:73

type Colors

Source: color.go:8

Colors is a struct to define custom colors for Fiber app and middlewares.

type Colors struct {
	// Black color.
	//
	// Optional. Default: "\u001b[90m"
	Black string

	// Red color.
	//
	// Optional. Default: "\u001b[91m"
	Red string

	// Green color.
	//
	// Optional. Default: "\u001b[92m"
	Green string

	// Yellow color.
	//
	// Optional. Default: "\u001b[93m"
	Yellow string

	// Blue color.
	//
	// Optional. Default: "\u001b[94m"
	Blue string

	// Magenta color.
	//
	// Optional. Default: "\u001b[95m"
	Magenta string

	// Cyan color.
	//
	// Optional. Default: "\u001b[96m"
	Cyan string

	// White color.
	//
	// Optional. Default: "\u001b[97m"
	White string

	// Reset color.
	//
	// Optional. Default: "\u001b[0m"
	Reset string
}
Fields
  • Black string

    Black color.

    Optional. Default: "\u001b[90m"

  • Red string

    Red color.

    Optional. Default: "\u001b[91m"

  • Green string

    Green color.

    Optional. Default: "\u001b[92m"

  • Yellow string

    Yellow color.

    Optional. Default: "\u001b[93m"

  • Blue string

    Blue color.

    Optional. Default: "\u001b[94m"

  • Magenta string

    Magenta color.

    Optional. Default: "\u001b[95m"

  • Cyan string

    Cyan color.

    Optional. Default: "\u001b[96m"

  • White string

    White color.

    Optional. Default: "\u001b[97m"

  • Reset string

    Reset color.

    Optional. Default: "\u001b[0m"

type Config

Source: app.go:210

Config is a struct holding the server settings.

type Config struct {
	// Enables the "Server: value" HTTP header.
	//
	// Default: ""
	ServerHeader string `json:"server_header"`

	// When set to true, the router treats "/foo" and "/foo/" as different.
	// By default this is disabled and both "/foo" and "/foo/" will execute the same handler.
	// Middleware registered with Use on "/foo/" runs for "/foo" either way.
	//
	// Default: false
	StrictRouting bool `json:"strict_routing"`

	// When set to true, enables case-sensitive routing.
	// E.g. "/FoO" and "/foo" are treated as different routes.
	// By default this is disabled and both "/FoO" and "/foo" will execute the same handler.
	//
	// Default: false
	CaseSensitive bool `json:"case_sensitive"`

	// When set to true, requests whose path and method match no registered route
	// are answered with 404 (or 405 when the path exists for other methods)
	// before the middleware chain runs, so no work is spent on bots, scanners,
	// and bad URLs.
	//
	// Warning: middleware never runs for skipped requests. This breaks Use-based
	// responders on unregistered paths (catch-all 404 pages, static, proxy,
	// healthcheck, rewrite and redirect middleware); loggers and metrics will not
	// see the skipped requests either, and a rate limiter neither counts nor
	// throttles them. CORS preflight requests are exempt, so cors middleware
	// keeps working. Customize the 404/405 responses via ErrorHandler.
	//
	// Note: with more than 64 entries in RequestMethods the fast path is disabled
	// and requests fall through to the normal router.
	//
	// Default: false
	SkipUnmatchedRoutes bool `json:"skip_unmatched_routes"`

	// When set to true, disables automatic registration of HEAD routes for
	// every GET route.
	//
	// Default: false
	DisableHeadAutoRegister bool `json:"disable_head_auto_register"`

	// When set to true, disables redirect flash messages: Redirect().With and
	// WithInput set no cookie, Messages and OldInput report nothing, and the
	// scan of every request's headers for an incoming flash cookie is skipped.
	// Flash messages travel in the fiber_flash cookie, so only clients that
	// keep cookies across a redirect, browsers above all, ever receive them;
	// deployments whose clients do not lose nothing by turning them off.
	//
	// Default: false
	DisableFlashMessages bool `json:"disable_flash_messages"`

	// When set to true, this relinquishes the 0-allocation promise in certain
	// cases in order to access the handler values (e.g. request bodies) in an
	// immutable fashion so that these values are available even if you return
	// from handler.
	//
	// Default: false
	Immutable bool `json:"immutable"`

	// The router always normalizes the request path before matching (RFC 3986
	// Section 6.2.2): escapes of unreserved characters are decoded, other
	// escapes keep their encoding with uppercase hex digits, and "." and ".."
	// segments are removed. When set to true, every escape is decoded, so the
	// routing, `ctx.Path()` and `ctx.Params(%key%)` see the fully decoded
	// path.
	//
	// Default: false
	UnescapePath bool `json:"unescape_path"`

	// Max body size that the server accepts.
	// Zero or negative values fall back to the default limit.
	//
	// Default: 4 * 1024 * 1024
	BodyLimit int `json:"body_limit"`

	// MaxRanges sets the maximum number of ranges parsed from a Range header.
	// Zero or negative values fall back to the default limit.
	//
	// Default: 16
	MaxRanges int `json:"max_ranges"`

	// Maximum number of concurrent connections.
	//
	// Default: 256 * 1024
	Concurrency int `json:"concurrency"`

	// Views is the interface that wraps the Render function.
	//
	// Default: nil
	Views Views `json:"-"`

	// Views Layout is the global layout for all template render until override on Render function.
	//
	// Default: ""
	ViewsLayout string `json:"views_layout"`

	// PassLocalsToViews Enables passing of the locals set on a fiber.Ctx to the template engine
	//
	// Default: false
	PassLocalsToViews bool `json:"pass_locals_to_views"`

	// PassLocalsToContext controls whether StoreInContext also propagates values to
	// the request context.Context for Fiber-backed contexts.
	//
	// ValueFromContext for Fiber-backed contexts always reads from c.Locals().
	//
	// Default: false
	PassLocalsToContext bool `json:"pass_locals_to_context"`

	// The amount of time allowed to read the full request including body.
	// It is reset after the request handler has returned.
	// The connection's read deadline is reset when the connection opens.
	//
	// Default: unlimited
	ReadTimeout time.Duration `json:"read_timeout"`

	// The maximum duration before timing out writes of the response.
	// It is reset after the request handler has returned.
	//
	// Default: unlimited
	WriteTimeout time.Duration `json:"write_timeout"`

	// The maximum amount of time to wait for the next request when keep-alive is enabled.
	// If IdleTimeout is zero, the value of ReadTimeout is used.
	//
	// Default: unlimited
	IdleTimeout time.Duration `json:"idle_timeout"`

	// Per-connection buffer size for requests' reading.
	// This also limits the maximum header size.
	// Increase this buffer if your clients send multi-KB RequestURIs
	// and/or multi-KB headers (for example, BIG cookies).
	//
	// Default: 8192
	ReadBufferSize int `json:"read_buffer_size"`

	// Per-connection buffer size for responses' writing.
	//
	// Default: 8192
	WriteBufferSize int `json:"write_buffer_size"`

	// CompressedFileSuffixes adds suffix to the original file name and
	// tries saving the resulting compressed file under the new file name.
	//
	// Default: map[string]string{"gzip": ".fiber.gz", "br": ".fiber.br", "zstd": ".fiber.zst"}
	CompressedFileSuffixes map[string]string `json:"compressed_file_suffixes"`

	// ProxyHeader will enable c.IP() to return the value of the given header key
	// By default c.IP() will return the Remote IP from the TCP connection
	// This property can be useful if you are behind a load balancer: X-Forwarded-*
	// NOTE: headers are easily spoofed and the detected IP addresses are unreliable.
	//
	// Default: ""
	ProxyHeader string `json:"proxy_header"`

	// GETOnly rejects every method except GET and HEAD if set to true.
	// This option is useful as anti-DoS protection for servers
	// accepting only GET requests. It refuses methods only: the body of a
	// GET or HEAD is still read up to BodyLimit. A rejected request gets 405
	// with "Allow: GET, HEAD", and no middleware runs for it.
	//
	// Default: false
	GETOnly bool `json:"get_only"`

	// ErrorHandler is executed when an error is returned from fiber.Handler.
	//
	// Default: DefaultErrorHandler
	ErrorHandler ErrorHandler `json:"-"`

	// When set to true, disables keep-alive connections.
	// The server will close incoming connections after sending the first response to client.
	//
	// Default: false
	DisableKeepalive bool `json:"disable_keepalive"`

	// When set to true, causes the default date header to be excluded from the response.
	//
	// Default: false
	DisableDefaultDate bool `json:"disable_default_date"`

	// When set to true, causes the default Content-Type header to be excluded from the response.
	//
	// Default: false
	DisableDefaultContentType bool `json:"disable_default_content_type"`

	// When set to true, disables header normalization.
	// By default all header names are normalized: conteNT-tYPE -> Content-Type.
	//
	// Default: false
	DisableHeaderNormalizing bool `json:"disable_header_normalizing"`

	// This function allows to setup app name for the app
	//
	// Default: nil
	AppName string `json:"app_name"`

	// SharedStorage configures storage-backed shared state that can be used
	// safely across prefork workers and processes.
	//
	// Default: nil
	SharedStorage Storage `json:"-"`

	// SharedStatePrefix customizes the namespace prefix for keys written to
	// SharedStorage. If empty, Fiber derives a prefixed namespace using
	// AppName (when set) or an internal default.
	//
	// Default: ""
	SharedStatePrefix string `json:"shared_state_prefix"`

	// StreamRequestBody enables request body streaming,
	// and calls the handler sooner when given body is
	// larger than the current limit.
	//
	// Only BodyStream reads such a body: Body, FormValue and the binders still
	// apply BodyLimit, and a multipart form is never pre-parsed.
	//
	// Default: false
	StreamRequestBody bool

	// Will not pre parse Multipart Form data if set to true.
	//
	// This option is useful for servers that desire to treat
	// multipart form data as a binary blob, or choose when to parse the data.
	//
	// Server pre parses multipart form data by default, but never with
	// StreamRequestBody.
	//
	// Default: false
	DisablePreParseMultipartForm bool

	// Aggressively reduces memory usage at the cost of higher CPU usage
	// if set to true.
	//
	// Try enabling this option only if the server consumes too much memory
	// serving mostly idle keep-alive connections. This may reduce memory
	// usage by more than 50%.
	//
	// Default: false
	ReduceMemoryUsage bool `json:"reduce_memory_usage"`

	// When set by an external client of Fiber it will use the provided implementation of a
	// JSONMarshal
	//
	// Allowing for flexibility in using another json library for encoding
	// Default: json.Marshal
	JSONEncoder utils.JSONMarshal `json:"-"`

	// When set by an external client of Fiber it will use the provided implementation of a
	// JSONUnmarshal
	//
	// Allowing for flexibility in using another json library for decoding
	// Default: json.Unmarshal
	JSONDecoder utils.JSONUnmarshal `json:"-"`

	// When set by an external client of Fiber it will use the provided implementation of a
	// MsgPackMarshal
	//
	// Allowing for flexibility in using another msgpack library for encoding
	// Default: binder.UnimplementedMsgpackMarshal
	MsgPackEncoder utils.MsgPackMarshal `json:"-"`

	// When set by an external client of Fiber it will use the provided implementation of a
	// MsgPackUnmarshal
	//
	// Allowing for flexibility in using another msgpack library for decoding
	// Default: binder.UnimplementedMsgpackUnmarshal
	MsgPackDecoder utils.MsgPackUnmarshal `json:"-"`

	// When set by an external client of Fiber it will use the provided implementation of a
	// CBORMarshal
	//
	// Allowing for flexibility in using another cbor library for encoding
	// Default: binder.UnimplementedCborMarshal
	CBOREncoder utils.CBORMarshal `json:"-"`

	// When set by an external client of Fiber it will use the provided implementation of a
	// CBORUnmarshal
	//
	// Allowing for flexibility in using another cbor library for decoding
	// Default: binder.UnimplementedCborUnmarshal
	CBORDecoder utils.CBORUnmarshal `json:"-"`

	// XMLEncoder set by an external client of Fiber it will use the provided implementation of a
	// XMLMarshal
	//
	// Allowing for flexibility in using another XML library for encoding
	// Default: xml.Marshal
	XMLEncoder utils.XMLMarshal `json:"-"`

	// XMLDecoder set by an external client of Fiber it will use the provided implementation of a
	// XMLUnmarshal
	//
	// Allowing for flexibility in using another XML library for decoding
	// Default: xml.Unmarshal
	XMLDecoder utils.XMLUnmarshal `json:"-"`

	// If you find yourself behind some sort of proxy, like a load balancer,
	// then certain header information may be sent to you using special X-Forwarded-* headers or the Forwarded header.
	// For example, the Host HTTP header is usually used to return the requested host.
	// But when you’re behind a proxy, the actual host may be stored in an X-Forwarded-Host header.
	//
	// If you are behind a proxy, you should enable TrustProxy to prevent header spoofing.
	// If you enable TrustProxy and do not provide a TrustProxyConfig, Fiber will skip
	// all headers that could be spoofed.
	// If the request IP is in the TrustProxyConfig.Proxies allowlist, then:
	//   1. c.Scheme() get value from X-Forwarded-Proto, X-Forwarded-Protocol, X-Forwarded-Ssl or X-Url-Scheme header
	//   2. c.IP() get value from ProxyHeader header.
	//   3. c.Host() and c.Hostname() get value from X-Forwarded-Host header
	// But if the request IP is NOT in the TrustProxyConfig.Proxies allowlist, then:
	//   1. c.Scheme() WON'T get value from X-Forwarded-Proto, X-Forwarded-Protocol, X-Forwarded-Ssl or X-Url-Scheme header,
	//    will return https when a TLS connection is handled by the app, or http otherwise.
	//   2. c.IP() WON'T get value from ProxyHeader header, will return RemoteIP() from fasthttp context
	//   3. c.Host() and c.Hostname() WON'T get value from X-Forwarded-Host header, fasthttp.Request.URI().Host()
	//    will be used to get the hostname.
	//
	// To automatically trust all loopback, link-local, or private IP addresses,
	// without manually adding them to the TrustProxyConfig.Proxies allowlist,
	// you can set TrustProxyConfig.Loopback, TrustProxyConfig.LinkLocal, or TrustProxyConfig.Private to true.
	//
	// Default: false
	TrustProxy bool `json:"trust_proxy"`

	// Read TrustProxy doc.
	//
	// Default: DefaultTrustProxyConfig
	TrustProxyConfig TrustProxyConfig `json:"trust_proxy_config"`

	// If set to true, c.IP() and c.IPs() will validate IP addresses before returning them.
	// Also, c.IP() will return a single validated IP rather than just the raw header value,
	// which for X-Forwarded-For may be a comma-separated chain: when TrustProxyConfig names
	// proxy IPs or ranges (Proxies, Loopback, Private or LinkLocal) the chain is walked
	// right-to-left and those proxies are skipped; otherwise, including when only UnixSocket
	// is trusted, the first valid IP from the left is returned. Enable it whenever c.IP() is
	// used as a single client identifier and the header can carry a chain; a proxy that
	// overwrites the header with one address, or a single-IP header, does not need it.
	// WARNING: this has a performance cost associated with it.
	//
	// Default: false
	EnableIPValidation bool `json:"enable_ip_validation"`

	// You can define custom color scheme. They'll be used for startup message, route list and some middlewares.
	//
	// Optional. Default: DefaultColors
	ColorScheme Colors `json:"color_scheme"`

	// If you want to validate header/form/query... automatically when to bind, you can define struct validator.
	// Fiber doesn't have default validator, so it'll skip validator step if you don't use any validator.
	//
	// Default: nil
	StructValidator StructValidator

	// RequestMethods provides customizability for HTTP methods. You can add/remove methods as you wish.
	//
	// Optional. Default: DefaultMethods
	RequestMethods []string

	// EnableSplittingOnParsers splits the query/body/header parameters by comma when it's true.
	// For example, you can use it to parse multiple values from a query parameter like this:
	//   /api?foo=bar,baz == foo[]=bar&foo[]=baz
	//
	// Optional. Default: false
	EnableSplittingOnParsers bool `json:"enable_splitting_on_parsers"`

	// Services is a list of services that are used by the app (e.g. databases, caches, etc.)
	//
	// Optional. Default: a zero value slice
	Services []Service

	// ServicesStartupContextProvider is a context provider for the startup of the services.
	//
	// Optional. Default: a provider that returns context.Background()
	ServicesStartupContextProvider func() context.Context

	// ServicesShutdownContextProvider is a context provider for the shutdown of the services.
	//
	// Optional. Default: a provider that returns context.Background()
	ServicesShutdownContextProvider func() context.Context

	// RegexHandler is a function that compiles regex patterns for `regex()`
	// route constraints. Assign regexp.MustCompile or coregex.MustCompile
	// directly to use the standard library or an alternative regex engine.
	//
	// Compiled matchers are reused across requests, so the returned value must
	// be safe for concurrent use. Fiber may invoke RegexHandler more than once
	// per route while parsing raw and normalized route patterns during
	// registration.
	//
	// Example with standard library (default):
	//     import "regexp"
	//     app := fiber.New(fiber.Config{
	//         RegexHandler: regexp.MustCompile,
	//     })
	//
	// Example with coregex:
	//     import "github.com/coregx/coregex"
	//     app := fiber.New(fiber.Config{
	//         RegexHandler: coregex.MustCompile,
	//     })
	//
	// Optional. Default: regexp.MustCompile
	RegexHandler any `json:"-"`
}
Fields
  • ServerHeader string `json:"server_header"`

    Enables the "Server: value" HTTP header.

    Default: ""

  • StrictRouting bool `json:"strict_routing"`

    When set to true, the router treats "/foo" and "/foo/" as different. By default this is disabled and both "/foo" and "/foo/" will execute the same handler. Middleware registered with Use on "/foo/" runs for "/foo" either way.

    Default: false

  • CaseSensitive bool `json:"case_sensitive"`

    When set to true, enables case-sensitive routing. E.g. "/FoO" and "/foo" are treated as different routes. By default this is disabled and both "/FoO" and "/foo" will execute the same handler.

    Default: false

  • SkipUnmatchedRoutes bool `json:"skip_unmatched_routes"`

    When set to true, requests whose path and method match no registered route are answered with 404 (or 405 when the path exists for other methods) before the middleware chain runs, so no work is spent on bots, scanners, and bad URLs.

    Warning: middleware never runs for skipped requests. This breaks Use-based responders on unregistered paths (catch-all 404 pages, static, proxy, healthcheck, rewrite and redirect middleware); loggers and metrics will not see the skipped requests either, and a rate limiter neither counts nor throttles them. CORS preflight requests are exempt, so cors middleware keeps working. Customize the 404/405 responses via ErrorHandler.

    Note: with more than 64 entries in RequestMethods the fast path is disabled and requests fall through to the normal router.

    Default: false

  • DisableHeadAutoRegister bool `json:"disable_head_auto_register"`

    When set to true, disables automatic registration of HEAD routes for every GET route.

    Default: false

  • DisableFlashMessages bool `json:"disable_flash_messages"`

    When set to true, disables redirect flash messages: Redirect().With and WithInput set no cookie, Messages and OldInput report nothing, and the scan of every request's headers for an incoming flash cookie is skipped. Flash messages travel in the fiber_flash cookie, so only clients that keep cookies across a redirect, browsers above all, ever receive them; deployments whose clients do not lose nothing by turning them off.

    Default: false

  • Immutable bool `json:"immutable"`

    When set to true, this relinquishes the 0-allocation promise in certain cases in order to access the handler values (e.g. request bodies) in an immutable fashion so that these values are available even if you return from handler.

    Default: false

  • UnescapePath bool `json:"unescape_path"`

    The router always normalizes the request path before matching (RFC 3986 Section 6.2.2): escapes of unreserved characters are decoded, other escapes keep their encoding with uppercase hex digits, and "." and ".." segments are removed. When set to true, every escape is decoded, so the routing, ctx.Path() and ctx.Params(%key%) see the fully decoded path.

    Default: false

  • BodyLimit int `json:"body_limit"`

    Max body size that the server accepts. Zero or negative values fall back to the default limit.

    Default: 4 * 1024 * 1024

  • MaxRanges int `json:"max_ranges"`

    MaxRanges sets the maximum number of ranges parsed from a Range header. Zero or negative values fall back to the default limit.

    Default: 16

  • Concurrency int `json:"concurrency"`

    Maximum number of concurrent connections.

    Default: 256 * 1024

  • Views Views `json:"-"`

    Views is the interface that wraps the Render function.

    Default: nil

  • ViewsLayout string `json:"views_layout"`

    Views Layout is the global layout for all template render until override on Render function.

    Default: ""

  • PassLocalsToViews bool `json:"pass_locals_to_views"`

    PassLocalsToViews Enables passing of the locals set on a fiber.Ctx to the template engine

    Default: false

  • PassLocalsToContext bool `json:"pass_locals_to_context"`

    PassLocalsToContext controls whether StoreInContext also propagates values to the request context.Context for Fiber-backed contexts.

    ValueFromContext for Fiber-backed contexts always reads from c.Locals().

    Default: false

  • ReadTimeout time.Duration `json:"read_timeout"`

    The amount of time allowed to read the full request including body. It is reset after the request handler has returned. The connection's read deadline is reset when the connection opens.

    Default: unlimited

  • WriteTimeout time.Duration `json:"write_timeout"`

    The maximum duration before timing out writes of the response. It is reset after the request handler has returned.

    Default: unlimited

  • IdleTimeout time.Duration `json:"idle_timeout"`

    The maximum amount of time to wait for the next request when keep-alive is enabled. If IdleTimeout is zero, the value of ReadTimeout is used.

    Default: unlimited

  • ReadBufferSize int `json:"read_buffer_size"`

    Per-connection buffer size for requests' reading. This also limits the maximum header size. Increase this buffer if your clients send multi-KB RequestURIs and/or multi-KB headers (for example, BIG cookies).

    Default: 8192

  • WriteBufferSize int `json:"write_buffer_size"`

    Per-connection buffer size for responses' writing.

    Default: 8192

  • CompressedFileSuffixes map[string]string `json:"compressed_file_suffixes"`

    CompressedFileSuffixes adds suffix to the original file name and tries saving the resulting compressed file under the new file name.

    Default: map[string]string{"gzip": ".fiber.gz", "br": ".fiber.br", "zstd": ".fiber.zst"}

  • ProxyHeader string `json:"proxy_header"`

    ProxyHeader will enable c.IP() to return the value of the given header key By default c.IP() will return the Remote IP from the TCP connection This property can be useful if you are behind a load balancer: X-Forwarded-* NOTE: headers are easily spoofed and the detected IP addresses are unreliable.

    Default: ""

  • GETOnly bool `json:"get_only"`

    GETOnly rejects every method except GET and HEAD if set to true. This option is useful as anti-DoS protection for servers accepting only GET requests. It refuses methods only: the body of a GET or HEAD is still read up to BodyLimit. A rejected request gets 405 with "Allow: GET, HEAD", and no middleware runs for it.

    Default: false

  • ErrorHandler ErrorHandler `json:"-"`

    ErrorHandler is executed when an error is returned from fiber.Handler.

    Default: DefaultErrorHandler

  • DisableKeepalive bool `json:"disable_keepalive"`

    When set to true, disables keep-alive connections. The server will close incoming connections after sending the first response to client.

    Default: false

  • DisableDefaultDate bool `json:"disable_default_date"`

    When set to true, causes the default date header to be excluded from the response.

    Default: false

  • DisableDefaultContentType bool `json:"disable_default_content_type"`

    When set to true, causes the default Content-Type header to be excluded from the response.

    Default: false

  • DisableHeaderNormalizing bool `json:"disable_header_normalizing"`

    When set to true, disables header normalization. By default all header names are normalized: conteNT-tYPE -> Content-Type.

    Default: false

  • AppName string `json:"app_name"`

    This function allows to setup app name for the app

    Default: nil

  • SharedStorage Storage `json:"-"`

    SharedStorage configures storage-backed shared state that can be used safely across prefork workers and processes.

    Default: nil

  • SharedStatePrefix string `json:"shared_state_prefix"`

    SharedStatePrefix customizes the namespace prefix for keys written to SharedStorage. If empty, Fiber derives a prefixed namespace using AppName (when set) or an internal default.

    Default: ""

  • StreamRequestBody bool

    StreamRequestBody enables request body streaming, and calls the handler sooner when given body is larger than the current limit.

    Only BodyStream reads such a body: Body, FormValue and the binders still apply BodyLimit, and a multipart form is never pre-parsed.

    Default: false

  • DisablePreParseMultipartForm bool

    Will not pre parse Multipart Form data if set to true.

    This option is useful for servers that desire to treat multipart form data as a binary blob, or choose when to parse the data.

    Server pre parses multipart form data by default, but never with StreamRequestBody.

    Default: false

  • ReduceMemoryUsage bool `json:"reduce_memory_usage"`

    Aggressively reduces memory usage at the cost of higher CPU usage if set to true.

    Try enabling this option only if the server consumes too much memory serving mostly idle keep-alive connections. This may reduce memory usage by more than 50%.

    Default: false

  • JSONEncoder utils.JSONMarshal `json:"-"`

    When set by an external client of Fiber it will use the provided implementation of a JSONMarshal

    Allowing for flexibility in using another json library for encoding Default: json.Marshal

  • JSONDecoder utils.JSONUnmarshal `json:"-"`

    When set by an external client of Fiber it will use the provided implementation of a JSONUnmarshal

    Allowing for flexibility in using another json library for decoding Default: json.Unmarshal

  • MsgPackEncoder utils.MsgPackMarshal `json:"-"`

    When set by an external client of Fiber it will use the provided implementation of a MsgPackMarshal

    Allowing for flexibility in using another msgpack library for encoding Default: binder.UnimplementedMsgpackMarshal

  • MsgPackDecoder utils.MsgPackUnmarshal `json:"-"`

    When set by an external client of Fiber it will use the provided implementation of a MsgPackUnmarshal

    Allowing for flexibility in using another msgpack library for decoding Default: binder.UnimplementedMsgpackUnmarshal

  • CBOREncoder utils.CBORMarshal `json:"-"`

    When set by an external client of Fiber it will use the provided implementation of a CBORMarshal

    Allowing for flexibility in using another cbor library for encoding Default: binder.UnimplementedCborMarshal

  • CBORDecoder utils.CBORUnmarshal `json:"-"`

    When set by an external client of Fiber it will use the provided implementation of a CBORUnmarshal

    Allowing for flexibility in using another cbor library for decoding Default: binder.UnimplementedCborUnmarshal

  • XMLEncoder utils.XMLMarshal `json:"-"`

    XMLEncoder set by an external client of Fiber it will use the provided implementation of a XMLMarshal

    Allowing for flexibility in using another XML library for encoding Default: xml.Marshal

  • XMLDecoder utils.XMLUnmarshal `json:"-"`

    XMLDecoder set by an external client of Fiber it will use the provided implementation of a XMLUnmarshal

    Allowing for flexibility in using another XML library for decoding Default: xml.Unmarshal

  • TrustProxy bool `json:"trust_proxy"`

    If you find yourself behind some sort of proxy, like a load balancer, then certain header information may be sent to you using special X-Forwarded-* headers or the Forwarded header. For example, the Host HTTP header is usually used to return the requested host. But when you’re behind a proxy, the actual host may be stored in an X-Forwarded-Host header.

    If you are behind a proxy, you should enable TrustProxy to prevent header spoofing. If you enable TrustProxy and do not provide a TrustProxyConfig, Fiber will skip all headers that could be spoofed. If the request IP is in the TrustProxyConfig.Proxies allowlist, then:

    1. c.Scheme() get value from X-Forwarded-Proto, X-Forwarded-Protocol, X-Forwarded-Ssl or X-Url-Scheme header
    2. c.IP() get value from ProxyHeader header.
    3. c.Host() and c.Hostname() get value from X-Forwarded-Host header

    But if the request IP is NOT in the TrustProxyConfig.Proxies allowlist, then:

    1. c.Scheme() WON'T get value from X-Forwarded-Proto, X-Forwarded-Protocol, X-Forwarded-Ssl or X-Url-Scheme header, will return https when a TLS connection is handled by the app, or http otherwise.
    2. c.IP() WON'T get value from ProxyHeader header, will return RemoteIP() from fasthttp context
    3. c.Host() and c.Hostname() WON'T get value from X-Forwarded-Host header, fasthttp.Request.URI().Host() will be used to get the hostname.

    To automatically trust all loopback, link-local, or private IP addresses, without manually adding them to the TrustProxyConfig.Proxies allowlist, you can set TrustProxyConfig.Loopback, TrustProxyConfig.LinkLocal, or TrustProxyConfig.Private to true.

    Default: false

  • TrustProxyConfig TrustProxyConfig `json:"trust_proxy_config"`

    Read TrustProxy doc.

    Default: DefaultTrustProxyConfig

  • EnableIPValidation bool `json:"enable_ip_validation"`

    If set to true, c.IP() and c.IPs() will validate IP addresses before returning them. Also, c.IP() will return a single validated IP rather than just the raw header value, which for X-Forwarded-For may be a comma-separated chain: when TrustProxyConfig names proxy IPs or ranges (Proxies, Loopback, Private or LinkLocal) the chain is walked right-to-left and those proxies are skipped; otherwise, including when only UnixSocket is trusted, the first valid IP from the left is returned. Enable it whenever c.IP() is used as a single client identifier and the header can carry a chain; a proxy that overwrites the header with one address, or a single-IP header, does not need it. WARNING: this has a performance cost associated with it.

    Default: false

  • ColorScheme Colors `json:"color_scheme"`

    You can define custom color scheme. They'll be used for startup message, route list and some middlewares.

    Optional. Default: DefaultColors

  • StructValidator StructValidator

    If you want to validate header/form/query... automatically when to bind, you can define struct validator. Fiber doesn't have default validator, so it'll skip validator step if you don't use any validator.

    Default: nil

  • RequestMethods []string

    RequestMethods provides customizability for HTTP methods. You can add/remove methods as you wish.

    Optional. Default: DefaultMethods

  • EnableSplittingOnParsers bool `json:"enable_splitting_on_parsers"`

    EnableSplittingOnParsers splits the query/body/header parameters by comma when it's true. For example, you can use it to parse multiple values from a query parameter like this:

    /api?foo=bar,baz == foo[]=bar&foo[]=baz

    Optional. Default: false

  • Services []Service

    Services is a list of services that are used by the app (e.g. databases, caches, etc.)

    Optional. Default: a zero value slice

  • ServicesStartupContextProvider func() context.Context

    ServicesStartupContextProvider is a context provider for the startup of the services.

    Optional. Default: a provider that returns context.Background()

  • ServicesShutdownContextProvider func() context.Context

    ServicesShutdownContextProvider is a context provider for the shutdown of the services.

    Optional. Default: a provider that returns context.Background()

  • RegexHandler any `json:"-"`

    RegexHandler is a function that compiles regex patterns for regex() route constraints. Assign regexp.MustCompile or coregex.MustCompile directly to use the standard library or an alternative regex engine.

    Compiled matchers are reused across requests, so the returned value must be safe for concurrent use. Fiber may invoke RegexHandler more than once per route while parsing raw and normalized route patterns during registration.

    Example with standard library (default):

    import "regexp"
    app := fiber.New(fiber.Config{
        RegexHandler: regexp.MustCompile,
    })

    Example with coregex:

    import "github.com/coregx/coregex"
    app := fiber.New(fiber.Config{
        RegexHandler: coregex.MustCompile,
    })

    Optional. Default: regexp.MustCompile

type Constraint

Source: path.go:98

Constraint describes the validation rules that apply to a dynamic route segment when matching incoming requests. See constraint.go for the ConstraintHandler and ConstraintAnalyzer interfaces.

type Constraint struct {

	// RegexCompiler is populated when the constraint is a regex and the
	// default regexp.Compile engine is used.
	//
	// Deprecated: Use the ConstraintHandler interface instead. Retained for
	// backward compatibility with external code that reads this field.
	RegexCompiler *regexp.Regexp

	// Name is the raw constraint name as it appeared in the route pattern
	// (e.g. "minlen", not the canonical "minLen").
	Name string

	// Data holds the raw parsed constraint arguments from the route pattern.
	Data []string

	// ID identifies the built-in constraint kind.
	//
	// Deprecated: Use the ConstraintHandler interface instead. Retained for
	// backward compatibility with external code that reads or compares IDs.
	ID TypeConstraint
	// contains filtered or unexported fields
}
Fields
  • RegexCompiler *regexp.Regexp

    RegexCompiler is populated when the constraint is a regex and the default regexp.Compile engine is used.

    Deprecated: Use the ConstraintHandler interface instead. Retained for backward compatibility with external code that reads this field.

  • Name string

    Name is the raw constraint name as it appeared in the route pattern (e.g. "minlen", not the canonical "minLen").

  • Data []string

    Data holds the raw parsed constraint arguments from the route pattern.

  • ID TypeConstraint

    ID identifies the built-in constraint kind.

    Deprecated: Use the ConstraintHandler interface instead. Retained for backward compatibility with external code that reads or compares IDs.

func (c *Constraint) CheckConstraint(param string) bool

Source: path.go:1735

CheckConstraint validates if a param matches the given constraint. Kept for backward compatibility with external callers.

type ConstraintAnalyzer

Source: constraint.go:86

ConstraintAnalyzer is an optional interface that constraints can implement to preprocess data at route registration time. The returned values are stored in Constraint.Data and passed to Execute() on every request, avoiding repeated parsing.

type ConstraintAnalyzer interface {
	// Analyze preprocesses constraint data at route registration time.
	// Returns pre-typed values that will be stored in Constraint.Data.
	Analyze(args []string) ([]any, error)
}
Methods
  • Analyze func(args []string) ([]any, error)

    Analyze preprocesses constraint data at route registration time. Returns pre-typed values that will be stored in Constraint.Data.

type ConstraintHandler

Source: constraint.go:73

ConstraintHandler is the interface that all constraints must implement. Built-in and custom constraints are treated uniformly through this interface.

type ConstraintHandler interface {
	// Name returns the constraint identifier used in route patterns (e.g. "int", "minLen", "regex").
	Name() string

	// Execute validates a request parameter value against the constraint.
	// param is the request parameter value to check.
	// data contains the pre-typed constraint data produced by Analyze() at registration time.
	Execute(param string, data []any) bool
}
Methods
  • Name func() string

    Name returns the constraint identifier used in route patterns (e.g. "int", "minLen", "regex").

  • Execute func(param string, data []any) bool

    Execute validates a request parameter value against the constraint. param is the request parameter value to check. data contains the pre-typed constraint data produced by Analyze() at registration time.

type ConversionError

Source: error.go:67

ConversionError Conversion error exposes the internal schema.ConversionError for public use.

type ConversionError = schema.ConversionError

type Ctx

Source: ctx_interface_gen.go:19

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

	// 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

	// 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

	// Reset is a method to reset context fields by given request when to use server handlers.
	Reset(fctx *fasthttp.RequestCtx)

	// 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.
	// It does nothing for a context that is not abandoned or whose reclaim ScheduleReclaim
	// armed: a second release would hand one context to two requests.
	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)

	// 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

	// 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

	// 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). Of an absolute-form
	// request target ("GET http://example.com/search") only the path and query follow the host.
	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

	// 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)

	// 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.
	// Behind a trusted proxy it is the first non-empty X-Forwarded-Host element when there is one, trimmed but neither validated nor case-folded.
	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

	// 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

	// 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)

	// 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)

	// 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
	// contains filtered or unexported methods
}
Methods
  • App func() *App

    App returns the *App reference to the instance of the Fiber application

  • BaseURL func() string

    BaseURL returns (protocol + host), such as "https://example.com". It carries no path.

  • RequestCtx func() *fasthttp.RequestCtx

    RequestCtx returns *fasthttp.RequestCtx that carries a deadline a cancellation signal, and other values across API boundaries.

  • Context func() context.Context

    Context returns a context implementation that was set by user earlier or returns a non-nil, empty context, if it was not set earlier.

  • SetContext func(ctx context.Context)

    SetContext sets a context implementation by user.

  • Deadline func() (time.Time, bool)

    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.

  • Done func() <-chan struct{}

    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.

  • Err func() error

    Err returns nil until the Done channel is closed. Done is always nil here, so Err always returns nil. See Deadline.

  • Request func() *fasthttp.Request

    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.

  • Response func() *fasthttp.Response

    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.

  • Body func() []byte

    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.

  • ContentLength func() int

    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.

  • ContentType func() string

    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.

  • Cookies func(key string, defaultValue ...string) 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().

  • Get func(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.

  • GetHeaders func() map[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.

  • GetReqHeaders func() 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.

  • GetRespHeader func(key string, defaultValue ...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.

  • GetRespHeaders func() map[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.

  • ClientHelloInfo func() *tls.ClientHelloInfo

    ClientHelloInfo returns the TLS ClientHelloInfo of the connection this request arrived on, or nil.

  • Next func() error

    Next executes the next method in the stack that matches the current route.

  • RestartRouting func() 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.

  • OriginalURL func() string

    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.

  • RequestID func() string

    RequestID returns the request identifier from the response header or request header.

  • Req func() Req

    Req returns a convenience type whose API is limited to operations on the incoming request.

  • Res func() Res

    Res returns a convenience type whose API is limited to operations on the outgoing response.

  • Redirect func() *Redirect

    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.

  • ViewBind func(vars Map) error

    ViewBind Add vars to default view var map binding to template engine. Variables are read by the Render method and may be overwritten.

  • Route func() *Route

    Route returns the matched Route struct.

  • Endpoint func() *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.

  • FullPath func() string

    FullPath returns the matched route path, including any group prefixes.

  • RouteName func() 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.

  • MountPath func() 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.

  • Matched func() bool

    Matched returns true if the current request path was matched by the router.

  • IsMiddleware func() bool

    IsMiddleware returns true if the current request handler was registered as middleware.

  • IsFinal func() 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.

  • OverrideParam func(name, value string)

    OverrideParam overwrites a route parameter value by name. If the parameter name does not exist in the route, this method does nothing.

  • SaveFile func(fileheader *multipart.FileHeader, path string) error

    SaveFile saves any multipart file to disk.

  • SaveFileToStorage func(fileheader *multipart.FileHeader, path string, storage Storage) error

    SaveFileToStorage saves any multipart file to an external storage system.

  • Error func(status int, message ...string) 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.

  • Status func(status int) Ctx

    Status sets the HTTP status for the response. This method is chainable.

    A status outside 100 to 999 is logged and replaced by 500.

  • ID func() uint64

    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.

  • StartTime func() time.Time

    StartTime returns the time the server began handling this request. It is the reference point Elapsed measures from.

  • Elapsed func() time.Duration

    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.

  • LocalAddr func() net.Addr

    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.

  • RemoteAddr func() 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.

  • Hijack func(handler fasthttp.HijackHandler)

    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.

  • Hijacked func() bool

    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.

  • String func() string

    String returns unique string representation of the ctx.

    The returned value may be useful for logging.

  • Value func(key any) any

    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.

  • Reset func(fctx *fasthttp.RequestCtx)

    Reset is a method to reset context fields by given request when to use server handlers.

  • Abandon func()

    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.

  • IsAbandoned func() bool

    IsAbandoned returns true if Abandon() was called on this context.

  • ForceRelease func()

    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. It does nothing for a context that is not abandoned or whose reclaim ScheduleReclaim armed: a second release would hand one context to two requests.

  • ScheduleReclaim func(handlerDone <-chan struct{}, cancel context.CancelFunc)

    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).

  • Bind func() *Bind

    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

  • Accepts func(offers ...string) string

    Accepts checks if the specified extensions or content types are acceptable.

  • AcceptsCharsets func(offers ...string) string

    AcceptsCharsets checks if the specified charset is acceptable.

  • AcceptsEncodings func(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.

  • AcceptsLanguages func(offers ...string) string

    AcceptsLanguages checks if the specified language is acceptable using RFC 4647 Basic Filtering.

  • AcceptsLanguagesExtended func(offers ...string) string

    AcceptsLanguagesExtended checks if the specified language is acceptable using RFC 4647 Extended Filtering.

  • BodyRaw func() []byte

    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.

  • BodyStream func() io.Reader

    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.

  • FullURL func() string

    FullURL returns the full request URL (protocol + host + original URL). Of an absolute-form request target ("GET http://example.com/search") only the path and query follow the host.

  • UserAgent func() string

    UserAgent returns the User-Agent request header.

  • Referer func() string

    Referer returns the Referer request header.

  • Origin func() 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.

  • AcceptLanguage func() string

    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.

  • AcceptEncoding func() 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.

  • HasHeader func(key string) bool

    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.

  • HasHeaderValue func(key, value 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.

  • MediaType func() string

    MediaType returns the MIME type from the Content-Type header without parameters.

  • Charset func() string

    Charset returns the charset parameter from the Content-Type header.

  • IsJSON func() bool

    IsJSON reports whether the Content-Type header is JSON.

  • IsForm func() bool

    IsForm reports whether the Content-Type header is form-encoded.

  • IsMultipart func() bool

    IsMultipart reports whether the Content-Type header is multipart form data.

  • AcceptsJSON func() bool

    AcceptsJSON reports whether the Accept header allows JSON.

  • AcceptsHTML func() bool

    AcceptsHTML reports whether the Accept header allows HTML.

  • AcceptsXML func() bool

    AcceptsXML reports whether the Accept header allows XML.

  • AcceptsEventStream func() bool

    AcceptsEventStream reports whether the Accept header allows text/event-stream.

  • CookieNames func() []string

    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.

  • AllCookies func() map[string]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.

  • FormFile func(key string) (*multipart.FileHeader, error)

    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.

  • FormValue func(key string, defaultValue ...string) string

    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.

  • Fresh func() bool

    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

  • IfNoneMatch func() []string

    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.

  • IfModifiedSince func() (time.Time, error)

    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.

  • GetAll func(key string) []string

    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.

  • Authorization func() (scheme, credentials 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.

  • Bearer func() string

    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.

  • Host func() 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. Behind a trusted proxy it is the first non-empty X-Forwarded-Host element when there is one, trimmed but neither validated nor case-folded.

  • Hostname func() 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.

  • Port func() string

    Port returns the remote port of the request.

  • IP func() 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.

  • IPs func() []string

    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.

  • Is func(extension string) bool

    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

  • HasBody func() bool

    HasBody returns true if the request declares a body via Content-Length, Transfer-Encoding, or already buffered payload data.

  • IsWebSocket func() bool

    IsWebSocket returns true if the request includes a WebSocket upgrade handshake.

  • IsPreflight func() bool

    IsPreflight returns true if the request is a CORS preflight.

  • Secure func() bool

    Secure returns whether a secure connection was established.

  • XHR func() 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).

  • Locals func(key any, value ...any) any

    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.

  • SetLocal func(key, value 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.

  • Method func(override ...string) string

    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.

  • IsSafe func() bool

    IsSafe reports whether the request method is safe, meaning it is not expected to change server state (RFC 9110 Section 9.2.1).

  • IsIdempotent func() 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.

  • MultipartForm func() (*multipart.Form, error)

    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.

  • URI func() *fasthttp.URI

    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.

  • Path func(override ...string) string

    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.

  • Params func(key string, defaultValue ...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.

  • Scheme func() 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.

  • Protocol func() string

    Protocol returns the HTTP protocol of request: HTTP/1.1 and HTTP/2.

  • Query func(key string, defaultValue ...string) 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.

  • Queries func() map[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"

  • Range func(size int64) (Range, error)

    Range returns a struct containing the type and a slice of ranges.

  • Subdomains func(offset ...int) []string

    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.

  • Stale func() bool

    Stale returns the inverse of Fresh, indicating if the client's cached response is considered stale.

  • IsProxyTrusted func() 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.

  • IsFromLocal func() bool

    IsFromLocal will return true if request came from a loopback IP.

  • IsFromUnixSocket func() bool

    IsFromUnixSocket returns true if the request arrived over a Unix domain socket.

  • Append func(field string, values ...string)

    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.

  • Add func(key, val 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.

  • Attachment func(filename ...string)

    Attachment sets the HTTP response Content-Disposition header field to attachment.

  • ClearCookie func(key ...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.

  • Cookie func(cookie *Cookie)

    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.

  • GetCookie func(name string) (*Cookie, bool)

    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.

  • GetCookies func() []*Cookie

    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.

  • Download func(file string, filename ...string) error

    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.

  • Format func(handlers ...ResFmt) 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.

  • AutoFormat func(body any) 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.

  • Del func(key string)

    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.

  • JSON func(data any, ctype ...string) error

    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.

  • MsgPack func(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.

  • CBOR func(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.

  • JSONP func(data any, callback ...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.

  • XML func(data any) error

    XML converts any interface or string to XML. This method also sets the content header to application/xml; charset=utf-8.

  • Links func(link ...string)

    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.

  • Location func(path string)

    Location sets the response Location HTTP header to the specified path parameter.

  • GetRouteURL func(routeName string, params Map) (string, error)

    GetRouteURL generates URLs to named routes, with parameters. URLs are relative, for example: "/user/1831"

  • Render func(name string, bind any, layouts ...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.

  • ResetBody func()

    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.

  • Written func() bool

    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.

  • Send func(body []byte) error

    Send sets the HTTP response body without copying it. From this point onward the body argument must not be changed.

  • SendEarlyHints func(hints []string) 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

  • SendFile func(file string, config ...SendFile) 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.

  • NoContent func() 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.

  • SendStatus func(status int) error

    SendStatus sets the HTTP status code and if the response body is empty, it sets the correct status message in the body.

  • SendString func(body string) error

    SendString sets the HTTP response body for string types. This means no type assertion, recommended for faster performance

  • SendStream func(stream io.Reader, size ...int) error

    SendStream sets response body stream and optional body size.

  • SendStreamWriter func(streamWriter func(*bufio.Writer)) error

    SendStreamWriter sets response body stream writer

  • Set func(key, val string)

    Set sets the response's HTTP header field to the specified key, value.

  • StatusCode func() int

    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.

  • Type func(extension string, charset ...string) Ctx

    Type sets the Content-Type HTTP header to the MIME type specified by the file extension.

  • Vary func(fields ...string)

    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 "*".

  • Write func(p []byte) (int, error)

    Write appends p into response body.

  • Writef func(f string, a ...any) (int, error)

    Writef appends f & a into response body writer.

  • WriteString func(s string) (int, error)

    WriteString appends s to response body.

  • Drop func() 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.

  • End func() 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.

type CustomBinder

Source: bind.go:19

CustomBinder An interface to register custom binders.

type CustomBinder interface {
	Name() string
	MIMETypes() []string
	Parse(c Ctx, out any) error
}
Methods
  • Name func() string
  • MIMETypes func() []string
  • Parse func(c Ctx, out any) error

type CustomConstraint

Source: constraint.go:95

CustomConstraint is the legacy interface for user-defined constraints. It is kept for backward compatibility. CustomConstraint implementations are automatically wrapped to satisfy the ConstraintHandler interface.

type CustomConstraint interface {
	Name() string
	Execute(param string, args ...string) bool
}
Methods
  • Name func() string
  • Execute func(param string, args ...string) bool

type CustomCtx

Source: ctx_interface.go:13

CustomCtx extends Ctx with the additional methods required by Fiber's internals and middleware helpers.

type CustomCtx interface {
	Ctx

	// Reset is a method to reset context fields by given request when to use server handlers.
	Reset(fctx *fasthttp.RequestCtx)

	// Abandon marks the context as abandoned. An abandoned context will not be
	// returned to the pool when ReleaseCtx is called. This is used by the timeout
	// middleware to return immediately while the handler goroutine continues.
	// The cleanup goroutine must call ForceRelease when the handler finishes,
	// unless ScheduleReclaim armed the reclaim, which then releases it.
	Abandon()

	// IsAbandoned returns true if the context has been abandoned.
	IsAbandoned() bool

	// ForceRelease releases an abandoned context back to the pool.
	// Must only be called after the handler goroutine has completely finished.
	// It does nothing once ScheduleReclaim armed the reclaim, or for a context that is not abandoned.
	ForceRelease()
	// contains filtered or unexported methods
}
Methods
  • Ctx
  • Reset func(fctx *fasthttp.RequestCtx)

    Reset is a method to reset context fields by given request when to use server handlers.

  • Abandon func()

    Abandon marks the context as abandoned. An abandoned context will not be returned to the pool when ReleaseCtx is called. This is used by the timeout middleware to return immediately while the handler goroutine continues. The cleanup goroutine must call ForceRelease when the handler finishes, unless ScheduleReclaim armed the reclaim, which then releases it.

  • IsAbandoned func() bool

    IsAbandoned returns true if the context has been abandoned.

  • ForceRelease func()

    ForceRelease releases an abandoned context back to the pool. Must only be called after the handler goroutine has completely finished. It does nothing once ScheduleReclaim armed the reclaim, or for a context that is not abandoned.

type DefaultCtx

Source: ctx.go:58

DefaultCtx is the default implementation of the Ctx interface generation tool go install github.com/vburenin/ifacemaker@f30b6f9bdbed4b5c4804ec9ba4a04a999525c202 https://github.com/vburenin/ifacemaker/blob/f30b6f9bdbed4b5c4804ec9ba4a04a999525c202/ifacemaker.go#L14-L31

type DefaultCtx struct {
	DefaultReq // Default request api
	DefaultRes // Default response api
	// contains filtered or unexported fields
}
Fields
  • DefaultReq

    Default request api

  • DefaultRes

    Default response api

func (c *DefaultCtx) Abandon()

Source: ctx.go:1010

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.

func (c *DefaultCtx) App() *App

Source: ctx.go:201

App returns the *App reference to the instance of the Fiber application

func (c *DefaultCtx) BaseURL() string

Source: ctx.go:206

BaseURL returns (protocol + host), such as "https://example.com". It carries no path.

func (c *DefaultCtx) Bind() *Bind

Source: ctx.go:1147

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

func (c *DefaultCtx) Body() []byte

Source: ctx.go:300

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.

func (c *DefaultCtx) ClientHelloInfo() *tls.ClientHelloInfo

Source: ctx.go:363

ClientHelloInfo returns the TLS ClientHelloInfo of the connection this request arrived on, or nil.

func (c *DefaultCtx) ContentLength() int

Source: ctx.go:307

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.

func (c *DefaultCtx) ContentType() string

Source: ctx.go:314

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.

func (c *DefaultCtx) Context() context.Context

Source: ctx.go:230

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) Cookies(key string, defaultValue ...string) string

Source: ctx.go:321

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().

func (*DefaultCtx) Deadline() (time.Time, bool)

Source: ctx.go:258

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.

func (*DefaultCtx) Done() <-chan struct{}

Source: ctx.go:265

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.

func (c *DefaultCtx) Elapsed() time.Duration

Source: ctx.go:748

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.

func (c *DefaultCtx) Endpoint() *Route

Source: ctx.go:520

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.

func (*DefaultCtx) Err() error

Source: ctx.go:271

Err returns nil until the Done channel is closed. Done is always nil here, so Err always returns nil. See Deadline.

func (*DefaultCtx) Error(status int, message ...string) error

Source: ctx.go:720

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.

func (c *DefaultCtx) ForceRelease()

Source: ctx.go:1025

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. It does nothing for a context that is not abandoned or whose reclaim ScheduleReclaim armed: a second release would hand one context to two requests.

func (c *DefaultCtx) FullPath() string

Source: ctx.go:576

FullPath returns the matched route path, including any group prefixes.

func (c *DefaultCtx) Get(key string, defaultValue ...string) string

Source: ctx.go:329

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) GetHeaders() map[string][]string

Source: ctx.go:336

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.

func (c *DefaultCtx) GetReqHeaders() map[string][]string

Source: ctx.go:343

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) GetRespHeader(key string, defaultValue ...string) string

Source: ctx.go:351

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) GetRespHeaders() map[string][]string

Source: ctx.go:358

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) Hijack(handler fasthttp.HijackHandler)

Source: ctx.go:769

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.

func (c *DefaultCtx) Hijacked() bool

Source: ctx.go:776

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.

func (c *DefaultCtx) ID() uint64

Source: ctx.go:736

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.

func (c *DefaultCtx) IsAbandoned() bool

Source: ctx.go:1015

IsAbandoned returns true if Abandon() was called on this context.

func (c *DefaultCtx) IsFinal() bool

Source: ctx.go:630

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.

func (c *DefaultCtx) IsMiddleware() bool

Source: ctx.go:616

IsMiddleware returns true if the current request handler was registered as middleware.

func (c *DefaultCtx) LocalAddr() net.Addr

Source: ctx.go:755

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.

func (c *DefaultCtx) Matched() bool

Source: ctx.go:611

Matched returns true if the current request path was matched by the router.

func (c *DefaultCtx) MountPath() string

Source: ctx.go:595

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.

func (c *DefaultCtx) Next() error

Source: ctx.go:372

Next executes the next method in the stack that matches the current route.

func (c *DefaultCtx) OriginalURL() string

Source: ctx.go:434

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 (c *DefaultCtx) OverrideParam(name, value string)

Source: ctx.go:636

OverrideParam overwrites a route parameter value by name. If the parameter name does not exist in the route, this method does nothing.

func (c *DefaultCtx) Redirect() *Redirect

Source: ctx.go:462

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 (c *DefaultCtx) RemoteAddr() net.Addr

Source: ctx.go:762

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.

func (c *DefaultCtx) Req() Req

Source: ctx.go:448

Req returns a convenience type whose API is limited to operations on the incoming request.

func (c *DefaultCtx) Request() *fasthttp.Request

Source: ctx.go:279

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.

func (c *DefaultCtx) RequestCtx() *fasthttp.RequestCtx

Source: ctx.go:224

RequestCtx returns *fasthttp.RequestCtx that carries a deadline a cancellation signal, and other values across API boundaries.

func (c *DefaultCtx) RequestID() string

Source: ctx.go:439

RequestID returns the request identifier from the response header or request header.

func (c *DefaultCtx) Res() Res

Source: ctx.go:454

Res returns a convenience type whose API is limited to operations on the outgoing response.

func (c *DefaultCtx) Reset(fctx *fasthttp.RequestCtx)

Source: ctx.go:917

Reset is a method to reset context fields by given request when to use server handlers.

func (c *DefaultCtx) Response() *fasthttp.Response

Source: ctx.go:290

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.

func (c *DefaultCtx) RestartRouting() error

Source: ctx.go:394

RestartRouting instead of going to the next handler. This may be useful after changing the request path. Note that handlers might be executed again.

func (c *DefaultCtx) Route() *Route

Source: ctx.go:483

Route returns the matched Route struct.

func (c *DefaultCtx) RouteName() string

Source: ctx.go:583

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.

func (*DefaultCtx) SaveFile(fileheader *multipart.FileHeader, path string) error

Source: ctx.go:668

SaveFile saves any multipart file to disk.

func (c *DefaultCtx) SaveFileToStorage(fileheader *multipart.FileHeader, path string, storage Storage) error

Source: ctx.go:676

SaveFileToStorage saves any multipart file to an external storage system.

func (c *DefaultCtx) ScheduleReclaim(handlerDone <-chan struct{}, cancel context.CancelFunc)

Source: ctx.go:1062

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).

func (c *DefaultCtx) SetContext(ctx context.Context)

Source: ctx.go:243

SetContext sets a context implementation by user.

func (c *DefaultCtx) StartTime() time.Time

Source: ctx.go:742

StartTime returns the time the server began handling this request. It is the reference point Elapsed measures from.

func (c *DefaultCtx) Status(status int) Ctx

Source: ctx.go:728

Status sets the HTTP status for the response. This method is chainable.

A status outside 100 to 999 is logged and replaced by 500.

func (c *DefaultCtx) String() string

Source: ctx.go:783

String returns unique string representation of the ctx.

The returned value may be useful for logging.

func (c *DefaultCtx) Value(key any) any

Source: ctx.go:823

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.

func (c *DefaultCtx) ViewBind(vars Map) error

Source: ctx.go:473

ViewBind Add vars to default view var map binding to template engine. Variables are read by the Render method and may be overwritten.

type DefaultReq

Source: req.go:65

DefaultReq is the default implementation of Req used by DefaultCtx.

type DefaultReq struct {
	// contains filtered or unexported fields
}

func (r *DefaultReq) AcceptEncoding() string

Source: req.go:342

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.

func (r *DefaultReq) AcceptLanguage() string

Source: req.go:334

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.

func (r *DefaultReq) Accepts(offers ...string) string

Source: req.go:70

Accepts checks if the specified extensions or content types are acceptable.

func (r *DefaultReq) AcceptsCharsets(offers ...string) string

Source: req.go:76

AcceptsCharsets checks if the specified charset is acceptable.

func (r *DefaultReq) AcceptsEncodings(offers ...string) string

Source: req.go:86

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.

func (r *DefaultReq) AcceptsEventStream() bool

Source: req.go:449

AcceptsEventStream reports whether the Accept header allows text/event-stream.

func (r *DefaultReq) AcceptsHTML() bool

Source: req.go:439

AcceptsHTML reports whether the Accept header allows HTML.

func (r *DefaultReq) AcceptsJSON() bool

Source: req.go:434

AcceptsJSON reports whether the Accept header allows JSON.

func (r *DefaultReq) AcceptsLanguages(offers ...string) string

Source: req.go:100

AcceptsLanguages checks if the specified language is acceptable using RFC 4647 Basic Filtering.

func (r *DefaultReq) AcceptsLanguagesExtended(offers ...string) string

Source: req.go:107

AcceptsLanguagesExtended checks if the specified language is acceptable using RFC 4647 Extended Filtering.

func (r *DefaultReq) AcceptsXML() bool

Source: req.go:444

AcceptsXML reports whether the Accept header allows XML.

func (r *DefaultReq) AllCookies() map[string]string

Source: req.go:476

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.

func (r *DefaultReq) App() *App

Source: req.go:113

App returns the *App reference to the instance of the Fiber application

func (r *DefaultReq) Authorization() (scheme, credentials string)

Source: req.go:743

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.

func (r *DefaultReq) BaseURL() string

Source: req.go:118

BaseURL returns (protocol + host), such as "https://example.com". It carries no path.

func (r *DefaultReq) Bearer() string

Source: req.go:767

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.

func (r *DefaultReq) Body() []byte

Source: req.go:189

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 (r *DefaultReq) BodyRaw() []byte

Source: req.go:125

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 (r *DefaultReq) BodyStream() io.Reader

Source: req.go:248

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.

func (r *DefaultReq) Charset() string

Source: req.go:390

Charset returns the charset parameter from the Content-Type header.

func (r *DefaultReq) ContentLength() int

Source: req.go:255

ContentLength returns the value of the Content-Length request header. A negative result is not a length: -1 is chunked and -2 is identity, which is what a bodyless GET reports. Use HasBody to test for a body at all.

func (r *DefaultReq) ContentType() string

Source: req.go:380

ContentType returns the Content-Type request header, parameters included; MediaType strips them and Charset returns just the charset. On Ctx the request wins over Res. Only valid within the handler unless Immutable is set.

func (r *DefaultReq) CookieNames() []string

Source: req.go:465

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.

func (r *DefaultReq) Cookies(key string, defaultValue ...string) string

Source: req.go:458

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 (r *DefaultReq) Endpoint() *Route

Source: req.go:1774

Endpoint returns the route that will handle this request. See Ctx.Endpoint.

func (r *DefaultReq) FormFile(key string) (*multipart.FileHeader, error)

Source: req.go:501

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.

func (r *DefaultReq) FormValue(key string, defaultValue ...string) string

Source: req.go:521

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.

func (r *DefaultReq) Fresh() bool

Source: req.go:576

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

func (r *DefaultReq) FullURL() string

Source: req.go:267

FullURL returns the full request URL (protocol + host + original URL). Of an absolute-form request target ("GET http://example.com/search") only the path and query follow the host.

func (r *DefaultReq) Get(key string, defaultValue ...string) string

Source: req.go:707

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 (r *DefaultReq) GetAll(key string) []string

Source: req.go:726

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.

func (r *DefaultReq) GetHeaders() map[string][]string

Source: req.go:781

GetHeaders (a.k.a 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 (r *DefaultReq) HasBody() bool

Source: req.go:1070

HasBody returns true if the request declares a body via Content-Length, Transfer-Encoding, or already buffered payload data.

func (r *DefaultReq) HasHeader(key string) bool

Source: req.go:349

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.

func (r *DefaultReq) HasHeaderValue(key, value string) bool

Source: req.go:361

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.

func (r *DefaultReq) Host() string

Source: req.go:819

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. Behind a trusted proxy it is the first non-empty X-Forwarded-Host element when there is one, trimmed but neither validated nor case-folded.

func (r *DefaultReq) Hostname() string

Source: req.go:834

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.

func (r *DefaultReq) IP() string

Source: req.go:875

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.

func (r *DefaultReq) IPs() []string

Source: req.go:1053

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 (r *DefaultReq) IfModifiedSince() (time.Time, error)

Source: req.go:695

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.

func (r *DefaultReq) IfNoneMatch() []string

Source: req.go:684

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.

func (r *DefaultReq) Is(extension string) bool

Source: req.go:1059

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 (r *DefaultReq) IsForm() bool

Source: req.go:424

IsForm reports whether the Content-Type header is form-encoded.

func (r *DefaultReq) IsFromLocal() bool

Source: req.go:1898

IsFromLocal will return true if request came from a loopback IP.

func (r *DefaultReq) IsFromUnixSocket() bool

Source: req.go:1906

IsFromUnixSocket returns true if the request arrived over a Unix domain socket.

func (r *DefaultReq) IsIdempotent() bool

Source: req.go:1340

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.

func (r *DefaultReq) IsJSON() bool

Source: req.go:419

IsJSON reports whether the Content-Type header is JSON.

func (r *DefaultReq) IsMultipart() bool

Source: req.go:429

IsMultipart reports whether the Content-Type header is multipart form data.

func (r *DefaultReq) IsPreflight() bool

Source: req.go:1165

IsPreflight returns true if the request is a CORS preflight.

func (r *DefaultReq) IsProxyTrusted() bool

Source: req.go:1850

IsProxyTrusted checks trustworthiness of remote ip. If Config.TrustProxy false, it returns false. IsProxyTrusted can check remote ip by proxy ranges and ip map.

func (r *DefaultReq) IsSafe() bool

Source: req.go:1333

IsSafe reports whether the request method is safe, meaning it is not expected to change server state (RFC 9110 Section 9.2.1).

func (r *DefaultReq) IsWebSocket() bool

Source: req.go:1131

IsWebSocket returns true if the request includes a WebSocket upgrade handshake.

func (r *DefaultReq) Locals(key any, value ...any) any

Source: req.go:1198

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.

func (r *DefaultReq) MediaType() string

Source: req.go:385

MediaType returns the MIME type from the Content-Type header without parameters.

func (r *DefaultReq) Method(override ...string) string

Source: req.go:1266

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.

func (r *DefaultReq) MultipartForm() (*multipart.Form, error)

Source: req.go:1351

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.

func (r *DefaultReq) Origin() string

Source: req.go:318

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.

func (r *DefaultReq) OriginalURL() string

Source: req.go:1368

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 *DefaultReq) Params(key string, defaultValue ...string) string

Source: req.go:1417

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.

func (r *DefaultReq) Path(override ...string) string

Source: req.go:1383

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.

func (r *DefaultReq) Port() string

Source: req.go:841

Port returns the remote port of the request.

func (r *DefaultReq) Protocol() string

Source: req.go:1549

Protocol returns the HTTP protocol of request: HTTP/1.1 and HTTP/2.

func (r *DefaultReq) Queries() map[string]string

Source: req.go:1583

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"

func (r *DefaultReq) Query(key string, defaultValue ...string) string

Source: req.go:1558

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.

func (r *DefaultReq) Range(size int64) (Range, error)

Source: req.go:1625

Range returns a struct containing the type and a slice of ranges.

func (r *DefaultReq) Referer() string

Source: req.go:306

Referer returns the Referer request header.

func (r *DefaultReq) Request() *fasthttp.Request

Source: req.go:494

Request return the *fasthttp.Request object This allows you to use all fasthttp request methods https://godoc.org/github.com/valyala/fasthttp#Request

func (r *DefaultReq) RequestCtx() *fasthttp.RequestCtx

Source: req.go:261

RequestCtx returns *fasthttp.RequestCtx that carries a deadline a cancellation signal, and other values across API boundaries.

func (r *DefaultReq) Route() *Route

Source: req.go:1779

Route returns the matched Route struct.

func (r *DefaultReq) Scheme() string

Source: req.go:1466

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.

func (r *DefaultReq) Secure() bool

Source: req.go:1176

Secure returns whether a secure connection was established.

func (r *DefaultReq) SetLocal(key, value any)

Source: req.go:1225

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.

func (r *DefaultReq) Stale() bool

Source: req.go:1843

Stale returns the inverse of Fresh, indicating if the client's cached response is considered stale.

func (r *DefaultReq) Subdomains(offset ...int) []string

Source: req.go:1786

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.

func (r *DefaultReq) URI() *fasthttp.URI

Source: req.go:1375

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.

func (r *DefaultReq) UserAgent() string

Source: req.go:296

UserAgent returns the User-Agent request header.

func (r *DefaultReq) XHR() bool

Source: req.go:1185

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).

type DefaultRes

Source: res.go:182

DefaultRes is the default implementation of Res used by DefaultCtx.

type DefaultRes struct {
	// contains filtered or unexported fields
}

func (r *DefaultRes) Add(key, val string)

Source: res.go:310

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.

func (r *DefaultRes) App() *App

Source: res.go:187

App returns the *App reference to the instance of the Fiber application

func (r *DefaultRes) Append(field string, values ...string)

Source: res.go:197

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) Attachment(filename ...string)

Source: res.go:315

Attachment sets the HTTP response Content-Disposition header field to attachment.

func (r *DefaultRes) AutoFormat(body any) error

Source: res.go:667

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) Body() []byte

Source: res.go:1229

Body returns the response body buffered so far, or nil for a streamed one, which draining would de-stream; Written tells those apart. The buffer is live, so writing to it writes to the response, and the next write voids it.

func (r *DefaultRes) CBOR(data any, ctype ...string) error

Source: res.go:809

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) ClearCookie(key ...string)

Source: res.go:329

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) ContentLength() int

Source: res.go:716

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) ContentType() string

Source: res.go:723

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) Del(key string)

Source: res.go:730

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) Download(file string, filename ...string) error

Source: res.go:564

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) Drop() error

Source: res.go:1719

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.

func (r *DefaultRes) End() error

Source: res.go:1730

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.

func (r *DefaultRes) Format(handlers ...ResFmt) error

Source: res.go:594

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) Get(key string, defaultValue ...string) string

Source: res.go:743

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) GetCookie(name string) (*Cookie, bool)

Source: res.go:463

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) GetCookies() []*Cookie

Source: res.go:491

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) GetHeaders() map[string][]string

Source: res.go:750

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) GetRouteURL(routeName string, params Map) (string, error)

Source: res.go:1087

GetRouteURL generates URLs to named routes, with parameters. URLs are relative, for example: "/user/1831"

func (r *DefaultRes) JSON(data any, ctype ...string) error

Source: res.go:769

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) JSONP(data any, callback ...string) error

Source: res.go:834

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) Location(path string)

Source: res.go:1051

Location sets the response Location HTTP header to the specified path parameter.

func (r *DefaultRes) MsgPack(data any, ctype ...string) error

Source: res.go:789

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) NoContent() error

Source: res.go:1520

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.

func (r *DefaultRes) OriginalURL() string

Source: res.go:1058

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) Redirect() *Redirect

Source: res.go:1066

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) Render(name string, bind any, layouts ...string) error

Source: res.go:1095

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.

func (r *DefaultRes) RequestCtx() *fasthttp.RequestCtx

Source: res.go:364

RequestCtx returns *fasthttp.RequestCtx that carries a deadline a cancellation signal, and other values across API boundaries.

func (r *DefaultRes) ResetBody()

Source: res.go:1240

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.

func (r *DefaultRes) Response() *fasthttp.Response

Source: res.go:580

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) Send(body []byte) error

Source: res.go:1254

Send sets the HTTP response body without copying it. From this point onward the body argument must not be changed.

func (r *DefaultRes) SendEarlyHints(hints []string) error

Source: res.go:1270

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

func (r *DefaultRes) SendFile(file string, config ...SendFile) error

Source: res.go:1311

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.

func (r *DefaultRes) SendStatus(status int) error

Source: res.go:1528

SendStatus sets the HTTP status code and if the response body is empty, it sets the correct status message in the body.

func (r *DefaultRes) SendStream(stream io.Reader, size ...int) error

Source: res.go:1561

SendStream sets response body stream and optional body size.

func (r *DefaultRes) SendStreamWriter(streamWriter func(*bufio.Writer)) error

Source: res.go:1572

SendStreamWriter sets response body stream writer

func (r *DefaultRes) SendString(body string) error

Source: res.go:1554

SendString sets the HTTP response body for string types. This means no type assertion, recommended for faster performance

func (r *DefaultRes) Set(key, val string)

Source: res.go:1579

Set sets the response's HTTP header field to the specified key, value.

func (r *DefaultRes) Status(status int) Ctx

Source: res.go:1599

Status sets the HTTP status for the response. This method is chainable.

A status outside 100 to 999 is logged and replaced by 500.

func (r *DefaultRes) StatusCode() int

Source: res.go:1607

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.

func (r *DefaultRes) Type(extension string, charset ...string) Ctx

Source: res.go:1626

Type sets the Content-Type HTTP header to the MIME type specified by the file extension.

func (r *DefaultRes) Vary(fields ...string)

Source: res.go:1670

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 "*".

func (r *DefaultRes) ViewBind(vars Map) error

Source: res.go:1072

ViewBind Add vars to default view var map binding to template engine. Variables are read by the Render method and may be overwritten.

func (r *DefaultRes) Write(p []byte) (int, error)

Source: res.go:1699

Write appends p into response body.

func (r *DefaultRes) WriteString(s string) (int, error)

Source: res.go:1711

WriteString appends s to response body.

func (r *DefaultRes) Writef(f string, a ...any) (int, error)

Source: res.go:1705

Writef appends f & a into response body writer.

func (r *DefaultRes) Written() bool

Source: res.go:1247

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.

func (r *DefaultRes) XML(data any) error

Source: res.go:1005

XML converts any interface or string to XML. This method also sets the content header to application/xml; charset=utf-8.

type EmptyFieldError

Source: error.go:71

EmptyFieldError error exposes the internal schema.EmptyFieldError for public use.

type EmptyFieldError = schema.EmptyFieldError

type Error

Source: app.go:70

Error represents an error that occurred while handling a request.

type Error struct {
	Message string `json:"message"`
	Code    int    `json:"code"`
}
Fields
  • Message string `json:"message"`
  • Code int `json:"code"`

func (e *Error) Error() string

Source: app.go:1312

Error makes it compatible with the error interface.

type ErrorHandler

Source: app.go:67

ErrorHandler defines a function that will process all errors returned from any handlers in the stack

cfg := fiber.Config{}
cfg.ErrorHandler = func(c Ctx, err error) error {
 code := StatusInternalServerError
 var e *fiber.Error
 matched := errors.As(err, &e)
 if matched && e != nil {
   code = e.Code
 }
 message := utils.StatusMessage(code)
 if err != nil && !(matched && e == nil) {
   message = err.Error()
 }
 c.Set(HeaderContentType, MIMETextPlainCharsetUTF8)
 return c.Status(code).SendString(message)
}
app := fiber.New(cfg)
type ErrorHandler = func(Ctx, error) error

type FlashMessage

Source: redirect.go:87

FlashMessage is a struct that holds the flash message data.

type FlashMessage struct {
	Key   string
	Value string
	Level uint8
}
Fields
  • Key string
  • Value string
  • Level uint8

type GenericType

Source: helpers.go:1358

GenericType enumerates the values that can be parsed from strings by the generic helper functions.

type GenericType interface {
	GenericTypeInteger | GenericTypeFloat | bool | string | []byte
}
Methods
  • GenericTypeInteger | GenericTypeFloat | bool | string | []byte

type GenericTypeFloat

Source: helpers.go:1378

GenericTypeFloat is the union of supported floating-point types.

type GenericTypeFloat interface {
	float32 | float64
}
Methods
  • float32 | float64

type GenericTypeInteger

Source: helpers.go:1363

GenericTypeInteger is the union of all supported integer types.

type GenericTypeInteger interface {
	GenericTypeIntegerSigned | GenericTypeIntegerUnsigned
}
Methods
  • GenericTypeIntegerSigned | GenericTypeIntegerUnsigned

type GenericTypeIntegerSigned

Source: helpers.go:1368

GenericTypeIntegerSigned is the union of supported signed integer types.

type GenericTypeIntegerSigned interface {
	int | int8 | int16 | int32 | int64
}
Methods
  • int | int8 | int16 | int32 | int64

type GenericTypeIntegerUnsigned

Source: helpers.go:1373

GenericTypeIntegerUnsigned is the union of supported unsigned integer types.

type GenericTypeIntegerUnsigned interface {
	uint | uint8 | uint16 | uint32 | uint64
}
Methods
  • uint | uint8 | uint16 | uint32 | uint64

type Group

Source: group.go:9

Group represents a collection of routes that share middleware and a common path prefix.

type Group struct {
	Prefix string
	// contains filtered or unexported fields
}
Fields
  • Prefix string

func (grp *Group) Add(methods []string, path string, handler any, handlers ...any) Router

Source: group.go:146

Add allows you to specify multiple HTTP methods to register a route. The provided handlers are executed in order, starting with handler and then the variadic handlers.

func (grp *Group) All(path string, handler any, handlers ...any) Router

Source: group.go:157

All will register the handler on all HTTP methods

func (grp *Group) Connect(path string, handler any, handlers ...any) Router

Source: group.go:116

Connect registers a route for CONNECT methods that establishes a tunnel to the server identified by the target resource.

func (grp *Group) Delete(path string, handler any, handlers ...any) Router

Source: group.go:110

Delete registers a route for DELETE methods that deletes the specified resource.

func (grp *Group) Domain(host string) Router

Source: group.go:194

Domain creates a new router scoped to the given hostname pattern within this group. Routes registered through the returned Router inherit the group prefix and only match requests whose hostname (from c.Hostname()) matches the pattern. When TrustProxy is enabled and the proxy is trusted, the hostname may be derived from the X-Forwarded-Host header.

To prevent header spoofing, configure both Config.TrustProxy and Config.TrustProxyConfig (trusted proxy IPs/ranges). See: https://docs.gofiber.io/api/fiber#trustproxy

api := app.Group("/api")
api.Domain("api.example.com").Get("/users", listUsers)

func (grp *Group) Get(path string, handler any, handlers ...any) Router

Source: group.go:87

Get registers a route for GET methods that requests a representation of the specified resource. Requests using GET should only retrieve data.

func (grp *Group) Group(prefix string, handlers ...any) Router

Source: group.go:166

Group is used for Routes with common prefix to define a new sub-router with optional middleware.

api := app.Group("/api")
api.Get("/users", handler)

func (grp *Group) Head(path string, handler any, handlers ...any) Router

Source: group.go:93

Head registers a route for HEAD methods that asks for a response identical to that of a GET request, but without the response body.

func (grp *Group) Name(name string) Router

Source: group.go:22

Name Assign name to specific route or group itself.

If this method is used before any route added to group, it'll set group name and OnGroupNameHook will be used. Otherwise, it'll set route name and OnName hook will be used.

func (grp *Group) Options(path string, handler any, handlers ...any) Router

Source: group.go:122

Options registers a route for OPTIONS methods that is used to describe the communication options for the target resource.

func (grp *Group) Patch(path string, handler any, handlers ...any) Router

Source: group.go:134

Patch registers a route for PATCH methods that is used to apply partial modifications to a resource.

func (grp *Group) Post(path string, handler any, handlers ...any) Router

Source: group.go:99

Post registers a route for POST methods that is used to submit an entity to the specified resource, often causing a change in state or side effects on the server.

func (grp *Group) Put(path string, handler any, handlers ...any) Router

Source: group.go:105

Put registers a route for PUT methods that replaces all current representations of the target resource with the request payload.

func (grp *Group) Query(path string, handler any, handlers ...any) Router

Source: group.go:140

Query registers a route for QUERY methods that performs a safe, idempotent query with a request body.

func (grp *Group) Route(prefix string, fn func(router Router), name ...string) Router

Source: group.go:214

Route is used to define routes with a common prefix inside the supplied function. It mirrors the legacy helper and reuses the Group method to create a sub-router.

func (grp *Group) RouteChain(path string) Register

Source: group.go:204

RouteChain creates a Registering instance scoped to the group's prefix, allowing chained route declarations for the same path.

func (grp *Group) Trace(path string, handler any, handlers ...any) Router

Source: group.go:128

Trace registers a route for TRACE methods that performs a message loop-back test along the path to the target resource.

func (grp *Group) Use(args ...any) Router

Source: group.go:66

Use registers a middleware route that will match requests with the provided prefix (which is optional and defaults to "/"). Also, you can pass another app instance as a sub-router along a routing path. It's very useful to split up a large API as many independent routers and compose them as a single service using Use. The fiber's error handler and any of the fiber's sub apps are added to the application's error handlers to be invoked on errors that happen within the prefix route.

	app.Use(func(c fiber.Ctx) error {
	     return c.Next()
	})
	app.Use("/api", func(c fiber.Ctx) error {
	     return c.Next()
	})
	app.Use("/api", handler, func(c fiber.Ctx) error {
	     return c.Next()
	})
 	subApp := fiber.New()
	app.Use("/mounted-path", subApp)

This method will match all HTTP verbs: GET, POST, PUT, HEAD etc...

type Handler

Source: app.go:43

Handler defines a function to serve HTTP requests.

type Handler = func(Ctx) error

type Hooks

Source: hooks.go:35

Hooks is a struct to use it with App.

type Hooks struct {
	// contains filtered or unexported fields
}

func (h *Hooks) OnFork(handler ...OnForkHandler)

Source: hooks.go:312

OnFork is a hook to execute user functions in the prefork master process each time it starts a child process, including a child it starts again after a crash. The handler receives the PID of that child; the children do not run it.

func (h *Hooks) OnGroup(handler ...OnGroupHandler)

Source: hooks.go:259

OnGroup is a hook to execute user functions on each group registration. Also you can get group properties by group parameter.

func (h *Hooks) OnGroupName(handler ...OnGroupNameHandler)

Source: hooks.go:269

OnGroupName is a hook to execute user functions on each group naming. Also you can get group properties by group parameter.

WARN: OnGroupName only works with naming groups, not routes.

func (h *Hooks) OnListen(handler ...OnListenHandler)

Source: hooks.go:276

OnListen is a hook to execute user functions on Listen or Listener.

func (h *Hooks) OnMount(handler ...OnMountHandler)

Source: hooks.go:321

OnMount is a hook to execute user function after mounting process. The mount event is fired when sub-app is mounted on a parent app. The parent app is passed as a parameter. It works for app and group mounting.

func (h *Hooks) OnName(handler ...OnNameHandler)

Source: hooks.go:251

OnName is a hook to execute user functions on each route naming. Also you can get route properties by route parameter.

WARN: OnName only works with naming routes, not groups.

func (h *Hooks) OnPostShutdown(handler ...OnPostShutdownHandler)

Source: hooks.go:304

OnPostShutdown is a hook to execute user functions after Shutdown.

func (h *Hooks) OnPostStartupMessage(handler ...OnPostStartupMessageHandler)

Source: hooks.go:290

OnPostStartupMessage is a hook to execute user functions after the startup message is printed (or skipped).

func (h *Hooks) OnPreShutdown(handler ...OnPreShutdownHandler)

Source: hooks.go:297

OnPreShutdown is a hook to execute user functions before Shutdown.

func (h *Hooks) OnPreStartupMessage(handler ...OnPreStartupMessageHandler)

Source: hooks.go:283

OnPreStartupMessage is a hook to execute user functions before the startup message is printed.

func (h *Hooks) OnRoute(handler ...OnRouteHandler)

Source: hooks.go:241

OnRoute is a hook to execute user functions on each route registration. Also you can get route properties by route parameter.

type InvalidUnmarshalError

Source: error.go:80

InvalidUnmarshalError describes an invalid argument passed to Unmarshal. (The argument to Unmarshal must be a non-nil pointer.)

type InvalidUnmarshalError = json.InvalidUnmarshalError

type ListenConfig

Source: listen.go:52

ListenConfig is a struct to customize startup of Fiber.

type ListenConfig struct {
	// GracefulContext is a field to shutdown Fiber by given context gracefully.
	//
	// A context that is done before the server starts to serve, including one that is
	// already done when Listen or Listener is called, shuts it down the same way:
	// Listen and Listener return once the shutdown has finished.
	//
	// With EnablePrefork the context stops only the process it is canceled in;
	// deliver the signal to every process so each child drains its own connections.
	// The master only runs its shutdown hooks and keeps supervising its children, so
	// Listen returns in a child but not in the master.
	//
	// Default: nil
	GracefulContext context.Context `json:"graceful_context"` //nolint:containedctx // It's needed to set context inside Listen.

	// PreforkLogger sets a custom logger for the prefork process manager.
	// This only applies when EnablePrefork is true.
	//
	// Default: Fiber's built-in logger (log.Infof)
	PreforkLogger PreforkLogger `json:"prefork_logger"`

	// TLSConfigFunc allows customizing tls.Config as you want.
	//
	// Ignored when TLSConfig is set: configure that tls.Config directly instead.
	//
	// Default: nil
	TLSConfigFunc func(tlsConfig *tls.Config) `json:"tls_config_func"`

	// TLSConfig is cloned and served as supplied, enabling external certificate
	// providers via GetCertificate. It replaces the other TLS settings rather than
	// seeding them, so there is no mutual TLS unless its ClientAuth requires it.
	//
	// Default: nil
	TLSConfig *tls.Config `json:"tls_config"`

	// ListenerAddrFunc is called with the net.Addr of the listener that Listen creates,
	// for example to read the port the OS picked for ":0". It cannot change the listener.
	// With prefork it runs once in each child process, and Listener does not call it.
	//
	// Default: nil
	ListenerAddrFunc func(addr net.Addr) `json:"listener_addr_func"`

	// BeforeServeFunc allows customizing and accessing fiber app before serving the app.
	//
	// Default: nil
	BeforeServeFunc func(app *App) error `json:"before_serve_func"`

	// AutoCertManager manages TLS certificates automatically using the ACME protocol,
	// Enables integration with Let's Encrypt or other ACME-compatible providers.
	//
	// Default: nil
	AutoCertManager *autocert.Manager `json:"auto_cert_manager"`

	// Known networks are "tcp", "tcp4" (IPv4-only), "tcp6" (IPv6-only), "unix" (Unix Domain Sockets)
	// WARNING: When prefork is set to true, only "tcp4" and "tcp6" can be chosen.
	//
	// Default: NetworkTCP4
	ListenerNetwork string `json:"listener_network"`

	// CertFile is a path of certificate file.
	// If you want to use TLS, you have to enter this field.
	//
	// Default : ""
	CertFile string `json:"cert_file"`

	// KeyFile is a path of certificate's private key.
	// If you want to use TLS, you have to enter this field.
	//
	// Default : ""
	CertKeyFile string `json:"cert_key_file"`

	// CertClientFile is a path of the CA bundle used to verify client
	// certificates, which is how ListenConfig asks for mTLS. Ignored when
	// TLSConfig is set: its ClientAuth decides instead, against its ClientCAs.
	//
	// Default : ""
	CertClientFile string `json:"cert_client_file"`

	// When the graceful shutdown begins, use this field to set the timeout
	// duration. If the timeout is reached, OnPostShutdown will be called with the error.
	// It bounds the wait for connections only; Listen also waits for the shutdown hooks.
	// Negative disables the timeout and waits indefinitely; zero applies the default.
	//
	// Default: 10 * time.Second
	ShutdownTimeout time.Duration `json:"shutdown_timeout"`

	// PreforkRecoverInterval delays the respawn of a crashed child process by this
	// duration. This only applies when EnablePrefork is true.
	//
	// Default: 0 (respawn immediately)
	PreforkRecoverInterval time.Duration `json:"prefork_recover_interval"`

	// PreforkShutdownGracePeriod is how long the prefork master waits for child
	// processes to exit after SIGTERM before sending SIGKILL during shutdown.
	// On Windows children are always killed immediately. This only applies when
	// EnablePrefork is true.
	//
	// Default: 5 * time.Second
	PreforkShutdownGracePeriod time.Duration `json:"prefork_shutdown_grace_period"`

	// FileMode to set for Unix Domain Socket (ListenerNetwork must be "unix")
	//
	// Default: 0770
	UnixSocketFileMode os.FileMode `json:"unix_socket_file_mode"`

	// TLSMinVersion allows to set TLS minimum version.
	//
	// Ignored when TLSConfig is set: set MinVersion on that tls.Config instead.
	//
	// Default: tls.VersionTLS12
	// WARNING: TLS1.0 and TLS1.1 versions are not supported.
	TLSMinVersion uint16 `json:"tls_min_version"`

	// When set to true, it will not print out the «Fiber» ASCII art and listening address.
	//
	// Default: false
	DisableStartupMessage bool `json:"disable_startup_message"`

	// When set to true, this will spawn multiple Go processes listening on the same port.
	//
	// Default: false
	EnablePrefork bool `json:"enable_prefork"`

	// PreforkRecoverThreshold defines the maximum number of times a child process
	// can be restarted after crashing before the master process exits with an error.
	// This only applies when EnablePrefork is true.
	//
	// Default: max(1, runtime.GOMAXPROCS(0) / 2)
	PreforkRecoverThreshold int `json:"prefork_recover_threshold"`

	// If set to true, will print all routes with their method, path and handler.
	//
	// Default: false
	EnablePrintRoutes bool `json:"enable_print_routes"`
}
Fields
  • GracefulContext context.Context `json:"graceful_context"`

    GracefulContext is a field to shutdown Fiber by given context gracefully.

    A context that is done before the server starts to serve, including one that is already done when Listen or Listener is called, shuts it down the same way: Listen and Listener return once the shutdown has finished.

    With EnablePrefork the context stops only the process it is canceled in; deliver the signal to every process so each child drains its own connections. The master only runs its shutdown hooks and keeps supervising its children, so Listen returns in a child but not in the master.

    Default: nil

  • PreforkLogger PreforkLogger `json:"prefork_logger"`

    PreforkLogger sets a custom logger for the prefork process manager. This only applies when EnablePrefork is true.

    Default: Fiber's built-in logger (log.Infof)

  • TLSConfigFunc func(tlsConfig *tls.Config) `json:"tls_config_func"`

    TLSConfigFunc allows customizing tls.Config as you want.

    Ignored when TLSConfig is set: configure that tls.Config directly instead.

    Default: nil

  • TLSConfig *tls.Config `json:"tls_config"`

    TLSConfig is cloned and served as supplied, enabling external certificate providers via GetCertificate. It replaces the other TLS settings rather than seeding them, so there is no mutual TLS unless its ClientAuth requires it.

    Default: nil

  • ListenerAddrFunc func(addr net.Addr) `json:"listener_addr_func"`

    ListenerAddrFunc is called with the net.Addr of the listener that Listen creates, for example to read the port the OS picked for ":0". It cannot change the listener. With prefork it runs once in each child process, and Listener does not call it.

    Default: nil

  • BeforeServeFunc func(app *App) error `json:"before_serve_func"`

    BeforeServeFunc allows customizing and accessing fiber app before serving the app.

    Default: nil

  • AutoCertManager *autocert.Manager `json:"auto_cert_manager"`

    AutoCertManager manages TLS certificates automatically using the ACME protocol, Enables integration with Let's Encrypt or other ACME-compatible providers.

    Default: nil

  • ListenerNetwork string `json:"listener_network"`

    Known networks are "tcp", "tcp4" (IPv4-only), "tcp6" (IPv6-only), "unix" (Unix Domain Sockets) WARNING: When prefork is set to true, only "tcp4" and "tcp6" can be chosen.

    Default: NetworkTCP4

  • CertFile string `json:"cert_file"`

    CertFile is a path of certificate file. If you want to use TLS, you have to enter this field.

    Default : ""

  • CertKeyFile string `json:"cert_key_file"`

    KeyFile is a path of certificate's private key. If you want to use TLS, you have to enter this field.

    Default : ""

  • CertClientFile string `json:"cert_client_file"`

    CertClientFile is a path of the CA bundle used to verify client certificates, which is how ListenConfig asks for mTLS. Ignored when TLSConfig is set: its ClientAuth decides instead, against its ClientCAs.

    Default : ""

  • ShutdownTimeout time.Duration `json:"shutdown_timeout"`

    When the graceful shutdown begins, use this field to set the timeout duration. If the timeout is reached, OnPostShutdown will be called with the error. It bounds the wait for connections only; Listen also waits for the shutdown hooks. Negative disables the timeout and waits indefinitely; zero applies the default.

    Default: 10 * time.Second

  • PreforkRecoverInterval time.Duration `json:"prefork_recover_interval"`

    PreforkRecoverInterval delays the respawn of a crashed child process by this duration. This only applies when EnablePrefork is true.

    Default: 0 (respawn immediately)

  • PreforkShutdownGracePeriod time.Duration `json:"prefork_shutdown_grace_period"`

    PreforkShutdownGracePeriod is how long the prefork master waits for child processes to exit after SIGTERM before sending SIGKILL during shutdown. On Windows children are always killed immediately. This only applies when EnablePrefork is true.

    Default: 5 * time.Second

  • UnixSocketFileMode os.FileMode `json:"unix_socket_file_mode"`

    FileMode to set for Unix Domain Socket (ListenerNetwork must be "unix")

    Default: 0770

  • TLSMinVersion uint16 `json:"tls_min_version"`

    TLSMinVersion allows to set TLS minimum version.

    Ignored when TLSConfig is set: set MinVersion on that tls.Config instead.

    Default: tls.VersionTLS12 WARNING: TLS1.0 and TLS1.1 versions are not supported.

  • DisableStartupMessage bool `json:"disable_startup_message"`

    When set to true, it will not print out the «Fiber» ASCII art and listening address.

    Default: false

  • EnablePrefork bool `json:"enable_prefork"`

    When set to true, this will spawn multiple Go processes listening on the same port.

    Default: false

  • PreforkRecoverThreshold int `json:"prefork_recover_threshold"`

    PreforkRecoverThreshold defines the maximum number of times a child process can be restarted after crashing before the master process exits with an error. This only applies when EnablePrefork is true.

    Default: max(1, runtime.GOMAXPROCS(0) / 2)

  • EnablePrintRoutes bool `json:"enable_print_routes"`

    If set to true, will print all routes with their method, path and handler.

    Default: false

type ListenData

Source: hooks.go:76

ListenData contains the listener metadata provided to OnListenHandler.

type ListenData struct {
	ColorScheme Colors
	Host        string
	Port        string
	Version     string
	AppName     string

	ChildPIDs []int

	HandlerCount int
	ProcessCount int
	PID          int

	TLS     bool
	Prefork bool
}
Fields
  • ColorScheme Colors
  • Host string
  • Port string
  • Version string
  • AppName string
  • ChildPIDs []int
  • HandlerCount int
  • ProcessCount int
  • PID int
  • TLS bool
  • Prefork bool

type Map

Source: app.go:46

Map is a shortcut for map[string]any, useful for JSON returns

type Map map[string]any

type MarshalerError

Source: error.go:83

MarshalerError represents an error from calling a MarshalJSON or MarshalText method.

type MarshalerError = json.MarshalerError

type MultiError

Source: error.go:73

MultiError error exposes the internal schema.MultiError for public use.

type MultiError = schema.MultiError

type OldInputData

Source: redirect.go:81

OldInputData is a struct that holds the old input data.

type OldInputData struct {
	Key   string
	Value string
}
Fields
  • Key string
  • Value string

type OnForkHandler

Source: hooks.go:29

OnForkHandler runs in the prefork master process each time it starts a child process and receives that child's PID.

type OnForkHandler = func(int) error

type OnGroupHandler

Source: hooks.go:15

OnGroupHandler defines the hook signature invoked whenever a group is registered.

type OnGroupHandler = func(Group) error

type OnGroupNameHandler

Source: hooks.go:17

OnGroupNameHandler shares the OnGroupHandler signature for group naming callbacks.

type OnGroupNameHandler = OnGroupHandler

type OnListenHandler

Source: hooks.go:19

OnListenHandler runs when the application begins listening and receives the listener details.

type OnListenHandler = func(ListenData) error

type OnMountHandler

Source: hooks.go:31

OnMountHandler runs after a sub-application mounts to a parent and receives the parent app reference.

type OnMountHandler = func(*App) error

type OnNameHandler

Source: hooks.go:13

OnNameHandler shares the OnRouteHandler signature for route naming callbacks.

type OnNameHandler = OnRouteHandler

type OnPostShutdownHandler

Source: hooks.go:27

OnPostShutdownHandler runs after shutdown and receives the shutdown result.

type OnPostShutdownHandler = func(error) error

type OnPostStartupMessageHandler

Source: hooks.go:23

OnPostStartupMessageHandler runs after Fiber prints (or skips) the startup banner.

type OnPostStartupMessageHandler = func(*PostStartupMessageData) error

type OnPreShutdownHandler

Source: hooks.go:25

OnPreShutdownHandler runs before the application shuts down.

type OnPreShutdownHandler = func() error

type OnPreStartupMessageHandler

Source: hooks.go:21

OnPreStartupMessageHandler runs before Fiber prints the startup banner.

type OnPreStartupMessageHandler = func(*PreStartupMessageData) error

type OnRouteHandler

Source: hooks.go:11

OnRouteHandler defines the hook signature invoked whenever a route is registered.

type OnRouteHandler = func(Route) error

type PostStartupMessageData

Source: hooks.go:195

PostStartupMessageData contains metadata exposed to OnPostStartupMessage hooks.

type PostStartupMessageData struct {
	*ListenData

	// Disabled indicates whether the startup message was disabled via configuration.
	Disabled bool

	// IsChild indicates whether the current process is a child in prefork mode.
	IsChild bool

	// Prevented indicates whether the startup message was suppressed by a pre-startup hook using PreventDefault property.
	Prevented bool
}
Fields
  • *ListenData
  • Disabled bool

    Disabled indicates whether the startup message was disabled via configuration.

  • IsChild bool

    IsChild indicates whether the current process is a child in prefork mode.

  • Prevented bool

    Prevented indicates whether the startup message was suppressed by a pre-startup hook using PreventDefault property.

type PreStartupMessageData

Source: hooks.go:94

PreStartupMessageData contains metadata exposed to OnPreStartupMessage hooks.

type PreStartupMessageData struct {
	*ListenData

	// BannerHeader allows overriding the ASCII art banner displayed at startup.
	BannerHeader string

	// PreventDefault, when set to true, suppresses the default startup message.
	PreventDefault bool
	// contains filtered or unexported fields
}
Fields
  • *ListenData
  • BannerHeader string

    BannerHeader allows overriding the ASCII art banner displayed at startup.

  • PreventDefault bool

    PreventDefault, when set to true, suppresses the default startup message.

func (sm *PreStartupMessageData) AddError(key, title, value string, priority ...int)

Source: hooks.go:127

AddError adds an error entry to the startup message with "ERROR" label.

func (sm *PreStartupMessageData) AddInfo(key, title, value string, priority ...int)

Source: hooks.go:107

AddInfo adds an informational entry to the startup message with "INFO" label.

func (sm *PreStartupMessageData) AddWarning(key, title, value string, priority ...int)

Source: hooks.go:117

AddWarning adds a warning entry to the startup message with "WARN" label.

func (sm *PreStartupMessageData) DeleteEntry(key string)

Source: hooks.go:151

DeleteEntry removes a specific entry from the startup message by its key.

func (sm *PreStartupMessageData) EntryKeys() []string

Source: hooks.go:137

EntryKeys returns all entry keys currently present in the startup message.

func (sm *PreStartupMessageData) ResetEntries()

Source: hooks.go:146

ResetEntries removes all existing entries from the startup message.

type PreforkLogger

Source: prefork_logger.go:9

PreforkLogger defines a logger for the prefork process manager. Compatible with fasthttp/prefork.Logger.

type PreforkLogger interface {
	// Printf must have the same semantics as log.Printf.
	Printf(format string, args ...any)
}
Methods
  • Printf func(format string, args ...any)

    Printf must have the same semantics as log.Printf.

type Range

Source: req.go:51

Range represents the parsed HTTP Range header extracted by DefaultReq.Range.

type Range struct {
	Type   string
	Ranges []RangeSet
}
Fields
  • Type string
  • Ranges []RangeSet

type RangeSet

Source: req.go:57

RangeSet represents a single content range from a request.

type RangeSet struct {
	Start int64
	End   int64
}
Fields
  • Start int64
  • End int64

type Redirect

Source: redirect.go:94

Redirect is a struct that holds the redirect data.

type Redirect struct {
	// contains filtered or unexported fields
}

func (r *Redirect) Back(fallback ...string) error

Source: redirect.go:421

Back redirect to the URL to referer. It validates that the Referer is same-origin to prevent open redirect attacks. If the Referer is missing, invalid, or cross-origin, the fallback URL is used.

func (r *Redirect) Message(key string) FlashMessage

Source: redirect.go:267

Message Get flash message by key.

func (r *Redirect) Messages() []FlashMessage

Source: redirect.go:235

Messages Get flash messages.

func (r *Redirect) OldInput(key string) OldInputData

Source: redirect.go:328

OldInput Get old input data by key.

func (r *Redirect) OldInputs() []OldInputData

Source: redirect.go:301

OldInputs Get old input data.

func (r *Redirect) Route(name string, config ...RedirectConfig) error

Source: redirect.go:355

Route redirects to the Route registered in the app with appropriate parameters. If you want to send queries or params to route, you should use config parameter.

func (r *Redirect) Status(code int) *Redirect

Source: redirect.go:162

Status sets the status code of redirection. If status is not specified, status defaults to 303 See Other.

func (r *Redirect) To(location string) error

Source: redirect.go:344

To redirect to the URL derived from the specified path, with specified status.

func (r *Redirect) With(key, value string, level ...uint8) *Redirect

Source: redirect.go:174

With You can send flash messages by using With(). They will be sent as a cookie. You can get them by using: Redirect().Messages(), Redirect().Message() The cookie payload is MessagePack encoded, so keys and values need no escaping. Calling With again with the same key replaces the earlier message. No cookie is set when Config.DisableFlashMessages is on.

func (r *Redirect) WithInput() *Redirect

Source: redirect.go:205

WithInput You can send input data by using WithInput(). They will be sent as a cookie. This method can send form, multipart form, query data to redirected route. You can get them by using: Redirect().OldInputs(), Redirect().OldInput() It does nothing when Config.DisableFlashMessages is on.

type RedirectConfig

Source: redirect.go:103

RedirectConfig A config to use with Redirect().Route() You can specify queries or route parameters. NOTE: We don't use net/url to parse parameters because of it has poor performance. You have to pass map.

type RedirectConfig struct {
	Params  Map               // Route parameters
	Queries map[string]string // Query map
}
Fields
  • Params Map

    Route parameters

  • Queries map[string]string

    Query map

type Register

Source: register.go:8

Register defines all router handle interface generate by RouteChain().

type Register interface {
	All(handler any, handlers ...any) Register
	Get(handler any, handlers ...any) Register
	Head(handler any, handlers ...any) Register
	Post(handler any, handlers ...any) Register
	Put(handler any, handlers ...any) Register
	Delete(handler any, handlers ...any) Register
	Connect(handler any, handlers ...any) Register
	Options(handler any, handlers ...any) Register
	Trace(handler any, handlers ...any) Register
	Patch(handler any, handlers ...any) Register
	Query(handler any, handlers ...any) Register

	Add(methods []string, handler any, handlers ...any) Register

	RouteChain(path string) Register
}
Methods
  • All func(handler any, handlers ...any) Register
  • Get func(handler any, handlers ...any) Register
  • Head func(handler any, handlers ...any) Register
  • Post func(handler any, handlers ...any) Register
  • Put func(handler any, handlers ...any) Register
  • Delete func(handler any, handlers ...any) Register
  • Connect func(handler any, handlers ...any) Register
  • Options func(handler any, handlers ...any) Register
  • Trace func(handler any, handlers ...any) Register
  • Patch func(handler any, handlers ...any) Register
  • Query func(handler any, handlers ...any) Register
  • Add func(methods []string, handler any, handlers ...any) Register
  • RouteChain func(path string) Register

type Registering

Source: register.go:30

Registering provides route registration helpers for a specific path on the application instance.

type Registering struct {
	// contains filtered or unexported fields
}

func (r *Registering) Add(methods []string, handler any, handlers ...any) Register

Source: register.go:118

Add allows you to specify multiple HTTP methods to register a route. The provided handlers are executed in order, starting with handler and then the variadic handlers.

func (r *Registering) All(handler any, handlers ...any) Register

Source: register.go:51

All registers a middleware route that will match requests with the provided path which is stored in register struct.

app.RouteChain("/").All(func(c fiber.Ctx) error {
     return c.Next()
})
app.RouteChain("/api").All(func(c fiber.Ctx) error {
     return c.Next()
})
app.RouteChain("/api").All(handler, func(c fiber.Ctx) error {
     return c.Next()
})

This method will match all HTTP verbs: GET, POST, PUT, HEAD etc...

func (r *Registering) Connect(handler any, handlers ...any) Register

Source: register.go:88

Connect registers a route for CONNECT methods that establishes a tunnel to the server identified by the target resource.

func (r *Registering) Delete(handler any, handlers ...any) Register

Source: register.go:82

Delete registers a route for DELETE methods that deletes the specified resource.

func (r *Registering) Get(handler any, handlers ...any) Register

Source: register.go:59

Get registers a route for GET methods that requests a representation of the specified resource. Requests using GET should only retrieve data.

func (r *Registering) Head(handler any, handlers ...any) Register

Source: register.go:65

Head registers a route for HEAD methods that asks for a response identical to that of a GET request, but without the response body.

func (r *Registering) Options(handler any, handlers ...any) Register

Source: register.go:94

Options registers a route for OPTIONS methods that is used to describe the communication options for the target resource.

func (r *Registering) Patch(handler any, handlers ...any) Register

Source: register.go:106

Patch registers a route for PATCH methods that is used to apply partial modifications to a resource.

func (r *Registering) Post(handler any, handlers ...any) Register

Source: register.go:71

Post registers a route for POST methods that is used to submit an entity to the specified resource, often causing a change in state or side effects on the server.

func (r *Registering) Put(handler any, handlers ...any) Register

Source: register.go:77

Put registers a route for PUT methods that replaces all current representations of the target resource with the request payload.

func (r *Registering) Query(handler any, handlers ...any) Register

Source: register.go:112

Query registers a route for QUERY methods that performs a safe, idempotent query with a request body.

func (r *Registering) RouteChain(path string) Register

Source: register.go:126

RouteChain returns a new Register instance whose route path takes the path in the current instance as its prefix.

func (r *Registering) Trace(handler any, handlers ...any) Register

Source: register.go:100

Trace registers a route for TRACE methods that performs a message loop-back test along the r.Path to the target resource.

type Req

Source: req_interface_gen.go:14

Req is an interface for request-related Ctx methods.

type Req interface {
	// 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
	// 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
	// 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

	// 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.
	Body() []byte
	// 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
	// ContentLength returns the value of the Content-Length request header. A
	// negative result is not a length: -1 is chunked and -2 is identity, which is
	// what a bodyless GET reports. Use HasBody to test for a body at all.
	ContentLength() int
	// RequestCtx returns *fasthttp.RequestCtx that carries a deadline
	// a cancellation signal, and other values across API boundaries.
	RequestCtx() *fasthttp.RequestCtx
	// FullURL returns the full request URL (protocol + host + original URL). Of an absolute-form
	// request target ("GET http://example.com/search") only the path and query follow the host.
	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

	// 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
	// ContentType returns the Content-Type request header, parameters included;
	// MediaType strips them and Charset returns just the charset. On Ctx the request
	// wins over Res. Only valid within the handler unless Immutable is set.
	ContentType() string
	// 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
	// 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.
	Cookies(key string, defaultValue ...string) string
	// 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
	// Request return the *fasthttp.Request object
	// This allows you to use all fasthttp request methods
	// https://godoc.org/github.com/valyala/fasthttp#Request
	Request() *fasthttp.Request
	// 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)
	// 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
	// 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)

	// 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
	// GetHeaders (a.k.a 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.
	GetHeaders() map[string][]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.
	// Behind a trusted proxy it is the first non-empty X-Forwarded-Host element when there is one, trimmed but neither validated nor case-folded.
	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

	// 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)
	// 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
	// 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)
	// Endpoint returns the route that will handle this request. See Ctx.Endpoint.
	Endpoint() *Route
	// Route returns the matched Route struct.
	Route() *Route
	// 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
	// contains filtered or unexported methods
}
Methods
  • Accepts func(offers ...string) string

    Accepts checks if the specified extensions or content types are acceptable.

  • AcceptsCharsets func(offers ...string) string

    AcceptsCharsets checks if the specified charset is acceptable.

  • AcceptsEncodings func(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.

  • AcceptsLanguages func(offers ...string) string

    AcceptsLanguages checks if the specified language is acceptable using RFC 4647 Basic Filtering.

  • AcceptsLanguagesExtended func(offers ...string) string

    AcceptsLanguagesExtended checks if the specified language is acceptable using RFC 4647 Extended Filtering.

  • App func() *App

    App returns the *App reference to the instance of the Fiber application

  • BaseURL func() string

    BaseURL returns (protocol + host), such as "https://example.com". It carries no path.

  • BodyRaw func() []byte

    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.

  • Body func() []byte

    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.

  • BodyStream func() io.Reader

    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.

  • ContentLength func() int

    ContentLength returns the value of the Content-Length request header. A negative result is not a length: -1 is chunked and -2 is identity, which is what a bodyless GET reports. Use HasBody to test for a body at all.

  • RequestCtx func() *fasthttp.RequestCtx

    RequestCtx returns *fasthttp.RequestCtx that carries a deadline a cancellation signal, and other values across API boundaries.

  • FullURL func() string

    FullURL returns the full request URL (protocol + host + original URL). Of an absolute-form request target ("GET http://example.com/search") only the path and query follow the host.

  • UserAgent func() string

    UserAgent returns the User-Agent request header.

  • Referer func() string

    Referer returns the Referer request header.

  • Origin func() 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.

  • AcceptLanguage func() string

    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.

  • AcceptEncoding func() 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.

  • HasHeader func(key string) bool

    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.

  • HasHeaderValue func(key, value 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.

  • ContentType func() string

    ContentType returns the Content-Type request header, parameters included; MediaType strips them and Charset returns just the charset. On Ctx the request wins over Res. Only valid within the handler unless Immutable is set.

  • MediaType func() string

    MediaType returns the MIME type from the Content-Type header without parameters.

  • Charset func() string

    Charset returns the charset parameter from the Content-Type header.

  • IsJSON func() bool

    IsJSON reports whether the Content-Type header is JSON.

  • IsForm func() bool

    IsForm reports whether the Content-Type header is form-encoded.

  • IsMultipart func() bool

    IsMultipart reports whether the Content-Type header is multipart form data.

  • AcceptsJSON func() bool

    AcceptsJSON reports whether the Accept header allows JSON.

  • AcceptsHTML func() bool

    AcceptsHTML reports whether the Accept header allows HTML.

  • AcceptsXML func() bool

    AcceptsXML reports whether the Accept header allows XML.

  • AcceptsEventStream func() bool

    AcceptsEventStream reports whether the Accept header allows text/event-stream.

  • Cookies func(key string, defaultValue ...string) string

    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.

  • CookieNames func() []string

    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.

  • AllCookies func() map[string]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.

  • Request func() *fasthttp.Request

    Request return the *fasthttp.Request object This allows you to use all fasthttp request methods https://godoc.org/github.com/valyala/fasthttp#Request

  • FormFile func(key string) (*multipart.FileHeader, error)

    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.

  • FormValue func(key string, defaultValue ...string) string

    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.

  • Fresh func() bool

    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

  • IfNoneMatch func() []string

    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.

  • IfModifiedSince func() (time.Time, error)

    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.

  • Get func(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.

  • GetAll func(key string) []string

    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.

  • Authorization func() (scheme, credentials 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.

  • Bearer func() string

    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.

  • GetHeaders func() map[string][]string

    GetHeaders (a.k.a 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.

  • Host func() 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. Behind a trusted proxy it is the first non-empty X-Forwarded-Host element when there is one, trimmed but neither validated nor case-folded.

  • Hostname func() 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.

  • Port func() string

    Port returns the remote port of the request.

  • IP func() 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.

  • IPs func() []string

    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.

  • Is func(extension string) bool

    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

  • HasBody func() bool

    HasBody returns true if the request declares a body via Content-Length, Transfer-Encoding, or already buffered payload data.

  • IsWebSocket func() bool

    IsWebSocket returns true if the request includes a WebSocket upgrade handshake.

  • IsPreflight func() bool

    IsPreflight returns true if the request is a CORS preflight.

  • Secure func() bool

    Secure returns whether a secure connection was established.

  • XHR func() 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).

  • Locals func(key any, value ...any) any

    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.

  • SetLocal func(key, value 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.

  • Method func(override ...string) string

    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.

  • IsSafe func() bool

    IsSafe reports whether the request method is safe, meaning it is not expected to change server state (RFC 9110 Section 9.2.1).

  • IsIdempotent func() 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.

  • MultipartForm func() (*multipart.Form, error)

    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.

  • OriginalURL func() string

    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.

  • URI func() *fasthttp.URI

    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.

  • Path func(override ...string) string

    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.

  • Params func(key string, defaultValue ...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.

  • Scheme func() 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.

  • Protocol func() string

    Protocol returns the HTTP protocol of request: HTTP/1.1 and HTTP/2.

  • Query func(key string, defaultValue ...string) 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.

  • Queries func() map[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"

  • Range func(size int64) (Range, error)

    Range returns a struct containing the type and a slice of ranges.

  • Endpoint func() *Route

    Endpoint returns the route that will handle this request. See Ctx.Endpoint.

  • Route func() *Route

    Route returns the matched Route struct.

  • Subdomains func(offset ...int) []string

    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.

  • Stale func() bool

    Stale returns the inverse of Fresh, indicating if the client's cached response is considered stale.

  • IsProxyTrusted func() 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.

  • IsFromLocal func() bool

    IsFromLocal will return true if request came from a loopback IP.

  • IsFromUnixSocket func() bool

    IsFromUnixSocket returns true if the request arrived over a Unix domain socket.

type Res

Source: res_interface_gen.go:13

Res is an interface for response-related Ctx methods.

type Res interface {
	// App returns the *App reference to the instance of the Fiber application
	App() *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.
	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)
	// RequestCtx returns *fasthttp.RequestCtx that carries a deadline
	// a cancellation signal, and other values across API boundaries.
	RequestCtx() *fasthttp.RequestCtx
	// 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
	// Response return the *fasthttp.Response object
	// This allows you to use all fasthttp response methods
	// https://godoc.org/github.com/valyala/fasthttp#Response
	Response() *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.
	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
	// 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.
	ContentLength() int
	// 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.
	ContentType() string
	// 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)
	// 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.
	Get(key string, defaultValue ...string) string
	// 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.
	GetHeaders() map[string][]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)
	// 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
	// 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

	// 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

	// Body returns the response body buffered so far, or nil for a streamed one,
	// which draining would de-stream; Written tells those apart. The buffer is live,
	// so writing to it writes to the response, and the next write voids it.
	Body() []byte
	// 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)

	// 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
	// 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
	// contains filtered or unexported methods
}
Methods
  • App func() *App

    App returns the *App reference to the instance of the Fiber application

  • Append func(field string, values ...string)

    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.

  • Add func(key, val 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.

  • Attachment func(filename ...string)

    Attachment sets the HTTP response Content-Disposition header field to attachment.

  • ClearCookie func(key ...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.

  • RequestCtx func() *fasthttp.RequestCtx

    RequestCtx returns *fasthttp.RequestCtx that carries a deadline a cancellation signal, and other values across API boundaries.

  • Cookie func(cookie *Cookie)

    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.

  • GetCookie func(name string) (*Cookie, bool)

    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.

  • GetCookies func() []*Cookie

    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.

  • Download func(file string, filename ...string) error

    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.

  • Response func() *fasthttp.Response

    Response return the *fasthttp.Response object This allows you to use all fasthttp response methods https://godoc.org/github.com/valyala/fasthttp#Response

  • Format func(handlers ...ResFmt) 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.

  • AutoFormat func(body any) 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.

  • ContentLength func() int

    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.

  • ContentType func() string

    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.

  • Del func(key string)

    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.

  • Get func(key string, defaultValue ...string) string

    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.

  • GetHeaders func() map[string][]string

    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.

  • JSON func(data any, ctype ...string) error

    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.

  • MsgPack func(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.

  • CBOR func(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.

  • JSONP func(data any, callback ...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.

  • XML func(data any) error

    XML converts any interface or string to XML. This method also sets the content header to application/xml; charset=utf-8.

  • Links func(link ...string)

    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.

  • Location func(path string)

    Location sets the response Location HTTP header to the specified path parameter.

  • OriginalURL func() string

    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.

  • Redirect func() *Redirect

    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.

  • ViewBind func(vars Map) error

    ViewBind Add vars to default view var map binding to template engine. Variables are read by the Render method and may be overwritten.

  • GetRouteURL func(routeName string, params Map) (string, error)

    GetRouteURL generates URLs to named routes, with parameters. URLs are relative, for example: "/user/1831"

  • Render func(name string, bind any, layouts ...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.

  • Body func() []byte

    Body returns the response body buffered so far, or nil for a streamed one, which draining would de-stream; Written tells those apart. The buffer is live, so writing to it writes to the response, and the next write voids it.

  • ResetBody func()

    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.

  • Written func() bool

    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.

  • Send func(body []byte) error

    Send sets the HTTP response body without copying it. From this point onward the body argument must not be changed.

  • SendEarlyHints func(hints []string) 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

  • SendFile func(file string, config ...SendFile) 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.

  • NoContent func() 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.

  • SendStatus func(status int) error

    SendStatus sets the HTTP status code and if the response body is empty, it sets the correct status message in the body.

  • SendString func(body string) error

    SendString sets the HTTP response body for string types. This means no type assertion, recommended for faster performance

  • SendStream func(stream io.Reader, size ...int) error

    SendStream sets response body stream and optional body size.

  • SendStreamWriter func(streamWriter func(*bufio.Writer)) error

    SendStreamWriter sets response body stream writer

  • Set func(key, val string)

    Set sets the response's HTTP header field to the specified key, value.

  • Status func(status int) Ctx

    Status sets the HTTP status for the response. This method is chainable.

    A status outside 100 to 999 is logged and replaced by 500.

  • StatusCode func() int

    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.

  • Type func(extension string, charset ...string) Ctx

    Type sets the Content-Type HTTP header to the MIME type specified by the file extension.

  • Vary func(fields ...string)

    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 "*".

  • Write func(p []byte) (int, error)

    Write appends p into response body.

  • Writef func(f string, a ...any) (int, error)

    Writef appends f & a into response body writer.

  • WriteString func(s string) (int, error)

    WriteString appends s to response body.

  • Drop func() 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.

  • End func() 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.

type ResFmt

Source: res.go:174

ResFmt associates a Content Type to a fiber.Handler for c.Format

type ResFmt struct {
	Handler   func(Ctx) error
	MediaType string
}
Fields
  • Handler func(Ctx) error
  • MediaType string

type Route

Source: router.go:87

Route is a struct that holds all metadata for each registered handler.

type Route struct {
	Params []string `json:"params"` // Case-sensitive param keys

	Handlers []Handler `json:"-"` // Ctx handlers

	// Public fields
	Method string `json:"method"` // HTTP method
	Name   string `json:"name"`   // Route's name
	//nolint:revive // Having both a Path (uppercase) and a path (lowercase) is fine
	Path string `json:"path"` // Original registered route path
	// contains filtered or unexported fields
}
Fields
  • Params []string `json:"params"`

    Case-sensitive param keys

  • Handlers []Handler `json:"-"`

    Ctx handlers

  • Method string `json:"method"`

    Public fields

    HTTP method

  • Name string `json:"name"`

    Route's name

  • Path string `json:"path"`

    Original registered route path

func (r Route) URL(params Map) (string, error)

Source: router.go:294

URL generates a URL from the route path and parameters. This method fills in the route parameters with the provided values. Parameter matching respects the app's CaseSensitive configuration: case-insensitive by default, case-sensitive when CaseSensitive is true. Parameter values are percent-encoded using URL path-segment rules. Dot-containing values that form a dot-only path segment, and slashes that UnescapePath would decode outside a parameter's match, return ErrRouteNotRepresentable.

Example:

app.Get("/user/:name/:id", handler).Name("user")
url, err := app.GetRoute("user").URL(Map{"name": "john", "id": "123"})
// Returns: "/user/john/123"

type RouteMessage

Source: app.go:653

RouteMessage is some message need to be print when server starts

type RouteMessage struct {
	// contains filtered or unexported fields
}

type Router

Source: router.go:57

Router defines all router handle interface, including app and group router.

type Router interface {
	Use(args ...any) Router

	Get(path string, handler any, handlers ...any) Router
	Head(path string, handler any, handlers ...any) Router
	Post(path string, handler any, handlers ...any) Router
	Put(path string, handler any, handlers ...any) Router
	Delete(path string, handler any, handlers ...any) Router
	Connect(path string, handler any, handlers ...any) Router
	Options(path string, handler any, handlers ...any) Router
	Trace(path string, handler any, handlers ...any) Router
	Patch(path string, handler any, handlers ...any) Router
	Query(path string, handler any, handlers ...any) Router

	Add(methods []string, path string, handler any, handlers ...any) Router
	All(path string, handler any, handlers ...any) Router

	Group(prefix string, handlers ...any) Router

	Domain(host string) Router

	RouteChain(path string) Register
	Route(prefix string, fn func(router Router), name ...string) Router

	Name(name string) Router
}
Methods
  • Use func(args ...any) Router
  • Get func(path string, handler any, handlers ...any) Router
  • Head func(path string, handler any, handlers ...any) Router
  • Post func(path string, handler any, handlers ...any) Router
  • Put func(path string, handler any, handlers ...any) Router
  • Delete func(path string, handler any, handlers ...any) Router
  • Connect func(path string, handler any, handlers ...any) Router
  • Options func(path string, handler any, handlers ...any) Router
  • Trace func(path string, handler any, handlers ...any) Router
  • Patch func(path string, handler any, handlers ...any) Router
  • Query func(path string, handler any, handlers ...any) Router
  • Add func(methods []string, path string, handler any, handlers ...any) Router
  • All func(path string, handler any, handlers ...any) Router
  • Group func(prefix string, handlers ...any) Router
  • Domain func(host string) Router
  • RouteChain func(path string) Register
  • Route func(prefix string, fn func(router Router), name ...string) Router
  • Name func(name string) Router

type SendFile

Source: res.go:33

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. A request for several
	// ranges, or whose If-Range does not match, gets the whole file.
	//
	// 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 max-age, in seconds, of the Cache-Control HTTP-header that is set
	// on the file response unless the response already has one.
	//
	// Optional. Default: 0
	MaxAge int `json:"max_age"`
}
Fields
  • FS fs.FS

    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

  • Compress bool `json:"compress"`

    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

  • ByteRange bool `json:"byte_range"`

    When set to true, enables byte range requests. A request for several ranges, or whose If-Range does not match, gets the whole file.

    Optional. Default: false

  • Download bool `json:"download"`

    When set to true, enables direct download.

    Optional. Default: false

  • CacheDuration time.Duration `json:"cache_duration"`

    Expiration duration for inactive file handlers. Use a negative time.Duration to disable it.

    Optional. Default: 10 * time.Second

  • MaxAge int `json:"max_age"`

    The max-age, in seconds, of the Cache-Control HTTP-header that is set on the file response unless the response already has one.

    Optional. Default: 0

type Service

Source: services.go:14

Service is an interface that defines the methods for a service.

type Service interface {
	// Start starts the service, returning an error if it fails.
	Start(ctx context.Context) error

	// String returns a string representation of the service.
	// It is used to print a human-readable name of the service in the startup message.
	String() string

	// State returns the current state of the service.
	State(ctx context.Context) (string, error)

	// Terminate terminates the service, returning an error if it fails.
	Terminate(ctx context.Context) error
}
Methods
  • Start func(ctx context.Context) error

    Start starts the service, returning an error if it fails.

  • String func() string

    String returns a string representation of the service. It is used to print a human-readable name of the service in the startup message.

  • State func(ctx context.Context) (string, error)

    State returns the current state of the service.

  • Terminate func(ctx context.Context) error

    Terminate terminates the service, returning an error if it fails.

type SharedState

Source: shared_state.go:19

type SharedState struct {
	// contains filtered or unexported fields
}

func (s *SharedState) Close() error

Source: shared_state.go:267

func (s *SharedState) Delete(key string) error

Source: shared_state.go:216

func (s *SharedState) DeleteWithContext(ctx context.Context, key string) error

Source: shared_state.go:220

func (s *SharedState) Get(key string) ([]byte, bool, error)

Source: shared_state.go:93

func (s *SharedState) GetCBOR(key string, out any) ([]byte, bool, error)

Source: shared_state.go:180

func (s *SharedState) GetCBORWithContext(ctx context.Context, key string, out any) ([]byte, bool, error)

Source: shared_state.go:184

func (s *SharedState) GetJSON(key string, out any) ([]byte, bool, error)

Source: shared_state.go:132

func (s *SharedState) GetJSONWithContext(ctx context.Context, key string, out any) ([]byte, bool, error)

Source: shared_state.go:136

func (s *SharedState) GetMsgPack(key string, out any) ([]byte, bool, error)

Source: shared_state.go:156

func (s *SharedState) GetMsgPackWithContext(ctx context.Context, key string, out any) ([]byte, bool, error)

Source: shared_state.go:160

func (s *SharedState) GetWithContext(ctx context.Context, key string) ([]byte, bool, error)

Source: shared_state.go:99

GetWithContext returns a defensive copy of the stored bytes so callers can safely mutate the returned slice without changing the shared value.

func (s *SharedState) GetXML(key string, out any) ([]byte, bool, error)

Source: shared_state.go:204

func (s *SharedState) GetXMLWithContext(ctx context.Context, key string, out any) ([]byte, bool, error)

Source: shared_state.go:208

func (s *SharedState) Has(key string) (bool, error)

Source: shared_state.go:233

func (s *SharedState) HasWithContext(ctx context.Context, key string) (bool, error)

Source: shared_state.go:237

func (s *SharedState) Reset() error

Source: shared_state.go:255

func (s *SharedState) ResetWithContext(ctx context.Context) error

Source: shared_state.go:259

func (s *SharedState) Set(key string, val []byte, ttl time.Duration) error

Source: shared_state.go:76

func (s *SharedState) SetCBOR(key string, v any, ttl time.Duration) error

Source: shared_state.go:168

func (s *SharedState) SetCBORWithContext(ctx context.Context, key string, v any, ttl time.Duration) error

Source: shared_state.go:172

func (s *SharedState) SetJSON(key string, v any, ttl time.Duration) error

Source: shared_state.go:120

func (s *SharedState) SetJSONWithContext(ctx context.Context, key string, v any, ttl time.Duration) error

Source: shared_state.go:124

func (s *SharedState) SetMsgPack(key string, v any, ttl time.Duration) error

Source: shared_state.go:144

func (s *SharedState) SetMsgPackWithContext(ctx context.Context, key string, v any, ttl time.Duration) error

Source: shared_state.go:148

func (s *SharedState) SetWithContext(ctx context.Context, key string, val []byte, ttl time.Duration) error

Source: shared_state.go:80

func (s *SharedState) SetXML(key string, v any, ttl time.Duration) error

Source: shared_state.go:192

func (s *SharedState) SetXMLWithContext(ctx context.Context, key string, v any, ttl time.Duration) error

Source: shared_state.go:196

type StartupMessageLevel

Source: hooks.go:53

type StartupMessageLevel int

type State

Source: state.go:21

State is a key-value store for Fiber's app in order to be used as a global storage for the app's dependencies. It's a thread-safe implementation of a map[string]any, using sync.Map.

type State struct {
	// contains filtered or unexported fields
}

func (s *State) Delete(key string)

Source: state.go:64

Delete removes a key-value pair from the State.

func (s *State) Get(key string) (any, bool)

Source: state.go:43

Get retrieves a value from the State.

func (s *State) GetBool(key string) (value, ok bool)

Source: state.go:152

GetBool retrieves a boolean value from the State. It returns the bool and a boolean indicating successful type assertion.

func (s *State) GetComplex128(key string) (complex128, bool)

Source: state.go:236

GetComplex128 retrieves a complex128 value from the State. It returns the complex128 and a boolean indicating successful type assertion.

func (s *State) GetComplex64(key string) (complex64, bool)

Source: state.go:230

GetComplex64 retrieves a complex64 value from the State. It returns the complex64 and a boolean indicating successful type assertion.

func (s *State) GetFloat32(key string) (float32, bool)

Source: state.go:224

GetFloat32 retrieves a float32 value from the State. It returns the float32 and a boolean indicating successful type assertion.

func (s *State) GetFloat64(key string) (float64, bool)

Source: state.go:158

GetFloat64 retrieves a float64 value from the State. It returns the float64 and a boolean indicating successful type assertion.

func (s *State) GetInt(key string) (int, bool)

Source: state.go:146

GetInt retrieves an integer value from the State. It returns the int and a boolean indicating successful type assertion.

func (s *State) GetInt16(key string) (int16, bool)

Source: state.go:176

GetInt16 retrieves an int16 value from the State. It returns the int16 and a boolean indicating successful type assertion.

func (s *State) GetInt32(key string) (int32, bool)

Source: state.go:182

GetInt32 retrieves an int32 value from the State. It returns the int32 and a boolean indicating successful type assertion.

func (s *State) GetInt64(key string) (int64, bool)

Source: state.go:188

GetInt64 retrieves an int64 value from the State. It returns the int64 and a boolean indicating successful type assertion.

func (s *State) GetInt8(key string) (int8, bool)

Source: state.go:170

GetInt8 retrieves an int8 value from the State. It returns the int8 and a boolean indicating successful type assertion.

func (s *State) GetString(key string) (string, bool)

Source: state.go:140

GetString retrieves a string value from the State. It returns the string and a boolean indicating successful type assertion.

func (s *State) GetUint(key string) (uint, bool)

Source: state.go:164

GetUint retrieves a uint value from the State. It returns the uint and a boolean indicating successful type assertion.

func (s *State) GetUint16(key string) (uint16, bool)

Source: state.go:200

GetUint16 retrieves a uint16 value from the State. It returns the uint16 and a boolean indicating successful type assertion.

func (s *State) GetUint32(key string) (uint32, bool)

Source: state.go:206

GetUint32 retrieves a uint32 value from the State. It returns the uint32 and a boolean indicating successful type assertion.

func (s *State) GetUint64(key string) (uint64, bool)

Source: state.go:212

GetUint64 retrieves a uint64 value from the State. It returns the uint64 and a boolean indicating successful type assertion.

func (s *State) GetUint8(key string) (uint8, bool)

Source: state.go:194

GetUint8 retrieves a uint8 value from the State. It returns the uint8 and a boolean indicating successful type assertion.

func (s *State) GetUintptr(key string) (uintptr, bool)

Source: state.go:218

GetUintptr retrieves a uintptr value from the State. It returns the uintptr and a boolean indicating successful type assertion.

func (s *State) Has(key string) bool

Source: state.go:58

Has checks if a key is present in the State. It returns a boolean indicating if the key is present.

func (s *State) Keys() []string

Source: state.go:74

Keys returns a slice containing all keys present in the State.

func (s *State) Len() int

Source: state.go:91

Len returns the number of keys in the State.

func (s *State) MustGet(key string) any

Source: state.go:48

MustGet retrieves a value from the State and panics if the key is not found.

func (s *State) Reset()

Source: state.go:69

Reset resets the State by removing all keys.

func (s *State) Services() map[string]Service

Source: state.go:338

Services returns a map containing all services present in the State. The key is the hash of the service String() value and the value is the service itself.

func (s *State) ServicesLen() int

Source: state.go:350

ServicesLen returns the number of keys for services in the State.

func (s *State) Set(key string, value any)

Source: state.go:38

Set sets a key-value pair in the State.

type Storage

Source: storage_interface.go:10

Storage interface for communicating with different database/key-value providers

type Storage interface {
	// GetWithContext gets the value for the given key with a context.
	// `nil, nil` is returned when the key does not exist
	GetWithContext(ctx context.Context, key string) ([]byte, error)

	// Get gets the value for the given key.
	// `nil, nil` is returned when the key does not exist
	Get(key string) ([]byte, error)

	// SetWithContext stores the given value for the given key
	// with an expiration value, 0 means no expiration.
	// Empty key or value will be ignored without an error.
	SetWithContext(ctx context.Context, key string, val []byte, exp time.Duration) error

	// Set stores the given value for the given key along
	// with an expiration value, 0 means no expiration.
	// Empty key or value will be ignored without an error.
	Set(key string, val []byte, exp time.Duration) error

	// DeleteWithContext deletes the value for the given key with a context.
	// It returns no error if the storage does not contain the key,
	DeleteWithContext(ctx context.Context, key string) error

	// Delete deletes the value for the given key.
	// It returns no error if the storage does not contain the key,
	Delete(key string) error

	// ResetWithContext resets the storage and deletes all keys with a context.
	ResetWithContext(ctx context.Context) error

	// Reset resets the storage and delete all keys.
	Reset() error

	// Close closes the storage and will stop any running garbage
	// collectors and open connections.
	Close() error
}
Methods
  • GetWithContext func(ctx context.Context, key string) ([]byte, error)

    GetWithContext gets the value for the given key with a context. nil, nil is returned when the key does not exist

  • Get func(key string) ([]byte, error)

    Get gets the value for the given key. nil, nil is returned when the key does not exist

  • SetWithContext func(ctx context.Context, key string, val []byte, exp time.Duration) error

    SetWithContext stores the given value for the given key with an expiration value, 0 means no expiration. Empty key or value will be ignored without an error.

  • Set func(key string, val []byte, exp time.Duration) error

    Set stores the given value for the given key along with an expiration value, 0 means no expiration. Empty key or value will be ignored without an error.

  • DeleteWithContext func(ctx context.Context, key string) error

    DeleteWithContext deletes the value for the given key with a context. It returns no error if the storage does not contain the key,

  • Delete func(key string) error

    Delete deletes the value for the given key. It returns no error if the storage does not contain the key,

  • ResetWithContext func(ctx context.Context) error

    ResetWithContext resets the storage and deletes all keys with a context.

  • Reset func() error

    Reset resets the storage and delete all keys.

  • Close func() error

    Close closes the storage and will stop any running garbage collectors and open connections.

type StructValidator

Source: bind.go:26

StructValidator is an interface to register custom struct validator for binding.

type StructValidator interface {
	Validate(out any) error
}
Methods
  • Validate func(out any) error

type SyntaxError

Source: error.go:86

SyntaxError is a description of a JSON syntax error.

type SyntaxError = json.SyntaxError

type TLSHandler

Source: ctx.go:97

TLSHandler hosts the callback hooks Fiber invokes while negotiating TLS connections, including optional client certificate lookups.

It records the ClientHelloInfo of every connection, keyed by the connection, and releases it when the server reports the connection closed.

type TLSHandler struct {
	// contains filtered or unexported fields
}

func (t *TLSHandler) GetClientInfo(info *tls.ClientHelloInfo) (*tls.Certificate, error)

Source: ctx.go:106

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

type TestConfig

Source: app.go:1487

TestConfig is a struct holding Test settings

type TestConfig struct {
	// Timeout defines the maximum duration a
	// test can run before timing out.
	// Default: time.Second
	Timeout time.Duration

	// FailOnTimeout specifies whether the test
	// should return a timeout error if the HTTP response
	// exceeds the Timeout duration.
	// Default: true
	FailOnTimeout bool
}
Fields
  • Timeout time.Duration

    Timeout defines the maximum duration a test can run before timing out. Default: time.Second

  • FailOnTimeout bool

    FailOnTimeout specifies whether the test should return a timeout error if the HTTP response exceeds the Timeout duration. Default: true

type TrustProxyConfig

Source: app.go:620

TrustProxyConfig is a struct for configuring trusted proxies if Config.TrustProxy is true.

type TrustProxyConfig struct {

	// Proxies is a list of trusted proxy IP addresses or CIDR ranges.
	//
	// Default: []string
	Proxies []string `json:"proxies"`

	// LinkLocal enables trusting all link-local IP ranges (e.g., 169.254.0.0/16, fe80::/10).
	//
	// Default: false
	LinkLocal bool `json:"link_local"`

	// Loopback enables trusting all loopback IP ranges (e.g., 127.0.0.0/8, ::1/128).
	//
	// Default: false
	Loopback bool `json:"loopback"`

	// Private enables trusting all private IP ranges (e.g., 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, fc00::/7).
	//
	// Default: false
	Private bool `json:"private"`

	// UnixSocket enables trusting Unix domain socket connections.
	// When enabled, requests from Unix sockets are treated as trusted proxies.
	//
	// Default: false
	UnixSocket bool `json:"unix_socket"`
	// contains filtered or unexported fields
}
Fields
  • Proxies []string `json:"proxies"`

    Proxies is a list of trusted proxy IP addresses or CIDR ranges.

    Default: []string

  • LinkLocal bool `json:"link_local"`

    LinkLocal enables trusting all link-local IP ranges (e.g., 169.254.0.0/16, fe80::/10).

    Default: false

  • Loopback bool `json:"loopback"`

    Loopback enables trusting all loopback IP ranges (e.g., 127.0.0.0/8, ::1/128).

    Default: false

  • Private bool `json:"private"`

    Private enables trusting all private IP ranges (e.g., 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, fc00::/7).

    Default: false

  • UnixSocket bool `json:"unix_socket"`

    UnixSocket enables trusting Unix domain socket connections. When enabled, requests from Unix sockets are treated as trusted proxies.

    Default: false

type TypeConstraint

Source: path.go:93

TypeConstraint parameter constraint types.

Deprecated: Use the ConstraintHandler interface instead. Retained for backward compatibility with external code that reads or compares IDs.

type TypeConstraint uint16

type UnknownKeyError

Source: error.go:69

UnknownKeyError error exposes the internal schema.UnknownKeyError for public use.

type UnknownKeyError = schema.UnknownKeyError

type UnmarshalTypeError

Source: error.go:90

UnmarshalTypeError describes a JSON value that was not appropriate for a value of a specific Go type.

type UnmarshalTypeError = json.UnmarshalTypeError

type UnsupportedTypeError

Source: error.go:94

UnsupportedTypeError is returned by Marshal when attempting to encode an unsupported value type.

type UnsupportedTypeError = json.UnsupportedTypeError

type UnsupportedValueError

Source: error.go:97

UnsupportedValueError exposes json.UnsupportedValueError to describe unsupported values encountered during encoding.

type UnsupportedValueError = json.UnsupportedValueError

type Views

Source: ctx.go:195

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
}
Methods
  • Load func() error
  • Render func(out io.Writer, name string, binding any, layout ...string) error