Documentation
¶
Overview ¶
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.
Index ¶
- Constants
- Variables
- func Convert[T any](value string, converter func(string) (T, error), defaultValue ...T) (T, error)
- func DefaultErrorHandler(c Ctx, err error) error
- func GetReqHeader[V GenericType](c Ctx, key string, defaultValue ...V) V
- func GetService[T Service](s *State, key string) (T, bool)
- func GetState[T any](s *State, key string) (T, bool)
- func GetStateWithDefault[T any](s *State, key string, defaultVal T) T
- func GetTrimmedParam(param string) string
- func IsChild() bool
- func IsMethodIdempotent(m string) bool
- func IsMethodSafe(m string) bool
- func Locals[V any](c Ctx, key any, value ...V) V
- func MustGetService[T Service](s *State, key string) T
- func MustGetState[T any](s *State, key string) T
- func Params[V GenericType](c Ctx, key string, defaultValue ...V) V
- func Query[V GenericType](c Ctx, key string, defaultValue ...V) V
- func ReleaseBind(b *Bind)
- func ReleaseRedirect(r *Redirect)
- func RemoveEscapeChar(word string) string
- func RemoveEscapeCharBytes(word []byte) []byte
- func RoutePatternMatch(path, pattern string, cfg ...Config) bool
- type App
- func (app *App) AcquireCtx(fctx *fasthttp.RequestCtx) CustomCtx
- func (app *App) Add(methods []string, path string, handler Handler, handlers ...Handler) Router
- func (app *App) All(path string, handler Handler, handlers ...Handler) Router
- func (app *App) Config() Config
- func (app *App) Connect(path string, handler Handler, handlers ...Handler) Router
- func (app *App) Delete(path string, handler Handler, handlers ...Handler) Router
- func (app *App) ErrorHandler(ctx Ctx, err error) error
- func (app *App) Get(path string, handler Handler, handlers ...Handler) Router
- func (app *App) GetBytes(b []byte) []byte
- func (app *App) GetRoute(name string) Route
- func (app *App) GetRoutes(filterUseOption ...bool) []Route
- func (app *App) GetString(s string) string
- func (app *App) Group(prefix string, handlers ...Handler) Router
- func (app *App) Handler() fasthttp.RequestHandler
- func (app *App) HandlersCount() uint32
- func (app *App) Head(path string, handler Handler, handlers ...Handler) Router
- func (app *App) Hooks() *Hooks
- func (app *App) Listen(addr string, config ...ListenConfig) error
- func (app *App) Listener(ln net.Listener, config ...ListenConfig) error
- func (app *App) MountPath() string
- func (app *App) Name(name string) Router
- func (app *App) Options(path string, handler Handler, handlers ...Handler) Router
- func (app *App) Patch(path string, handler Handler, handlers ...Handler) Router
- func (app *App) Post(path string, handler Handler, handlers ...Handler) Router
- func (app *App) Put(path string, handler Handler, handlers ...Handler) Router
- func (app *App) RebuildTree() *App
- func (app *App) RegisterCustomBinder(customBinder CustomBinder)
- func (app *App) RegisterCustomConstraint(constraint CustomConstraint)
- func (app *App) ReleaseCtx(c CustomCtx)
- func (app *App) RemoveRoute(path string, methods ...string)
- func (app *App) RemoveRouteByName(name string, methods ...string)
- func (app *App) RemoveRouteFunc(matchFunc func(r *Route) bool, methods ...string)
- func (app *App) Route(prefix string, fn func(router Router), name ...string) Router
- func (app *App) RouteChain(path string) Register
- func (app *App) Server() *fasthttp.Server
- func (app *App) SetTLSHandler(tlsHandler *TLSHandler)
- func (app *App) Shutdown() error
- func (app *App) ShutdownWithContext(ctx context.Context) error
- func (app *App) ShutdownWithTimeout(timeout time.Duration) error
- func (app *App) Stack() [][]*Route
- func (app *App) State() *State
- func (app *App) Test(req *http.Request, config ...TestConfig) (*http.Response, error)
- func (app *App) Trace(path string, handler Handler, handlers ...Handler) Router
- func (app *App) Use(args ...any) Router
- type Bind
- func (b *Bind) All(out any) error
- func (b *Bind) Body(out any) error
- func (b *Bind) CBOR(out any) error
- func (b *Bind) Cookie(out any) error
- func (b *Bind) Custom(name string, dest any) error
- func (b *Bind) Form(out any) error
- func (b *Bind) Header(out any) error
- func (b *Bind) JSON(out any) error
- func (b *Bind) MsgPack(out any) error
- func (b *Bind) Query(out any) error
- func (b *Bind) RespHeader(out any) error
- func (b *Bind) URI(out any) error
- func (b *Bind) WithAutoHandling() *Bind
- func (b *Bind) WithoutAutoHandling() *Bind
- func (b *Bind) XML(out any) error
- type Colors
- type Config
- type Constraint
- type ConversionError
- type Cookie
- type Ctx
- type CustomBinder
- type CustomConstraint
- type CustomCtx
- type DefaultCtx
- func (c *DefaultCtx) App() *App
- func (c *DefaultCtx) BaseURL() string
- func (c *DefaultCtx) Bind() *Bind
- func (c *DefaultCtx) ClientHelloInfo() *tls.ClientHelloInfo
- func (c *DefaultCtx) Context() context.Context
- func (*DefaultCtx) Deadline() (time.Time, bool)
- func (*DefaultCtx) Done() <-chan struct{}
- func (*DefaultCtx) Err() error
- func (c *DefaultCtx) Get(key string, defaultValue ...string) string
- func (c *DefaultCtx) GetHeaders() map[string][]string
- func (c *DefaultCtx) GetReqHeaders() map[string][]string
- func (c *DefaultCtx) GetRespHeader(key string, defaultValue ...string) string
- func (c *DefaultCtx) GetRespHeaders() map[string][]string
- func (c *DefaultCtx) HasBody() bool
- func (c *DefaultCtx) IsMiddleware() bool
- func (c *DefaultCtx) IsPreflight() bool
- func (c *DefaultCtx) IsWebSocket() bool
- func (c *DefaultCtx) Matched() bool
- func (c *DefaultCtx) Next() error
- func (c *DefaultCtx) OriginalURL() string
- func (c *DefaultCtx) Path(override ...string) string
- func (c *DefaultCtx) Redirect() *Redirect
- func (c *DefaultCtx) Req() Req
- func (c *DefaultCtx) Request() *fasthttp.Request
- func (c *DefaultCtx) RequestCtx() *fasthttp.RequestCtx
- func (c *DefaultCtx) Res() Res
- func (c *DefaultCtx) Reset(fctx *fasthttp.RequestCtx)
- func (c *DefaultCtx) Response() *fasthttp.Response
- func (c *DefaultCtx) RestartRouting() error
- func (c *DefaultCtx) Route() *Route
- func (*DefaultCtx) SaveFile(fileheader *multipart.FileHeader, path string) error
- func (c *DefaultCtx) SaveFileToStorage(fileheader *multipart.FileHeader, path string, storage Storage) error
- func (c *DefaultCtx) Secure() bool
- func (c *DefaultCtx) SetContext(ctx context.Context)
- func (c *DefaultCtx) Status(status int) Ctx
- func (c *DefaultCtx) String() string
- func (c *DefaultCtx) Value(key any) any
- func (c *DefaultCtx) ViewBind(vars Map) error
- func (c *DefaultCtx) XHR() bool
- type DefaultReq
- func (r *DefaultReq) Accepts(offers ...string) string
- func (r *DefaultReq) AcceptsCharsets(offers ...string) string
- func (r *DefaultReq) AcceptsEncodings(offers ...string) string
- func (r *DefaultReq) AcceptsLanguages(offers ...string) string
- func (r *DefaultReq) AcceptsLanguagesExtended(offers ...string) string
- func (r *DefaultReq) App() *App
- func (r *DefaultReq) BaseURL() string
- func (r *DefaultReq) Body() []byte
- func (r *DefaultReq) BodyRaw() []byte
- func (r *DefaultReq) Cookies(key string, defaultValue ...string) string
- func (r *DefaultReq) FormFile(key string) (*multipart.FileHeader, error)
- func (r *DefaultReq) FormValue(key string, defaultValue ...string) string
- func (r *DefaultReq) Fresh() bool
- func (r *DefaultReq) Get(key string, defaultValue ...string) string
- func (r *DefaultReq) GetHeaders() map[string][]string
- func (r *DefaultReq) Host() string
- func (r *DefaultReq) Hostname() string
- func (r *DefaultReq) IP() string
- func (r *DefaultReq) IPs() []string
- func (r *DefaultReq) Is(extension string) bool
- func (r *DefaultReq) IsFromLocal() bool
- func (r *DefaultReq) IsProxyTrusted() bool
- func (r *DefaultReq) Locals(key any, value ...any) any
- func (r *DefaultReq) Method(override ...string) string
- func (r *DefaultReq) MultipartForm() (*multipart.Form, error)
- func (r *DefaultReq) OriginalURL() string
- func (r *DefaultReq) Params(key string, defaultValue ...string) string
- func (r *DefaultReq) Port() string
- func (r *DefaultReq) Protocol() string
- func (r *DefaultReq) Queries() map[string]string
- func (r *DefaultReq) Query(key string, defaultValue ...string) string
- func (r *DefaultReq) Range(size int) (Range, error)
- func (r *DefaultReq) Request() *fasthttp.Request
- func (r *DefaultReq) RequestCtx() *fasthttp.RequestCtx
- func (r *DefaultReq) Route() *Route
- func (r *DefaultReq) Scheme() string
- func (r *DefaultReq) Stale() bool
- func (r *DefaultReq) Subdomains(offset ...int) []string
- type DefaultRes
- func (r *DefaultRes) App() *App
- func (r *DefaultRes) Append(field string, values ...string)
- func (r *DefaultRes) Attachment(filename ...string)
- func (r *DefaultRes) AutoFormat(body any) error
- func (r *DefaultRes) CBOR(data any, ctype ...string) error
- func (r *DefaultRes) ClearCookie(key ...string)
- func (r *DefaultRes) Cookie(cookie *Cookie)
- func (r *DefaultRes) Download(file string, filename ...string) error
- func (r *DefaultRes) Drop() error
- func (r *DefaultRes) End() error
- func (r *DefaultRes) Format(handlers ...ResFmt) error
- func (r *DefaultRes) Get(key string, defaultValue ...string) string
- func (r *DefaultRes) GetHeaders() map[string][]string
- func (r *DefaultRes) GetRouteURL(routeName string, params Map) (string, error)
- func (r *DefaultRes) JSON(data any, ctype ...string) error
- func (r *DefaultRes) JSONP(data any, callback ...string) error
- func (r *DefaultRes) Links(link ...string)
- func (r *DefaultRes) Location(path string)
- func (r *DefaultRes) MsgPack(data any, ctype ...string) error
- func (r *DefaultRes) OriginalURL() string
- func (r *DefaultRes) Redirect() *Redirect
- func (r *DefaultRes) Render(name string, bind any, layouts ...string) error
- func (r *DefaultRes) RequestCtx() *fasthttp.RequestCtx
- func (r *DefaultRes) Response() *fasthttp.Response
- func (r *DefaultRes) Send(body []byte) error
- func (r *DefaultRes) SendEarlyHints(hints []string) error
- func (r *DefaultRes) SendFile(file string, config ...SendFile) error
- func (r *DefaultRes) SendStatus(status int) error
- func (r *DefaultRes) SendStream(stream io.Reader, size ...int) error
- func (r *DefaultRes) SendStreamWriter(streamWriter func(*bufio.Writer)) error
- func (r *DefaultRes) SendString(body string) error
- func (r *DefaultRes) Set(key, val string)
- func (r *DefaultRes) Status(status int) Ctx
- func (r *DefaultRes) Type(extension string, charset ...string) Ctx
- func (r *DefaultRes) Vary(fields ...string)
- func (r *DefaultRes) ViewBind(vars Map) error
- func (r *DefaultRes) Write(p []byte) (int, error)
- func (r *DefaultRes) WriteString(s string) (int, error)
- func (r *DefaultRes) Writef(f string, a ...any) (int, error)
- func (r *DefaultRes) XML(data any) error
- type EmptyFieldError
- type Error
- type ErrorHandler
- type FlashMessage
- type GenericType
- type GenericTypeFloat
- type GenericTypeInteger
- type GenericTypeIntegerSigned
- type GenericTypeIntegerUnsigned
- type Group
- func (grp *Group) Add(methods []string, path string, handler Handler, handlers ...Handler) Router
- func (grp *Group) All(path string, handler Handler, handlers ...Handler) Router
- func (grp *Group) Connect(path string, handler Handler, handlers ...Handler) Router
- func (grp *Group) Delete(path string, handler Handler, handlers ...Handler) Router
- func (grp *Group) Get(path string, handler Handler, handlers ...Handler) Router
- func (grp *Group) Group(prefix string, handlers ...Handler) Router
- func (grp *Group) Head(path string, handler Handler, handlers ...Handler) Router
- func (grp *Group) Name(name string) Router
- func (grp *Group) Options(path string, handler Handler, handlers ...Handler) Router
- func (grp *Group) Patch(path string, handler Handler, handlers ...Handler) Router
- func (grp *Group) Post(path string, handler Handler, handlers ...Handler) Router
- func (grp *Group) Put(path string, handler Handler, handlers ...Handler) Router
- func (grp *Group) Route(prefix string, fn func(router Router), name ...string) Router
- func (grp *Group) RouteChain(path string) Register
- func (grp *Group) Trace(path string, handler Handler, handlers ...Handler) Router
- func (grp *Group) Use(args ...any) Router
- type Handler
- type Hooks
- func (h *Hooks) OnFork(handler ...OnForkHandler)
- func (h *Hooks) OnGroup(handler ...OnGroupHandler)
- func (h *Hooks) OnGroupName(handler ...OnGroupNameHandler)
- func (h *Hooks) OnListen(handler ...OnListenHandler)
- func (h *Hooks) OnMount(handler ...OnMountHandler)
- func (h *Hooks) OnName(handler ...OnNameHandler)
- func (h *Hooks) OnPostShutdown(handler ...OnPostShutdownHandler)
- func (h *Hooks) OnPreShutdown(handler ...OnPreShutdownHandler)
- func (h *Hooks) OnRoute(handler ...OnRouteHandler)
- type InvalidUnmarshalError
- type ListenConfig
- type ListenData
- type Map
- type MarshalerError
- type MultiError
- type OldInputData
- type OnForkHandler
- type OnGroupHandler
- type OnGroupNameHandler
- type OnListenHandler
- type OnMountHandler
- type OnNameHandler
- type OnPostShutdownHandler
- type OnPreShutdownHandler
- type OnRouteHandler
- type Range
- type RangeSet
- type Redirect
- func (r *Redirect) Back(fallback ...string) error
- func (r *Redirect) Message(key string) FlashMessage
- func (r *Redirect) Messages() []FlashMessage
- func (r *Redirect) OldInput(key string) OldInputData
- func (r *Redirect) OldInputs() []OldInputData
- func (r *Redirect) Route(name string, config ...RedirectConfig) error
- func (r *Redirect) Status(code int) *Redirect
- func (r *Redirect) To(location string) error
- func (r *Redirect) With(key, value string, level ...uint8) *Redirect
- func (r *Redirect) WithInput() *Redirect
- type RedirectConfig
- type Register
- type Registering
- func (r *Registering) Add(methods []string, handler Handler, handlers ...Handler) Register
- func (r *Registering) All(handler Handler, handlers ...Handler) Register
- func (r *Registering) Connect(handler Handler, handlers ...Handler) Register
- func (r *Registering) Delete(handler Handler, handlers ...Handler) Register
- func (r *Registering) Get(handler Handler, handlers ...Handler) Register
- func (r *Registering) Head(handler Handler, handlers ...Handler) Register
- func (r *Registering) Options(handler Handler, handlers ...Handler) Register
- func (r *Registering) Patch(handler Handler, handlers ...Handler) Register
- func (r *Registering) Post(handler Handler, handlers ...Handler) Register
- func (r *Registering) Put(handler Handler, handlers ...Handler) Register
- func (r *Registering) RouteChain(path string) Register
- func (r *Registering) Trace(handler Handler, handlers ...Handler) Register
- type Req
- type Res
- type ResFmt
- type Route
- type RouteMessage
- type Router
- type SendFile
- type Service
- type State
- func (s *State) Delete(key string)
- func (s *State) Get(key string) (any, bool)
- func (s *State) GetBool(key string) (value, ok bool)
- func (s *State) GetComplex128(key string) (complex128, bool)
- func (s *State) GetComplex64(key string) (complex64, bool)
- func (s *State) GetFloat32(key string) (float32, bool)
- func (s *State) GetFloat64(key string) (float64, bool)
- func (s *State) GetInt(key string) (int, bool)
- func (s *State) GetInt16(key string) (int16, bool)
- func (s *State) GetInt32(key string) (int32, bool)
- func (s *State) GetInt64(key string) (int64, bool)
- func (s *State) GetInt8(key string) (int8, bool)
- func (s *State) GetString(key string) (string, bool)
- func (s *State) GetUint(key string) (uint, bool)
- func (s *State) GetUint16(key string) (uint16, bool)
- func (s *State) GetUint32(key string) (uint32, bool)
- func (s *State) GetUint64(key string) (uint64, bool)
- func (s *State) GetUint8(key string) (uint8, bool)
- func (s *State) GetUintptr(key string) (uintptr, bool)
- func (s *State) Has(key string) bool
- func (s *State) Keys() []string
- func (s *State) Len() int
- func (s *State) MustGet(key string) any
- func (s *State) Reset()
- func (s *State) Services() map[string]Service
- func (s *State) ServicesLen() int
- func (s *State) Set(key string, value any)
- type Storage
- type StructValidator
- type SyntaxError
- type TLSHandler
- type TestConfig
- type TrustProxyConfig
- type TypeConstraint
- type UnknownKeyError
- type UnmarshalTypeError
- type UnsupportedTypeError
- type UnsupportedValueError
- type Views
Constants ¶
const ( DefaultBodyLimit = 4 * 1024 * 1024 DefaultConcurrency = 256 * 1024 DefaultReadBufferSize = 4096 DefaultWriteBufferSize = 4096 )
Default Config values
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 )
HTTP methods were copied from net/http.
const ( MIMETextXML = "text/xml" MIMETextHTML = "text/html" MIMETextPlain = "text/plain" MIMETextJavaScript = "text/javascript" MIMETextCSS = "text/css" 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" )
MIME types that are commonly used
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 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 StatusInternalServerError = 500 // RFC 9110, 15.6.1 StatusNotImplemented = 501 // RFC 9110, 15.6.2 StatusBadGateway = 502 // RFC 9110, 15.6.3 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 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
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" 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" 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" HeaderIndex = "Index" HeaderLargeAllocation = "Large-Allocation" HeaderLink = "Link" HeaderPushPolicy = "Push-Policy" HeaderRetryAfter = "Retry-After" HeaderServerTiming = "Server-Timing" HeaderSignature = "Signature" HeaderSignedHeaders = "Signed-Headers" HeaderSourceMap = "SourceMap" HeaderUpgrade = "Upgrade" HeaderXDNSPrefetchControl = "X-DNS-Prefetch-Control" HeaderXPingback = "X-Pingback" HeaderXRequestID = "X-Request-ID" HeaderXRequestedWith = "X-Requested-With" HeaderXRobotsTag = "X-Robots-Tag" HeaderXUACompatible = "X-UA-Compatible" HeaderAccessControlAllowPrivateNetwork = "Access-Control-Allow-Private-Network" HeaderAccessControlRequestPrivateNetwork = "Access-Control-Request-Private-Network" )
HTTP Headers were copied from net/http.
const ( NetworkTCP = "tcp" NetworkTCP4 = "tcp4" NetworkTCP6 = "tcp6" NetworkUnix = "unix" )
Network types that are commonly used
const ( StrGzip = "gzip" StrCompress = "compress" StrIdentity = "identity" StrBr = "br" StrDeflate = "deflate" StrBrotli = "brotli" StrZstd = "zstd" )
Compression types
const ( CookieSameSiteDisabled = "disabled" // not in RFC, just control "SameSite" attribute will not be set. CookieSameSiteLaxMode = "Lax" CookieSameSiteStrictMode = "Strict" CookieSameSiteNoneMode = "None" )
Cookie SameSite https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-03#section-4.1.2.7
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" )
Route Constraints
const ( FlashCookieName = "fiber_flash" OldInputDataPrefix = "old_input_data_" CookieDataSeparator = "," CookieDataAssigner = ":" )
Cookie name to send flash messages when to use redirection.
const Version = "3.0.0-rc.2"
Version of current fiber package
Variables ¶
var ( ErrBadRequest = NewError(StatusBadRequest) // 400 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 ErrInternalServerError = NewError(StatusInternalServerError) // 500 ErrNotImplemented = NewError(StatusNotImplemented) // 501 ErrBadGateway = NewError(StatusBadGateway) // 502 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 )
Errors
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") )
General errors
var ( ErrRangeMalformed = errors.New("range: malformed range header string") ErrRangeUnsatisfiable = errors.New("range: unsatisfiable range") )
Range errors
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",
}
DefaultColors Default color codes
var DefaultMethods = []string{ // contains filtered or unexported fields }
HTTP methods enabled by default
var DefaultTrustProxyConfig = TrustProxyConfig{}
Default TrustProxyConfig
var ErrCustomBinderNotFound = errors.New("binder: custom binder not found, please be sure to enter the right name")
Binder errors
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") )
Format errors
var (
ErrRedirectBackNoFallback = NewError(StatusInternalServerError, "Referer not found, you have to enter fallback URL for redirection.")
)
Fiber redirection errors
var ErrTestGotEmptyResponse = errors.New("test: got empty response")
Functions ¶
func Convert ¶
Convert a string value to a specified type, handling errors and optional default values.
func DefaultErrorHandler ¶
DefaultErrorHandler that process return errors from handlers
func GetReqHeader ¶
func GetReqHeader[V GenericType](c Ctx, key string, defaultValue ...V) V
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 ¶
GetService returns a service present in the application's State.
func GetState ¶
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 ¶
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 ¶
GetTrimmedParam trims the ':' & '?' from a string
func IsMethodIdempotent ¶
IsMethodIdempotent reports whether the HTTP method is considered idempotent. See https://datatracker.ietf.org/doc/html/rfc9110#section-9.2.2
func IsMethodSafe ¶
IsMethodSafe reports whether the HTTP method is considered safe. See https://datatracker.ietf.org/doc/html/rfc9110#section-9.2.1
func Locals ¶
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 ¶
MustGetService returns a service present in the application's State. It panics if the service is not found.
func MustGetState ¶
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 Params ¶
func Params[V GenericType](c Ctx, key string, defaultValue ...V) V
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 ¶
func Query[V GenericType](c Ctx, key string, defaultValue ...V) V
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 in case the query parameter is not found or cannot be parsed. The function performs the following steps:
- Type-asserts the context object to *DefaultCtx.
- Retrieves the raw query parameter value from the request's URI.
- 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.
- 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 ReleaseRedirect ¶
func ReleaseRedirect(r *Redirect)
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 ¶
RemoveEscapeChar removes escape characters
func RemoveEscapeCharBytes ¶
RemoveEscapeCharBytes removes escape characters
func RoutePatternMatch ¶
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.
Types ¶
type App ¶
type App struct {
// contains filtered or unexported fields
}
App denotes the Fiber application.
func New ¶
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{
Prefork: true,
ServerHeader: "Fiber",
})
func NewWithCustomCtx ¶
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 (*App) AcquireCtx ¶
func (app *App) AcquireCtx(fctx *fasthttp.RequestCtx) CustomCtx
AcquireCtx retrieves a new Ctx from the pool.
func (*App) Connect ¶
Connect registers a route for CONNECT methods that establishes a tunnel to the server identified by the target resource.
func (*App) Delete ¶
Delete registers a route for DELETE methods that deletes the specified resource.
func (*App) ErrorHandler ¶
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) Get ¶
Get registers a route for GET methods that requests a representation of the specified resource. Requests using GET should only retrieve data.
func (*App) GetBytes ¶
GetBytes returns b unchanged when Immutable is off or b is read-only (rodata). Otherwise it returns a detached copy.
func (*App) GetRoutes ¶
GetRoutes Get all routes. When filterUseOption equal to true, it will filter the routes registered by the middleware.
func (*App) GetString ¶
GetString returns s unchanged when Immutable is off or s is read-only (rodata). Otherwise it returns a detached copy (strings.Clone).
func (*App) Group ¶
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) Handler ¶
func (app *App) Handler() fasthttp.RequestHandler
Handler returns the server handler.
func (*App) HandlersCount ¶
HandlersCount returns the amount of registered handlers.
func (*App) Head ¶
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) Listen ¶
func (app *App) Listen(addr string, config ...ListenConfig) error
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) Listener ¶
func (app *App) Listener(ln net.Listener, config ...ListenConfig) error
Listener serves HTTP requests from the given listener. You should enter custom ListenConfig to customize startup. (prefork, startup message, graceful shutdown...)
func (*App) MountPath ¶
MountPath returns the route pattern where the current app instance was mounted as a sub-application.
func (*App) Options ¶
Options registers a route for OPTIONS methods that is used to describe the communication options for the target resource.
func (*App) Patch ¶
Patch registers a route for PATCH methods that is used to apply partial modifications to a resource.
func (*App) Post ¶
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) Put ¶
Put registers a route for PUT methods that replaces all current representations of the target resource with the request payload.
func (*App) RebuildTree ¶
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) RegisterCustomBinder ¶
func (app *App) RegisterCustomBinder(customBinder CustomBinder)
RegisterCustomBinder Allows to register custom binders to use as Bind().Custom("name"). They should be compatible with CustomBinder interface.
func (*App) RegisterCustomConstraint ¶
func (app *App) RegisterCustomConstraint(constraint CustomConstraint)
RegisterCustomConstraint allows to register custom constraint.
func (*App) ReleaseCtx ¶
ReleaseCtx releases the ctx back into the pool.
func (*App) RemoveRoute ¶
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) RemoveRouteByName ¶
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) RemoveRouteFunc ¶
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) Route ¶
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) RouteChain ¶
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) SetTLSHandler ¶
func (app *App) SetTLSHandler(tlsHandler *TLSHandler)
SetTLSHandler Can be used to set ClientHelloInfo when using TLS with Listener.
func (*App) Shutdown ¶
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) ShutdownWithContext ¶
ShutdownWithContext shuts down the server including by force if the context's deadline is exceeded.
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) ShutdownWithTimeout ¶
ShutdownWithTimeout gracefully shuts down the server without interrupting any active connections. However, if the timeout is exceeded, ShutdownWithTimeout will forcefully close any active connections. 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) State ¶
State returns the state struct to store global data in order to share it between handlers.
func (*App) Test ¶
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) Trace ¶
Trace registers a route for TRACE methods that performs a message loop-back test along the path to the target resource.
func (*App) Use ¶
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 ¶
type Bind struct {
// contains filtered or unexported fields
}
Bind provides helper methods for binding request data to Go values.
func (*Bind) All ¶
All binds values from URI params, the request body, the query string, headers, and cookies into the provided struct in precedence order.
func (*Bind) Body ¶
Body binds the request body into the struct, map[string]string and map[string][]string. It supports decoding the following content types based on the Content-Type header: application/json, application/xml, application/x-www-form-urlencoded, multipart/form-data If none of the content types above are matched, it'll take a look custom binders by checking the MIMETypes() method of custom binder. If there're no custom binder for mime type of body, it will return a ErrUnprocessableEntity error.
func (*Bind) Cookie ¶
Cookie binds the request cookie strings into the struct, map[string]string and map[string][]string. NOTE: If your cookie is like key=val1,val2; they'll be binded as an slice if your map is map[string][]string. Else, it'll use last element of cookie.
func (*Bind) Custom ¶
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 (*Bind) Form ¶
Form binds the form into the struct, map[string]string and map[string][]string. If Content-Type is "application/x-www-form-urlencoded" or "multipart/form-data", it will bind the form values.
Binding multipart files is not supported yet.
func (*Bind) Header ¶
Header binds the request header strings into the struct, map[string]string and map[string][]string.
func (*Bind) Query ¶
Query binds the query string into the struct, map[string]string and map[string][]string.
func (*Bind) RespHeader ¶
RespHeader binds the response header strings into the struct, map[string]string and map[string][]string.
func (*Bind) URI ¶
URI binds the route parameters into the struct, map[string]string and map[string][]string.
func (*Bind) WithAutoHandling ¶
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 (*Bind) WithoutAutoHandling ¶
WithoutAutoHandling If you want to handle binder errors manually, you can use `WithoutAutoHandling`. It's default behavior of binder.
type Colors ¶
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
}
Colors is a struct to define custom colors for Fiber app and middlewares.
type Config ¶
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.
//
// 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, 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"`
// When set to true, converts all encoded characters in the route back
// before setting the path for the context, so that the routing,
// the returning of the current url from the context `ctx.Path()`
// and the parameters `ctx.Params(%key%)` with decoded characters will work
//
// 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"`
// 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"`
// 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: 4096
ReadBufferSize int `json:"read_buffer_size"`
// Per-connection buffer size for responses' writing.
//
// Default: 4096
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 all non-GET requests if set to true.
// This option is useful as anti-DoS protection for servers
// accepting only GET requests. The request size is limited
// by ReadBufferSize if GETOnly is set.
//
// 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"`
// StreamRequestBody enables request body streaming,
// and calls the handler sooner when given body is
// larger than the current limit.
//
// 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.
//
// 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 only the first valid IP rather than just the raw header
// 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
}
Config is a struct holding the server settings.
type Constraint ¶
type Constraint struct {
RegexCompiler *regexp.Regexp
Name string
Data []string
ID TypeConstraint
// contains filtered or unexported fields
}
Constraint describes the validation rules that apply to a dynamic route segment when matching incoming requests.
func (*Constraint) CheckConstraint ¶
func (c *Constraint) CheckConstraint(param string) bool
CheckConstraint validates if a param matches the given constraint Returns true if the param passes the constraint check, false otherwise
type ConversionError ¶
type ConversionError = schema.ConversionError
ConversionError Conversion error exposes the internal schema.ConversionError for public use.
type Cookie ¶
type Cookie struct {
Expires time.Time `json:"expires"` // The expiration date of the cookie
Name string `json:"name"` // The name of the cookie
Value string `json:"value"` // The value of the cookie
Path string `json:"path"` // Specifies a URL path which is allowed to receive the cookie
Domain string `json:"domain"` // Specifies the domain which is allowed to receive the cookie
SameSite string `json:"same_site"` // Controls whether or not a cookie is sent with cross-site requests
MaxAge int `json:"max_age"` // The maximum age (in seconds) of the cookie
Secure bool `json:"secure"` // Indicates that the cookie should only be transmitted over a secure HTTPS connection
HTTPOnly bool `json:"http_only"` // Indicates that the cookie is accessible only through the HTTP protocol
Partitioned bool `json:"partitioned"` // Indicates if the cookie is stored in a partitioned cookie jar
SessionOnly bool `json:"session_only"` // Indicates if the cookie is a session-only cookie
}
Cookie defines the values used when configuring cookies emitted by DefaultRes.Cookie.
type Ctx ¶
type Ctx interface {
// App returns the *App reference to the instance of the Fiber application
App() *App
// BaseURL returns (protocol + host + base 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. Deadline returns ok==false when no deadline is
// set. Successive calls to Deadline return the same results.
//
// Due to current limitations in how fasthttp works, Deadline operates as a nop.
// See: https://github.com/valyala/fasthttp/issues/965#issuecomment-777268945
Deadline() (time.Time, bool)
// Done returns a channel that's closed when work done on behalf of this
// context should be canceled. Done may return nil if this context can
// never be canceled. Successive calls to Done return the same value.
// The close of the Done channel may happen asynchronously,
// after the cancel function returns.
//
// Due to current limitations in how fasthttp works, Done operates as a nop.
// See: https://github.com/valyala/fasthttp/issues/965#issuecomment-777268945
Done() <-chan struct{}
// Err mirrors context.Err, returning nil until cancellation and then the terminal error value.
//
// Due to current limitations in how fasthttp works, Err operates as a nop.
// See: https://github.com/valyala/fasthttp/issues/965#issuecomment-777268945
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
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
Response() *fasthttp.Response
// 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 return CHI from context
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
// Path returns the path part of the request URL.
// Optionally, you could override the path.
// Make copies or use the Immutable setting to use the value outside the Handler.
Path(override ...string) 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
// 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
// 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
// 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
// Secure returns whether a secure connection was established.
Secure() bool
// Status sets the HTTP status for the response.
// This method is chainable.
Status(status int) Ctx
// 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.
Value(key any) any
// 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
// Reset is a method to reset context fields by given request when to use server handlers.
Reset(fctx *fasthttp.RequestCtx)
// 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.
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
// 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
// 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
// FormFile returns the first file by key from a MultipartForm.
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.
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.
// 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
// Host contains the host derived from the X-Forwarded-Host or Host HTTP header.
// Returned value is only valid within the handler. Do not store any references.
// In a network context, `Host` refers to the combination of a hostname and potentially a port number used for connecting,
// while `Hostname` refers specifically to the name assigned to a device on a network, excluding any port information.
// Example: URL: https://example.com:8080 -> Host: example.com:8080
// Make copies or use the Immutable setting instead.
// Please use Config.TrustProxy to prevent header spoofing, in case when your app is behind the proxy.
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, in case when your app is behind the proxy.
Hostname() string
// Port returns the remote port of the request.
Port() string
// IP returns the remote IP address of the request.
// If ProxyHeader and IP Validation is configured, it will parse that header and return the first valid IP address.
// Please use Config.TrustProxy to prevent header spoofing, in case when your app is behind the proxy.
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
// 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.
Locals(key any, value ...any) 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
// MultipartForm parse form entries from binary.
// This returns a map[string][]string, so given a key the value will be a string slice.
MultipartForm() (*multipart.Form, error)
// 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, in case when your app is behind the 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 int) (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 true
// IsProxyTrusted can check remote ip by proxy ranges and ip map.
IsProxyTrusted() bool
// IsFromLocal will return true if request came from local.
IsFromLocal() 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.
Append(field string, values ...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.
Cookie(cookie *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.
// 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
// 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.
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.
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(name string, bind any, layouts ...string) error
// 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
// 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)
// 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.
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.
End() error
// contains filtered or unexported methods
}
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 CustomBinder ¶
CustomBinder An interface to register custom binders.
type CustomConstraint ¶
type CustomConstraint interface {
// Name returns the name of the constraint.
// This name is used in the constraint matching.
Name() string
// Execute executes the constraint.
// It returns true if the constraint is matched and right.
// param is the parameter value to check.
// args are the constraint arguments.
Execute(param string, args ...string) bool
}
CustomConstraint is an interface for custom constraints
type CustomCtx ¶
type CustomCtx interface {
Ctx
// Reset is a method to reset context fields by given request when to use server handlers.
Reset(fctx *fasthttp.RequestCtx)
// contains filtered or unexported methods
}
CustomCtx extends Ctx with the additional methods required by Fiber's internals and middleware helpers.
type DefaultCtx ¶
type DefaultCtx struct {
DefaultReq // Default request api
DefaultRes // Default response api
// contains filtered or unexported fields
}
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
func NewDefaultCtx ¶
func NewDefaultCtx(app *App) *DefaultCtx
NewDefaultCtx constructs the default context implementation bound to the provided application.
func (*DefaultCtx) App ¶
func (c *DefaultCtx) App() *App
App returns the *App reference to the instance of the Fiber application
func (*DefaultCtx) BaseURL ¶
func (c *DefaultCtx) BaseURL() string
BaseURL returns (protocol + host + base path).
func (*DefaultCtx) Bind ¶
func (c *DefaultCtx) Bind() *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
func (*DefaultCtx) ClientHelloInfo ¶
func (c *DefaultCtx) ClientHelloInfo() *tls.ClientHelloInfo
ClientHelloInfo return CHI from context
func (*DefaultCtx) Context ¶
func (c *DefaultCtx) Context() 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.
func (*DefaultCtx) Deadline ¶
func (*DefaultCtx) Deadline() (time.Time, bool)
Deadline returns the time when work done on behalf of this context should be canceled. Deadline returns ok==false when no deadline is set. Successive calls to Deadline return the same results.
Due to current limitations in how fasthttp works, Deadline operates as a nop. See: https://github.com/valyala/fasthttp/issues/965#issuecomment-777268945
func (*DefaultCtx) Done ¶
func (*DefaultCtx) Done() <-chan struct{}
Done returns a channel that's closed when work done on behalf of this context should be canceled. Done may return nil if this context can never be canceled. Successive calls to Done return the same value. The close of the Done channel may happen asynchronously, after the cancel function returns.
Due to current limitations in how fasthttp works, Done operates as a nop. See: https://github.com/valyala/fasthttp/issues/965#issuecomment-777268945
func (*DefaultCtx) Err ¶
func (*DefaultCtx) Err() error
Err mirrors context.Err, returning nil until cancellation and then the terminal error value.
Due to current limitations in how fasthttp works, Err operates as a nop. See: https://github.com/valyala/fasthttp/issues/965#issuecomment-777268945
func (*DefaultCtx) Get ¶
func (c *DefaultCtx) Get(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.
func (*DefaultCtx) GetHeaders ¶
func (c *DefaultCtx) GetHeaders() 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.
func (*DefaultCtx) GetReqHeaders ¶
func (c *DefaultCtx) GetReqHeaders() 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.
func (*DefaultCtx) GetRespHeader ¶
func (c *DefaultCtx) GetRespHeader(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.
func (*DefaultCtx) GetRespHeaders ¶
func (c *DefaultCtx) GetRespHeaders() 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.
func (*DefaultCtx) HasBody ¶
func (c *DefaultCtx) HasBody() bool
HasBody returns true if the request declares a body via Content-Length, Transfer-Encoding, or already buffered payload data.
func (*DefaultCtx) IsMiddleware ¶
func (c *DefaultCtx) IsMiddleware() bool
IsMiddleware returns true if the current request handler was registered as middleware.
func (*DefaultCtx) IsPreflight ¶
func (c *DefaultCtx) IsPreflight() bool
IsPreflight returns true if the request is a CORS preflight.
func (*DefaultCtx) IsWebSocket ¶
func (c *DefaultCtx) IsWebSocket() bool
IsWebSocket returns true if the request includes a WebSocket upgrade handshake.
func (*DefaultCtx) Matched ¶
func (c *DefaultCtx) Matched() bool
Matched returns true if the current request path was matched by the router.
func (*DefaultCtx) Next ¶
func (c *DefaultCtx) Next() error
Next executes the next method in the stack that matches the current route.
func (*DefaultCtx) OriginalURL ¶
func (c *DefaultCtx) OriginalURL() 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.
func (*DefaultCtx) Path ¶
func (c *DefaultCtx) Path(override ...string) string
Path returns the path part of the request URL. Optionally, you could override the path. Make copies or use the Immutable setting to use the value outside the Handler.
func (*DefaultCtx) Redirect ¶
func (c *DefaultCtx) Redirect() *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.
func (*DefaultCtx) Req ¶
func (c *DefaultCtx) Req() Req
Req returns a convenience type whose API is limited to operations on the incoming request.
func (*DefaultCtx) Request ¶
func (c *DefaultCtx) Request() *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
func (*DefaultCtx) RequestCtx ¶
func (c *DefaultCtx) RequestCtx() *fasthttp.RequestCtx
RequestCtx returns *fasthttp.RequestCtx that carries a deadline a cancellation signal, and other values across API boundaries.
func (*DefaultCtx) Res ¶
func (c *DefaultCtx) Res() Res
Res returns a convenience type whose API is limited to operations on the outgoing response.
func (*DefaultCtx) Reset ¶
func (c *DefaultCtx) Reset(fctx *fasthttp.RequestCtx)
Reset is a method to reset context fields by given request when to use server handlers.
func (*DefaultCtx) Response ¶
func (c *DefaultCtx) Response() *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
func (*DefaultCtx) RestartRouting ¶
func (c *DefaultCtx) RestartRouting() 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.
func (*DefaultCtx) Route ¶
func (c *DefaultCtx) Route() *Route
Route returns the matched Route struct.
func (*DefaultCtx) SaveFile ¶
func (*DefaultCtx) SaveFile(fileheader *multipart.FileHeader, path string) error
SaveFile saves any multipart file to disk.
func (*DefaultCtx) SaveFileToStorage ¶
func (c *DefaultCtx) SaveFileToStorage(fileheader *multipart.FileHeader, path string, storage Storage) error
SaveFileToStorage saves any multipart file to an external storage system.
func (*DefaultCtx) Secure ¶
func (c *DefaultCtx) Secure() bool
Secure returns whether a secure connection was established.
func (*DefaultCtx) SetContext ¶
func (c *DefaultCtx) SetContext(ctx context.Context)
SetContext sets a context implementation by user.
func (*DefaultCtx) Status ¶
func (c *DefaultCtx) Status(status int) Ctx
Status sets the HTTP status for the response. This method is chainable.
func (*DefaultCtx) String ¶
func (c *DefaultCtx) String() string
String returns unique string representation of the ctx.
The returned value may be useful for logging.
func (*DefaultCtx) Value ¶
func (c *DefaultCtx) Value(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.
func (*DefaultCtx) ViewBind ¶
func (c *DefaultCtx) ViewBind(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.
func (*DefaultCtx) XHR ¶
func (c *DefaultCtx) XHR() 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).
type DefaultReq ¶
type DefaultReq struct {
// contains filtered or unexported fields
}
DefaultReq is the default implementation of Req used by DefaultCtx.
func (*DefaultReq) Accepts ¶
func (r *DefaultReq) Accepts(offers ...string) string
Accepts checks if the specified extensions or content types are acceptable.
func (*DefaultReq) AcceptsCharsets ¶
func (r *DefaultReq) AcceptsCharsets(offers ...string) string
AcceptsCharsets checks if the specified charset is acceptable.
func (*DefaultReq) AcceptsEncodings ¶
func (r *DefaultReq) AcceptsEncodings(offers ...string) string
AcceptsEncodings checks if the specified encoding is acceptable.
func (*DefaultReq) AcceptsLanguages ¶
func (r *DefaultReq) AcceptsLanguages(offers ...string) string
AcceptsLanguages checks if the specified language is acceptable using RFC 4647 Basic Filtering.
func (*DefaultReq) AcceptsLanguagesExtended ¶
func (r *DefaultReq) AcceptsLanguagesExtended(offers ...string) string
AcceptsLanguagesExtended checks if the specified language is acceptable using RFC 4647 Extended Filtering.
func (*DefaultReq) App ¶
func (r *DefaultReq) App() *App
App returns the *App reference to the instance of the Fiber application
func (*DefaultReq) BaseURL ¶
func (r *DefaultReq) BaseURL() string
BaseURL returns (protocol + host + base path).
func (*DefaultReq) Body ¶
func (r *DefaultReq) Body() []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.
func (*DefaultReq) BodyRaw ¶
func (r *DefaultReq) BodyRaw() []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.
func (*DefaultReq) Cookies ¶
func (r *DefaultReq) Cookies(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.
func (*DefaultReq) FormFile ¶
func (r *DefaultReq) FormFile(key string) (*multipart.FileHeader, error)
FormFile returns the first file by key from a MultipartForm.
func (*DefaultReq) FormValue ¶
func (r *DefaultReq) FormValue(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.
func (*DefaultReq) Fresh ¶
func (r *DefaultReq) Fresh() 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. 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 (*DefaultReq) Get ¶
func (r *DefaultReq) Get(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.
func (*DefaultReq) GetHeaders ¶
func (r *DefaultReq) GetHeaders() 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.
func (*DefaultReq) Host ¶
func (r *DefaultReq) Host() 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, in case when your app is behind the proxy.
func (*DefaultReq) Hostname ¶
func (r *DefaultReq) Hostname() 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, in case when your app is behind the proxy.
func (*DefaultReq) IP ¶
func (r *DefaultReq) IP() string
IP returns the remote IP address of the request. If ProxyHeader and IP Validation is configured, it will parse that header and return the first valid IP address. Please use Config.TrustProxy to prevent header spoofing, in case when your app is behind the proxy.
func (*DefaultReq) IPs ¶
func (r *DefaultReq) IPs() []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.
func (*DefaultReq) Is ¶
func (r *DefaultReq) Is(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
func (*DefaultReq) IsFromLocal ¶
func (r *DefaultReq) IsFromLocal() bool
IsFromLocal will return true if request came from local.
func (*DefaultReq) IsProxyTrusted ¶
func (r *DefaultReq) IsProxyTrusted() bool
IsProxyTrusted checks trustworthiness of remote ip. If Config.TrustProxy false, it returns true IsProxyTrusted can check remote ip by proxy ranges and ip map.
func (*DefaultReq) Locals ¶
func (r *DefaultReq) Locals(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.
func (*DefaultReq) Method ¶
func (r *DefaultReq) Method(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.
func (*DefaultReq) MultipartForm ¶
func (r *DefaultReq) MultipartForm() (*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.
func (*DefaultReq) OriginalURL ¶
func (r *DefaultReq) OriginalURL() 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.
func (*DefaultReq) Params ¶
func (r *DefaultReq) Params(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.
func (*DefaultReq) Port ¶
func (r *DefaultReq) Port() string
Port returns the remote port of the request.
func (*DefaultReq) Protocol ¶
func (r *DefaultReq) Protocol() string
Protocol returns the HTTP protocol of request: HTTP/1.1 and HTTP/2.
func (*DefaultReq) Queries ¶
func (r *DefaultReq) Queries() 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"
func (*DefaultReq) Query ¶
func (r *DefaultReq) Query(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.
func (*DefaultReq) Range ¶
func (r *DefaultReq) Range(size int) (Range, error)
Range returns a struct containing the type and a slice of ranges.
func (*DefaultReq) Request ¶
func (r *DefaultReq) Request() *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
func (*DefaultReq) RequestCtx ¶
func (r *DefaultReq) RequestCtx() *fasthttp.RequestCtx
RequestCtx returns *fasthttp.RequestCtx that carries a deadline a cancellation signal, and other values across API boundaries.
func (*DefaultReq) Route ¶
func (r *DefaultReq) Route() *Route
Route returns the matched Route struct.
func (*DefaultReq) Scheme ¶
func (r *DefaultReq) Scheme() string
Scheme contains the request protocol string: http or https for TLS requests. Please use Config.TrustProxy to prevent header spoofing, in case when your app is behind the proxy.
func (*DefaultReq) Stale ¶
func (r *DefaultReq) Stale() bool
Stale returns the inverse of Fresh, indicating if the client's cached response is considered stale.
func (*DefaultReq) Subdomains ¶
func (r *DefaultReq) Subdomains(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.
type DefaultRes ¶
type DefaultRes struct {
// contains filtered or unexported fields
}
DefaultRes is the default implementation of Res used by DefaultCtx.
func (*DefaultRes) App ¶
func (r *DefaultRes) App() *App
App returns the *App reference to the instance of the Fiber application
func (*DefaultRes) Append ¶
func (r *DefaultRes) Append(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.
func (*DefaultRes) Attachment ¶
func (r *DefaultRes) Attachment(filename ...string)
Attachment sets the HTTP response Content-Disposition header field to attachment.
func (*DefaultRes) AutoFormat ¶
func (r *DefaultRes) AutoFormat(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. For more flexible content negotiation, use Format. If the header is not specified or there is no proper format, text/plain is used.
func (*DefaultRes) CBOR ¶
func (r *DefaultRes) CBOR(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.
func (*DefaultRes) ClearCookie ¶
func (r *DefaultRes) ClearCookie(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.
func (*DefaultRes) Cookie ¶
func (r *DefaultRes) Cookie(cookie *Cookie)
Cookie sets a cookie by passing a cookie struct.
func (*DefaultRes) Download ¶
func (r *DefaultRes) Download(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.
func (*DefaultRes) Drop ¶
func (r *DefaultRes) Drop() 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.
func (*DefaultRes) End ¶
func (r *DefaultRes) End() error
End immediately flushes the current response and closes the underlying connection.
func (*DefaultRes) Format ¶
func (r *DefaultRes) Format(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.
func (*DefaultRes) Get ¶
func (r *DefaultRes) Get(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.
func (*DefaultRes) GetHeaders ¶
func (r *DefaultRes) GetHeaders() 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.
func (*DefaultRes) GetRouteURL ¶
func (r *DefaultRes) GetRouteURL(routeName string, params Map) (string, error)
GetRouteURL generates URLs to named routes, with parameters. URLs are relative, for example: "/user/1831"
func (*DefaultRes) JSON ¶
func (r *DefaultRes) JSON(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.
func (*DefaultRes) JSONP ¶
func (r *DefaultRes) JSONP(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.
func (*DefaultRes) Links ¶
func (r *DefaultRes) Links(link ...string)
Links joins the links followed by the property to populate the response's Link HTTP header field.
func (*DefaultRes) Location ¶
func (r *DefaultRes) Location(path string)
Location sets the response Location HTTP header to the specified path parameter.
func (*DefaultRes) MsgPack ¶
func (r *DefaultRes) MsgPack(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.
func (*DefaultRes) OriginalURL ¶
func (r *DefaultRes) OriginalURL() 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.
func (*DefaultRes) Redirect ¶
func (r *DefaultRes) Redirect() *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.
func (*DefaultRes) Render ¶
func (r *DefaultRes) Render(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
func (*DefaultRes) RequestCtx ¶
func (r *DefaultRes) RequestCtx() *fasthttp.RequestCtx
RequestCtx returns *fasthttp.RequestCtx that carries a deadline a cancellation signal, and other values across API boundaries.
func (*DefaultRes) Response ¶
func (r *DefaultRes) Response() *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
func (*DefaultRes) Send ¶
func (r *DefaultRes) Send(body []byte) error
Send sets the HTTP response body without copying it. From this point onward the body argument must not be changed.
func (*DefaultRes) SendEarlyHints ¶
func (r *DefaultRes) SendEarlyHints(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
func (*DefaultRes) SendFile ¶
func (r *DefaultRes) SendFile(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.
func (*DefaultRes) SendStatus ¶
func (r *DefaultRes) SendStatus(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.
func (*DefaultRes) SendStream ¶
func (r *DefaultRes) SendStream(stream io.Reader, size ...int) error
SendStream sets response body stream and optional body size.
func (*DefaultRes) SendStreamWriter ¶
func (r *DefaultRes) SendStreamWriter(streamWriter func(*bufio.Writer)) error
SendStreamWriter sets response body stream writer
func (*DefaultRes) SendString ¶
func (r *DefaultRes) SendString(body string) error
SendString sets the HTTP response body for string types. This means no type assertion, recommended for faster performance
func (*DefaultRes) Set ¶
func (r *DefaultRes) Set(key, val string)
Set sets the response's HTTP header field to the specified key, value.
func (*DefaultRes) Status ¶
func (r *DefaultRes) Status(status int) Ctx
Status sets the HTTP status for the response. This method is chainable.
func (*DefaultRes) Type ¶
func (r *DefaultRes) Type(extension string, charset ...string) Ctx
Type sets the Content-Type HTTP header to the MIME type specified by the file extension.
func (*DefaultRes) Vary ¶
func (r *DefaultRes) Vary(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.
func (*DefaultRes) ViewBind ¶
func (r *DefaultRes) ViewBind(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.
func (*DefaultRes) Write ¶
func (r *DefaultRes) Write(p []byte) (int, error)
Write appends p into response body.
func (*DefaultRes) WriteString ¶
func (r *DefaultRes) WriteString(s string) (int, error)
WriteString appends s to response body.
func (*DefaultRes) Writef ¶
func (r *DefaultRes) Writef(f string, a ...any) (int, error)
Writef appends f & a into response body writer.
func (*DefaultRes) XML ¶
func (r *DefaultRes) XML(data any) error
XML converts any interface or string to XML. This method also sets the content header to application/xml; charset=utf-8.
type EmptyFieldError ¶
type EmptyFieldError = schema.EmptyFieldError
EmptyFieldError error exposes the internal schema.EmptyFieldError for public use.
type Error ¶
Error represents an error that occurred while handling a request.
type ErrorHandler ¶
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
if errors.As(err, &e) {
code = e.Code
}
c.Set(HeaderContentType, MIMETextPlainCharsetUTF8)
return c.Status(code).SendString(err.Error())
}
app := fiber.New(cfg)
type FlashMessage ¶
FlashMessage is a struct that holds the flash message data.
type GenericType ¶
type GenericType interface {
GenericTypeInteger | GenericTypeFloat | bool | string | []byte
}
GenericType enumerates the values that can be parsed from strings by the generic helper functions.
type GenericTypeFloat ¶
GenericTypeFloat is the union of supported floating-point types.
type GenericTypeInteger ¶
type GenericTypeInteger interface {
GenericTypeIntegerSigned | GenericTypeIntegerUnsigned
}
GenericTypeInteger is the union of all supported integer types.
type GenericTypeIntegerSigned ¶
GenericTypeIntegerSigned is the union of supported signed integer types.
type GenericTypeIntegerUnsigned ¶
GenericTypeIntegerUnsigned is the union of supported unsigned integer types.
type Group ¶
type Group struct {
Prefix string
// contains filtered or unexported fields
}
Group represents a collection of routes that share middleware and a common path prefix.
func (*Group) Connect ¶
Connect registers a route for CONNECT methods that establishes a tunnel to the server identified by the target resource.
func (*Group) Delete ¶
Delete registers a route for DELETE methods that deletes the specified resource.
func (*Group) Get ¶
Get registers a route for GET methods that requests a representation of the specified resource. Requests using GET should only retrieve data.
func (*Group) Group ¶
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 (*Group) Head ¶
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 (*Group) Name ¶
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 (*Group) Options ¶
Options registers a route for OPTIONS methods that is used to describe the communication options for the target resource.
func (*Group) Patch ¶
Patch registers a route for PATCH methods that is used to apply partial modifications to a resource.
func (*Group) Post ¶
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 (*Group) Put ¶
Put registers a route for PUT methods that replaces all current representations of the target resource with the request payload.
func (*Group) Route ¶
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 (*Group) RouteChain ¶
RouteChain creates a Registering instance scoped to the group's prefix, allowing chained route declarations for the same path.
func (*Group) Trace ¶
Trace registers a route for TRACE methods that performs a message loop-back test along the path to the target resource.
func (*Group) Use ¶
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 Hooks ¶
type Hooks struct {
// contains filtered or unexported fields
}
Hooks is a struct to use it with App.
func (*Hooks) OnFork ¶
func (h *Hooks) OnFork(handler ...OnForkHandler)
OnFork is a hook to execute user function after fork process.
func (*Hooks) OnGroup ¶
func (h *Hooks) OnGroup(handler ...OnGroupHandler)
OnGroup is a hook to execute user functions on each group registration. Also you can get group properties by group parameter.
func (*Hooks) OnGroupName ¶
func (h *Hooks) OnGroupName(handler ...OnGroupNameHandler)
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 (*Hooks) OnListen ¶
func (h *Hooks) OnListen(handler ...OnListenHandler)
OnListen is a hook to execute user functions on Listen, ListenTLS, Listener.
func (*Hooks) OnMount ¶
func (h *Hooks) OnMount(handler ...OnMountHandler)
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 (*Hooks) OnName ¶
func (h *Hooks) OnName(handler ...OnNameHandler)
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 (*Hooks) OnPostShutdown ¶
func (h *Hooks) OnPostShutdown(handler ...OnPostShutdownHandler)
OnPostShutdown is a hook to execute user functions after Shutdown.
func (*Hooks) OnPreShutdown ¶
func (h *Hooks) OnPreShutdown(handler ...OnPreShutdownHandler)
OnPreShutdown is a hook to execute user functions before Shutdown.
func (*Hooks) OnRoute ¶
func (h *Hooks) OnRoute(handler ...OnRouteHandler)
OnRoute is a hook to execute user functions on each route registration. Also you can get route properties by route parameter.
type InvalidUnmarshalError ¶
type InvalidUnmarshalError = json.InvalidUnmarshalError
InvalidUnmarshalError describes an invalid argument passed to Unmarshal. (The argument to Unmarshal must be a non-nil pointer.)
type ListenConfig ¶
type ListenConfig struct {
// GracefulContext is a field to shutdown Fiber by given context gracefully.
//
// Default: nil
GracefulContext context.Context `json:"graceful_context"` //nolint:containedctx // It's needed to set context inside Listen.
// TLSConfigFunc allows customizing tls.Config as you want.
//
// Default: nil
TLSConfigFunc func(tlsConfig *tls.Config) `json:"tls_config_func"`
// ListenerFunc allows accessing and customizing net.Listener.
//
// 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 client certificate.
// If you want to use mTLS, you have to enter this field.
//
// 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.
// Set to 0 to disable the timeout and wait indefinitely.
//
// Default: 10 * time.Second
ShutdownTimeout time.Duration `json:"shutdown_timeout"`
// 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.
//
// 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"`
// If set to true, will print all routes with their method, path and handler.
//
// Default: false
EnablePrintRoutes bool `json:"enable_print_routes"`
}
ListenConfig is a struct to customize startup of Fiber.
type ListenData ¶
ListenData is a struct to use it with OnListenHandler
type MarshalerError ¶
type MarshalerError = json.MarshalerError
MarshalerError represents an error from calling a MarshalJSON or MarshalText method.
type MultiError ¶
type MultiError = schema.MultiError
MultiError error exposes the internal schema.MultiError for public use.
type OldInputData ¶
OldInputData is a struct that holds the old input data.
type OnForkHandler ¶
OnForkHandler runs inside a forked worker process and receives the worker ID.
type OnGroupHandler ¶
OnGroupHandler defines the hook signature invoked whenever a group is registered.
type OnGroupNameHandler ¶
type OnGroupNameHandler = OnGroupHandler
OnGroupNameHandler shares the OnGroupHandler signature for group naming callbacks.
type OnListenHandler ¶
type OnListenHandler = func(ListenData) error
OnListenHandler runs when the application begins listening and receives the listener details.
type OnMountHandler ¶
OnMountHandler runs after a sub-application mounts to a parent and receives the parent app reference.
type OnNameHandler ¶
type OnNameHandler = OnRouteHandler
OnNameHandler shares the OnRouteHandler signature for route naming callbacks.
type OnPostShutdownHandler ¶
OnPostShutdownHandler runs after shutdown and receives the shutdown result.
type OnPreShutdownHandler ¶
type OnPreShutdownHandler = func() error
OnPreShutdownHandler runs before the application shuts down.
type OnRouteHandler ¶
OnRouteHandler defines the hook signature invoked whenever a route is registered.
type Redirect ¶
type Redirect struct {
// contains filtered or unexported fields
}
Redirect is a struct that holds the redirect data.
func AcquireRedirect ¶
func AcquireRedirect() *Redirect
AcquireRedirect return default Redirect reference from the redirect pool
func (*Redirect) Message ¶
func (r *Redirect) Message(key string) FlashMessage
Message Get flash message by key.
func (*Redirect) Messages ¶
func (r *Redirect) Messages() []FlashMessage
Messages Get flash messages.
func (*Redirect) OldInput ¶
func (r *Redirect) OldInput(key string) OldInputData
OldInput Get old input data by key.
func (*Redirect) OldInputs ¶
func (r *Redirect) OldInputs() []OldInputData
OldInputs Get old input data.
func (*Redirect) Route ¶
func (r *Redirect) Route(name string, config ...RedirectConfig) error
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 (*Redirect) Status ¶
Status sets the status code of redirection. If status is not specified, status defaults to 303 See Other.
func (*Redirect) To ¶
To redirect to the URL derived from the specified path, with specified status.
func (*Redirect) With ¶
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() Note: You must use escape char before using ',' and ':' chars to avoid wrong parsing.
type RedirectConfig ¶
type RedirectConfig struct {
Params Map // Route parameters
Queries map[string]string // Query map
}
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 Register ¶
type Register interface {
All(handler Handler, handlers ...Handler) Register
Get(handler Handler, handlers ...Handler) Register
Head(handler Handler, handlers ...Handler) Register
Post(handler Handler, handlers ...Handler) Register
Put(handler Handler, handlers ...Handler) Register
Delete(handler Handler, handlers ...Handler) Register
Connect(handler Handler, handlers ...Handler) Register
Options(handler Handler, handlers ...Handler) Register
Trace(handler Handler, handlers ...Handler) Register
Patch(handler Handler, handlers ...Handler) Register
Add(methods []string, handler Handler, handlers ...Handler) Register
RouteChain(path string) Register
}
Register defines all router handle interface generate by RouteChain().
type Registering ¶
type Registering struct {
// contains filtered or unexported fields
}
Registering provides route registration helpers for a specific path on the application instance.
func (*Registering) Add ¶
func (r *Registering) Add(methods []string, handler Handler, handlers ...Handler) Register
Add allows you to specify multiple HTTP methods to register a route.
func (*Registering) All ¶
func (r *Registering) All(handler Handler, handlers ...Handler) Register
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 (*Registering) Connect ¶
func (r *Registering) Connect(handler Handler, handlers ...Handler) Register
Connect registers a route for CONNECT methods that establishes a tunnel to the server identified by the target resource.
func (*Registering) Delete ¶
func (r *Registering) Delete(handler Handler, handlers ...Handler) Register
Delete registers a route for DELETE methods that deletes the specified resource.
func (*Registering) Get ¶
func (r *Registering) Get(handler Handler, handlers ...Handler) Register
Get registers a route for GET methods that requests a representation of the specified resource. Requests using GET should only retrieve data.
func (*Registering) Head ¶
func (r *Registering) Head(handler Handler, handlers ...Handler) Register
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 (*Registering) Options ¶
func (r *Registering) Options(handler Handler, handlers ...Handler) Register
Options registers a route for OPTIONS methods that is used to describe the communication options for the target resource.
func (*Registering) Patch ¶
func (r *Registering) Patch(handler Handler, handlers ...Handler) Register
Patch registers a route for PATCH methods that is used to apply partial modifications to a resource.
func (*Registering) Post ¶
func (r *Registering) Post(handler Handler, handlers ...Handler) Register
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 (*Registering) Put ¶
func (r *Registering) Put(handler Handler, handlers ...Handler) Register
Put registers a route for PUT methods that replaces all current representations of the target resource with the request payload.
func (*Registering) RouteChain ¶
func (r *Registering) RouteChain(path string) Register
RouteChain returns a new Register instance whose route path takes the path in the current instance as its prefix.
type Req ¶
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.
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 + base 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
// RequestCtx returns *fasthttp.RequestCtx that carries a deadline
// a cancellation signal, and other values across API boundaries.
RequestCtx() *fasthttp.RequestCtx
// 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
// 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.
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.
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.
// 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
// 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 (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, in case when your app is behind the proxy.
Host() string
// Hostname contains the hostname derived from the X-Forwarded-Host or Host HTTP header using the c.Host() method.
// Returned value is only valid within the handler. Do not store any references.
// Example: URL: https://example.com:8080 -> Hostname: example.com
// Make copies or use the Immutable setting instead.
// Please use Config.TrustProxy to prevent header spoofing, in case when your app is behind the proxy.
Hostname() string
// Port returns the remote port of the request.
Port() string
// IP returns the remote IP address of the request.
// If ProxyHeader and IP Validation is configured, it will parse that header and return the first valid IP address.
// Please use Config.TrustProxy to prevent header spoofing, in case when your app is behind the proxy.
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
// 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.
Locals(key any, value ...any) 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
// MultipartForm parse form entries from binary.
// This returns a map[string][]string, so given a key the value will be a string slice.
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
// 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, in case when your app is behind the 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 int) (Range, error)
// 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 true
// IsProxyTrusted can check remote ip by proxy ranges and ip map.
IsProxyTrusted() bool
// IsFromLocal will return true if request came from local.
IsFromLocal() bool
// contains filtered or unexported methods
}
Req is an interface for request-related Ctx methods.
type Res ¶
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.
Append(field string, values ...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.
Cookie(cookie *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.
// 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
// 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.
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.
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(name string, bind any, layouts ...string) error
// 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
// 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.
Status(status int) Ctx
// 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.
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.
End() error
// contains filtered or unexported methods
}
Res is an interface for response-related Ctx methods.
type Route ¶
type Route struct {
// 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
Params []string `json:"params"` // Case-sensitive param keys
Handlers []Handler `json:"-"` // Ctx handlers
// contains filtered or unexported fields
}
Route is a struct that holds all metadata for each registered handler.
type RouteMessage ¶
type RouteMessage struct {
// contains filtered or unexported fields
}
RouteMessage is some message need to be print when server starts
type Router ¶
type Router interface {
Use(args ...any) Router
Get(path string, handler Handler, handlers ...Handler) Router
Head(path string, handler Handler, handlers ...Handler) Router
Post(path string, handler Handler, handlers ...Handler) Router
Put(path string, handler Handler, handlers ...Handler) Router
Delete(path string, handler Handler, handlers ...Handler) Router
Connect(path string, handler Handler, handlers ...Handler) Router
Options(path string, handler Handler, handlers ...Handler) Router
Trace(path string, handler Handler, handlers ...Handler) Router
Patch(path string, handler Handler, handlers ...Handler) Router
Add(methods []string, path string, handler Handler, handlers ...Handler) Router
All(path string, handler Handler, handlers ...Handler) Router
Group(prefix string, handlers ...Handler) Router
RouteChain(path string) Register
Route(prefix string, fn func(router Router), name ...string) Router
Name(name string) Router
}
Router defines all router handle interface, including app and group router.
type SendFile ¶
type SendFile struct {
// FS is the file system to serve the static files from.
// You can use interfaces compatible with fs.FS like embed.FS, os.DirFS etc.
//
// Optional. Default: nil
FS fs.FS
// When set to true, the server tries minimizing CPU usage by caching compressed files.
// This works differently than the github.com/gofiber/compression middleware.
// You have to set Content-Encoding header to compress the file.
// Available compression methods are gzip, br, and zstd.
//
// Optional. Default: false
Compress bool `json:"compress"`
// When set to true, enables byte range requests.
//
// Optional. Default: false
ByteRange bool `json:"byte_range"`
// When set to true, enables direct download.
//
// Optional. Default: false
Download bool `json:"download"`
// Expiration duration for inactive file handlers.
// Use a negative time.Duration to disable it.
//
// Optional. Default: 10 * time.Second
CacheDuration time.Duration `json:"cache_duration"`
// The value for the Cache-Control HTTP-header
// that is set on the file response. MaxAge is defined in seconds.
//
// Optional. Default: 0
MaxAge int `json:"max_age"`
}
SendFile defines configuration options when to transfer file with SendFile.
type 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
}
Service is an interface that defines the methods for a service.
type State ¶
type State struct {
// contains filtered or unexported fields
}
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.
func (*State) GetBool ¶
GetBool retrieves a boolean value from the State. It returns the bool and a boolean indicating successful type assertion.
func (*State) GetComplex128 ¶
func (s *State) GetComplex128(key string) (complex128, bool)
GetComplex128 retrieves a complex128 value from the State. It returns the complex128 and a boolean indicating successful type assertion.
func (*State) GetComplex64 ¶
GetComplex64 retrieves a complex64 value from the State. It returns the complex64 and a boolean indicating successful type assertion.
func (*State) GetFloat32 ¶
GetFloat32 retrieves a float32 value from the State. It returns the float32 and a boolean indicating successful type assertion.
func (*State) GetFloat64 ¶
GetFloat64 retrieves a float64 value from the State. It returns the float64 and a boolean indicating successful type assertion.
func (*State) GetInt ¶
GetInt retrieves an integer value from the State. It returns the int and a boolean indicating successful type assertion.
func (*State) GetInt16 ¶
GetInt16 retrieves an int16 value from the State. It returns the int16 and a boolean indicating successful type assertion.
func (*State) GetInt32 ¶
GetInt32 retrieves an int32 value from the State. It returns the int32 and a boolean indicating successful type assertion.
func (*State) GetInt64 ¶
GetInt64 retrieves an int64 value from the State. It returns the int64 and a boolean indicating successful type assertion.
func (*State) GetInt8 ¶
GetInt8 retrieves an int8 value from the State. It returns the int8 and a boolean indicating successful type assertion.
func (*State) GetString ¶
GetString retrieves a string value from the State. It returns the string and a boolean indicating successful type assertion.
func (*State) GetUint ¶
GetUint retrieves a uint value from the State. It returns the uint and a boolean indicating successful type assertion.
func (*State) GetUint16 ¶
GetUint16 retrieves a uint16 value from the State. It returns the uint16 and a boolean indicating successful type assertion.
func (*State) GetUint32 ¶
GetUint32 retrieves a uint32 value from the State. It returns the uint32 and a boolean indicating successful type assertion.
func (*State) GetUint64 ¶
GetUint64 retrieves a uint64 value from the State. It returns the uint64 and a boolean indicating successful type assertion.
func (*State) GetUint8 ¶
GetUint8 retrieves a uint8 value from the State. It returns the uint8 and a boolean indicating successful type assertion.
func (*State) GetUintptr ¶
GetUintptr retrieves a uintptr value from the State. It returns the uintptr and a boolean indicating successful type assertion.
func (*State) Has ¶
Has checks if a key is present in the State. It returns a boolean indicating if the key is present.
func (*State) MustGet ¶
MustGet retrieves a value from the State and panics if the key is not found.
func (*State) Services ¶
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 (*State) ServicesLen ¶
ServicesLen returns the number of keys for services in the State.
type Storage ¶
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
}
Storage interface for communicating with different database/key-value providers
type StructValidator ¶
StructValidator is an interface to register custom struct validator for binding.
type SyntaxError ¶
type SyntaxError = json.SyntaxError
SyntaxError is a description of a JSON syntax error.
type TLSHandler ¶
type TLSHandler struct {
// contains filtered or unexported fields
}
TLSHandler hosts the callback hooks Fiber invokes while negotiating TLS connections, including optional client certificate lookups.
func (*TLSHandler) GetClientInfo ¶
func (t *TLSHandler) GetClientInfo(info *tls.ClientHelloInfo) (*tls.Certificate, error)
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 ¶
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
}
TestConfig is a struct holding Test settings
type TrustProxyConfig ¶
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"`
// contains filtered or unexported fields
}
TrustProxyConfig is a struct for configuring trusted proxies if Config.TrustProxy is true.
type UnknownKeyError ¶
type UnknownKeyError = schema.UnknownKeyError
UnknownKeyError error exposes the internal schema.UnknownKeyError for public use.
type UnmarshalTypeError ¶
type UnmarshalTypeError = json.UnmarshalTypeError
UnmarshalTypeError describes a JSON value that was not appropriate for a value of a specific Go type.
type UnsupportedTypeError ¶
type UnsupportedTypeError = json.UnsupportedTypeError
UnsupportedTypeError is returned by Marshal when attempting to encode an unsupported value type.
type UnsupportedValueError ¶
type UnsupportedValueError = json.UnsupportedValueError
UnsupportedValueError exposes json.UnsupportedValueError to describe unsupported values encountered during encoding.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
addon
|
|
|
The code was originally taken from https://github.com/valyala/fasthttp/pull/526.
|
The code was originally taken from https://github.com/valyala/fasthttp/pull/526. |
|
internal
|
|
|
memory
Package memory Is a slight copy of the memory storage, but far from the storage interface it can not only work with bytes but directly store any kind of data without having to encode it each time, which gives a huge speed advantage
|
Package memory Is a slight copy of the memory storage, but far from the storage interface it can not only work with bytes but directly store any kind of data without having to encode it each time, which gives a huge speed advantage |
|
storage/memory
Package memory Is a copy of the storage memory from the external storage packet as a purpose to test the behavior in the unittests when using a storages from these packets
|
Package memory Is a copy of the storage memory from the external storage packet as a purpose to test the behavior in the unittests when using a storages from these packets |
|
middleware
|
|
|
cache
Special thanks to @codemicro for moving this to fiber core Original middleware: github.com/codemicro/fiber-cache
|
Special thanks to @codemicro for moving this to fiber core Original middleware: github.com/codemicro/fiber-cache |
|
session
Package session provides session management middleware for Fiber.
|
Package session provides session management middleware for Fiber. |