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 GetTrimmedParam(param string) string
- func IsChild() bool
- func ReleaseAgent(a *Agent)
- func ReleaseArgs(a *Args)
- func ReleaseClient(c *Client)
- func ReleaseFormFile(ff *FormFile)
- func ReleaseResponse(resp *Response)
- func RemoveEscapeChar(word string) string
- func SetParserDecoder(parserConfig ParserConfig)
- type Agent
- func (a *Agent) Add(k, v string) *Agent
- func (a *Agent) AddBytesK(k []byte, v string) *Agent
- func (a *Agent) AddBytesKV(k []byte, v []byte) *Agent
- func (a *Agent) AddBytesV(k string, v []byte) *Agent
- func (a *Agent) BasicAuth(username, password string) *Agent
- func (a *Agent) BasicAuthBytes(username, password []byte) *Agent
- func (a *Agent) Body(body []byte) *Agent
- func (a *Agent) BodyStream(bodyStream io.Reader, bodySize int) *Agent
- func (a *Agent) BodyString(bodyString string) *Agent
- func (a *Agent) Boundary(boundary string) *Agent
- func (a *Agent) Bytes() (code int, body []byte, errs []error)
- func (a *Agent) ConnectionClose() *Agent
- func (a *Agent) ContentType(contentType string) *Agent
- func (a *Agent) ContentTypeBytes(contentType []byte) *Agent
- func (a *Agent) Cookie(key, value string) *Agent
- func (a *Agent) CookieBytesK(key []byte, value string) *Agent
- func (a *Agent) CookieBytesKV(key, value []byte) *Agent
- func (a *Agent) Cookies(kv ...string) *Agent
- func (a *Agent) CookiesBytesKV(kv ...[]byte) *Agent
- func (a *Agent) Debug(w ...io.Writer) *Agent
- func (a *Agent) Dest(dest []byte) *Agent
- func (a *Agent) FileData(formFiles ...*FormFile) *Agent
- func (a *Agent) Form(args *Args) *Agent
- func (a *Agent) Host(host string) *Agent
- func (a *Agent) HostBytes(host []byte) *Agent
- func (a *Agent) InsecureSkipVerify() *Agent
- func (a *Agent) JSON(v interface{}) *Agent
- func (a *Agent) JSONDecoder(jsonDecoder utils.JSONUnmarshal) *Agent
- func (a *Agent) JSONEncoder(jsonEncoder utils.JSONMarshal) *Agent
- func (a *Agent) MaxRedirectsCount(count int) *Agent
- func (a *Agent) MultipartForm(args *Args) *Agent
- func (a *Agent) Parse() error
- func (a *Agent) QueryString(queryString string) *Agent
- func (a *Agent) QueryStringBytes(queryString []byte) *Agent
- func (a *Agent) Referer(referer string) *Agent
- func (a *Agent) RefererBytes(referer []byte) *Agent
- func (a *Agent) Request() *Request
- func (a *Agent) RetryIf(retryIf RetryIfFunc) *Agent
- func (a *Agent) Reuse() *Agent
- func (a *Agent) SendFile(filename string, fieldname ...string) *Agent
- func (a *Agent) SendFiles(filenamesAndFieldnames ...string) *Agent
- func (a *Agent) Set(k, v string) *Agent
- func (a *Agent) SetBytesK(k []byte, v string) *Agent
- func (a *Agent) SetBytesKV(k []byte, v []byte) *Agent
- func (a *Agent) SetBytesV(k string, v []byte) *Agent
- func (a *Agent) SetResponse(customResp *Response) *Agent
- func (a *Agent) String() (int, string, []error)
- func (a *Agent) Struct(v interface{}) (code int, body []byte, errs []error)
- func (a *Agent) TLSConfig(config *tls.Config) *Agent
- func (a *Agent) Timeout(timeout time.Duration) *Agent
- func (a *Agent) UserAgent(userAgent string) *Agent
- func (a *Agent) UserAgentBytes(userAgent []byte) *Agent
- func (a *Agent) XML(v interface{}) *Agent
- type App
- func (app *App) AcquireCtx(fctx *fasthttp.RequestCtx) *Ctx
- func (app *App) Add(method, path string, handlers ...Handler) Router
- func (app *App) All(path string, handlers ...Handler) Router
- func (app *App) Config() Config
- func (app *App) Connect(path string, handlers ...Handler) Router
- func (app *App) Delete(path string, handlers ...Handler) Router
- func (app *App) ErrorHandler(ctx *Ctx, err error) error
- func (app *App) Get(path string, handlers ...Handler) Router
- func (app *App) GetRoute(name string) Route
- func (app *App) GetRoutes(filterUseOption ...bool) []Route
- 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, handlers ...Handler) Router
- func (app *App) Hooks() *Hooks
- func (app *App) Listen(addr string) error
- func (app *App) ListenMutualTLS(addr, certFile, keyFile, clientCertFile string) error
- func (app *App) ListenTLS(addr, certFile, keyFile string) error
- func (app *App) Listener(ln net.Listener) error
- func (app *App) Mount(prefix string, fiber *App) Router
- func (app *App) MountPath() string
- func (app *App) Name(name string) Router
- func (app *App) Options(path string, handlers ...Handler) Router
- func (app *App) Patch(path string, handlers ...Handler) Router
- func (app *App) Post(path string, handlers ...Handler) Router
- func (app *App) Put(path string, handlers ...Handler) Router
- func (app *App) ReleaseCtx(c *Ctx)
- func (app *App) Route(prefix string, fn func(router Router), name ...string) Router
- func (app *App) Server() *fasthttp.Server
- func (app *App) SetTLSHandler(tlsHandler *TLSHandler)
- func (app *App) Shutdown() error
- func (app *App) Stack() [][]*Route
- func (app *App) Static(prefix, root string, config ...Static) Router
- func (app *App) Test(req *http.Request, msTimeout ...int) (resp *http.Response, err error)
- func (app *App) Trace(path string, handlers ...Handler) Router
- func (app *App) Use(args ...interface{}) Router
- type Args
- type Client
- type Colors
- type Config
- type Constraint
- type ConversionError
- type Cookie
- type Ctx
- func (c *Ctx) Accepts(offers ...string) string
- func (c *Ctx) AcceptsCharsets(offers ...string) string
- func (c *Ctx) AcceptsEncodings(offers ...string) string
- func (c *Ctx) AcceptsLanguages(offers ...string) string
- func (c *Ctx) AllParams() map[string]string
- func (c *Ctx) App() *App
- func (c *Ctx) Append(field string, values ...string)
- func (c *Ctx) Attachment(filename ...string)
- func (c *Ctx) BaseURL() string
- func (c *Ctx) Bind(vars Map) error
- func (c *Ctx) Body() []byte
- func (c *Ctx) BodyParser(out interface{}) error
- func (c *Ctx) ClearCookie(key ...string)
- func (c *Ctx) ClientHelloInfo() *tls.ClientHelloInfo
- func (c *Ctx) Context() *fasthttp.RequestCtx
- func (c *Ctx) Cookie(cookie *Cookie)
- func (c *Ctx) Cookies(key string, defaultValue ...string) string
- func (c *Ctx) Download(file string, filename ...string) error
- func (c *Ctx) FormFile(key string) (*multipart.FileHeader, error)
- func (c *Ctx) FormValue(key string, defaultValue ...string) string
- func (c *Ctx) Format(body interface{}) error
- func (c *Ctx) Fresh() bool
- func (c *Ctx) Get(key string, defaultValue ...string) string
- func (c *Ctx) GetReqHeaders() map[string]string
- func (c *Ctx) GetRespHeader(key string, defaultValue ...string) string
- func (c *Ctx) GetRespHeaders() map[string]string
- func (c *Ctx) GetRouteURL(routeName string, params Map) (string, error)
- func (c *Ctx) Hostname() string
- func (c *Ctx) IP() string
- func (c *Ctx) IPs() (ips []string)
- func (c *Ctx) Is(extension string) bool
- func (c *Ctx) IsFromLocal() bool
- func (c *Ctx) IsProxyTrusted() bool
- func (c *Ctx) JSON(data interface{}) error
- func (c *Ctx) JSONP(data interface{}, callback ...string) error
- func (c *Ctx) Links(link ...string)
- func (c *Ctx) Locals(key interface{}, value ...interface{}) (val interface{})
- func (c *Ctx) Location(path string)
- func (c *Ctx) Method(override ...string) string
- func (c *Ctx) MultipartForm() (*multipart.Form, error)
- func (c *Ctx) Next() (err error)
- func (c *Ctx) OriginalURL() string
- func (c *Ctx) Params(key string, defaultValue ...string) string
- func (c *Ctx) ParamsInt(key string, defaultValue ...int) (int, error)
- func (c *Ctx) ParamsParser(out interface{}) error
- func (c *Ctx) Path(override ...string) string
- func (c *Ctx) Port() string
- func (c *Ctx) Protocol() string
- func (c *Ctx) Query(key string, defaultValue ...string) string
- func (c *Ctx) QueryParser(out interface{}) error
- func (c *Ctx) Range(size int) (rangeData Range, err error)
- func (c *Ctx) Redirect(location string, status ...int) error
- func (c *Ctx) RedirectBack(fallback string, status ...int) error
- func (c *Ctx) RedirectToRoute(routeName string, params Map, status ...int) error
- func (c *Ctx) Render(name string, bind interface{}, layouts ...string) error
- func (c *Ctx) ReqHeaderParser(out interface{}) error
- func (c *Ctx) Request() *fasthttp.Request
- func (c *Ctx) Response() *fasthttp.Response
- func (c *Ctx) RestartRouting() error
- func (c *Ctx) Route() *Route
- func (c *Ctx) SaveFile(fileheader *multipart.FileHeader, path string) error
- func (c *Ctx) SaveFileToStorage(fileheader *multipart.FileHeader, path string, storage Storage) error
- func (c *Ctx) Secure() bool
- func (c *Ctx) Send(body []byte) error
- func (c *Ctx) SendFile(file string, compress ...bool) error
- func (c *Ctx) SendStatus(status int) error
- func (c *Ctx) SendStream(stream io.Reader, size ...int) error
- func (c *Ctx) SendString(body string) error
- func (c *Ctx) Set(key string, val string)
- func (c *Ctx) SetUserContext(ctx context.Context)
- func (c *Ctx) Stale() bool
- func (c *Ctx) Status(status int) *Ctx
- func (c *Ctx) String() string
- func (c *Ctx) Subdomains(offset ...int) []string
- func (c *Ctx) Type(extension string, charset ...string) *Ctx
- func (c *Ctx) UserContext() context.Context
- func (c *Ctx) Vary(fields ...string)
- func (c *Ctx) Write(p []byte) (int, error)
- func (c *Ctx) WriteString(s string) (int, error)
- func (c *Ctx) Writef(f string, a ...interface{}) (int, error)
- func (c *Ctx) XHR() bool
- func (c *Ctx) XML(data interface{}) error
- type EmptyFieldError
- type Error
- type ErrorHandler
- type FormFile
- type Group
- func (grp *Group) Add(method, path string, handlers ...Handler) Router
- func (grp *Group) All(path string, handlers ...Handler) Router
- func (grp *Group) Connect(path string, handlers ...Handler) Router
- func (grp *Group) Delete(path string, handlers ...Handler) Router
- func (grp *Group) Get(path string, handlers ...Handler) Router
- func (grp *Group) Group(prefix string, handlers ...Handler) Router
- func (grp *Group) Head(path string, handlers ...Handler) Router
- func (grp *Group) Mount(prefix string, fiber *App) Router
- func (grp *Group) Name(name string) Router
- func (grp *Group) Options(path string, handlers ...Handler) Router
- func (grp *Group) Patch(path string, handlers ...Handler) Router
- func (grp *Group) Post(path string, handlers ...Handler) Router
- func (grp *Group) Put(path string, handlers ...Handler) Router
- func (grp *Group) Route(prefix string, fn func(router Router), name ...string) Router
- func (grp *Group) Static(prefix, root string, config ...Static) Router
- func (grp *Group) Trace(path string, handlers ...Handler) Router
- func (grp *Group) Use(args ...interface{}) 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) OnRoute(handler ...OnRouteHandler)
- func (h *Hooks) OnShutdown(handler ...OnShutdownHandler)
- type InvalidUnmarshalError
- type Map
- type MarshalerError
- type MultiError
- type OnForkHandler
- type OnGroupHandler
- type OnGroupNameHandler
- type OnListenHandler
- type OnMountHandler
- type OnNameHandler
- type OnRouteHandler
- type OnShutdownHandler
- type ParserConfig
- type ParserType
- type Range
- type Request
- type Response
- type RetryIfFunc
- type Route
- type RouteMessage
- type Router
- type Static
- type Storage
- type SyntaxError
- type TLSHandler
- 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 DefaultCompressedFileSuffix = ".fiber.gz" )
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" MIMEApplicationXML = "application/xml" MIMEApplicationJSON = "application/json" // Deprecated: use MIMETextJavaScript instead MIMEApplicationJavaScript = "application/javascript" MIMEApplicationForm = "application/x-www-form-urlencoded" MIMEOctetStream = "application/octet-stream" MIMEMultipartForm = "multipart/form-data" MIMETextXMLCharsetUTF8 = "text/xml; charset=utf-8" MIMETextHTMLCharsetUTF8 = "text/html; charset=utf-8" MIMETextPlainCharsetUTF8 = "text/plain; charset=utf-8" MIMETextJavaScriptCharsetUTF8 = "text/javascript; charset=utf-8" MIMEApplicationXMLCharsetUTF8 = "application/xml; charset=utf-8" MIMEApplicationJSONCharsetUTF8 = "application/json; charset=utf-8" // Deprecated: use MIMETextJavaScriptCharsetUTF8 instead MIMEApplicationJavaScriptCharsetUTF8 = "application/javascript; 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 https://github.com/nginx/nginx/blob/67d2a9541826ecd5db97d604f23460210fd3e517/conf/mime.types 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" // Deprecated: use HeaderPermissionsPolicy instead HeaderFeaturePolicy = "Feature-Policy" 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" )
HTTP Headers were copied from net/http.
const ( NetworkTCP = "tcp" NetworkTCP4 = "tcp4" NetworkTCP6 = "tcp6" )
Network types that are commonly used
const ( StrGzip = "gzip" StrBr = "br" StrDeflate = "deflate" StrBrotli = "brotli" )
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 Version = "2.40.0"
Version of current fiber package
Variables ¶
var ( ErrRangeMalformed = errors.New("range: malformed range header string") ErrRangeUnsatisfiable = errors.New("range: unsatisfiable range") )
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 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 DefaultErrorHandler = func(c *Ctx, err error) error { code := StatusInternalServerError var e *Error if errors.As(err, &e) { code = e.Code } c.Set(HeaderContentType, MIMETextPlainCharsetUTF8) return c.Status(code).SendString(err.Error()) }
DefaultErrorHandler that process return errors from handlers
var DefaultMethods = []string{ MethodGet, MethodHead, MethodPost, MethodPut, MethodDelete, MethodConnect, MethodOptions, MethodTrace, MethodPatch, }
HTTP methods enabled by default
Functions ¶
func GetTrimmedParam ¶
GetTrimmedParam trims the ':' & '?' from a string
func ReleaseAgent ¶ added in v2.6.0
func ReleaseAgent(a *Agent)
ReleaseAgent returns a acquired via AcquireAgent to Agent pool.
It is forbidden accessing req and/or its' members after returning it to Agent pool.
func ReleaseArgs ¶ added in v2.6.0
func ReleaseArgs(a *Args)
ReleaseArgs returns the object acquired via AcquireArgs to the pool.
String not access the released Args object, otherwise data races may occur. Copy from fasthttp
func ReleaseClient ¶ added in v2.6.0
func ReleaseClient(c *Client)
ReleaseClient returns c acquired via AcquireClient to client pool.
It is forbidden accessing req and/or its' members after returning it to client pool.
func ReleaseFormFile ¶ added in v2.6.0
func ReleaseFormFile(ff *FormFile)
ReleaseFormFile returns the object acquired via AcquireFormFile to the pool.
String not access the released FormFile object, otherwise data races may occur.
func ReleaseResponse ¶ added in v2.6.0
func ReleaseResponse(resp *Response)
ReleaseResponse return resp acquired via AcquireResponse to response pool.
It is forbidden accessing resp and/or its' members after returning it to response pool. Copy from fasthttp
func RemoveEscapeChar ¶ added in v2.8.0
RemoveEscapeChar remove escape characters
func SetParserDecoder ¶ added in v2.20.0
func SetParserDecoder(parserConfig ParserConfig)
SetParserDecoder allow globally change the option of form decoder, update decoderPool
Types ¶
type Agent ¶ added in v2.6.0
type Agent struct { // Name is used in User-Agent request header. Name string // NoDefaultUserAgentHeader when set to true, causes the default // User-Agent header to be excluded from the Request. NoDefaultUserAgentHeader bool // HostClient is an embedded fasthttp HostClient *fasthttp.HostClient // contains filtered or unexported fields }
Agent is an object storing all request data for client. Agent instance MUST NOT be used from concurrently running goroutines.
func AcquireAgent ¶ added in v2.6.0
func AcquireAgent() *Agent
AcquireAgent returns an empty Agent instance from Agent pool.
The returned Agent instance may be passed to ReleaseAgent when it is no longer needed. This allows Agent recycling, reduces GC pressure and usually improves performance.
func (*Agent) Add ¶ added in v2.6.0
Add adds the given 'key: value' header.
Multiple headers with the same key may be added with this function. Use Set for setting a single header for the given key.
func (*Agent) AddBytesK ¶ added in v2.6.0
AddBytesK adds the given 'key: value' header.
Multiple headers with the same key may be added with this function. Use SetBytesK for setting a single header for the given key.
func (*Agent) AddBytesKV ¶ added in v2.6.0
AddBytesKV adds the given 'key: value' header.
Multiple headers with the same key may be added with this function. Use SetBytesKV for setting a single header for the given key.
func (*Agent) AddBytesV ¶ added in v2.6.0
AddBytesV adds the given 'key: value' header.
Multiple headers with the same key may be added with this function. Use SetBytesV for setting a single header for the given key.
func (*Agent) BasicAuthBytes ¶ added in v2.6.0
BasicAuthBytes sets URI username and password.
func (*Agent) BodyStream ¶ added in v2.6.0
BodyStream sets request body stream and, optionally body size.
If bodySize is >= 0, then the bodyStream must provide exactly bodySize bytes before returning io.EOF.
If bodySize < 0, then bodyStream is read until io.EOF.
bodyStream.Close() is called after finishing reading all body data if it implements io.Closer.
Note that GET and HEAD requests cannot have body.
func (*Agent) BodyString ¶ added in v2.6.0
BodyString sets request body.
func (*Agent) Bytes ¶ added in v2.6.0
Bytes returns the status code, bytes body and errors of url.
it's not safe to use Agent after calling Agent.Bytes
func (*Agent) ConnectionClose ¶ added in v2.6.0
ConnectionClose sets 'Connection: close' header.
func (*Agent) ContentType ¶ added in v2.6.0
ContentType sets Content-Type header value.
func (*Agent) ContentTypeBytes ¶ added in v2.6.0
ContentTypeBytes sets Content-Type header value.
func (*Agent) CookieBytesK ¶ added in v2.6.0
CookieBytesK sets one 'key: value' cookie.
func (*Agent) CookieBytesKV ¶ added in v2.6.0
CookieBytesKV sets one 'key: value' cookie.
func (*Agent) CookiesBytesKV ¶ added in v2.6.0
CookiesBytesKV sets multiple 'key: value' cookies.
func (*Agent) Dest ¶ added in v2.6.0
Dest sets custom dest.
The contents of dest will be replaced by the response body, if the dest is too small a new slice will be allocated.
func (*Agent) FileData ¶ added in v2.6.0
FileData appends files for multipart form request.
It is recommended obtaining formFile via AcquireFormFile and release it manually in performance-critical code.
func (*Agent) Form ¶ added in v2.6.0
Form sends form request with body if args is non-nil.
It is recommended obtaining args via AcquireArgs and release it manually in performance-critical code.
func (*Agent) InsecureSkipVerify ¶ added in v2.6.0
InsecureSkipVerify controls whether the Agent verifies the server certificate chain and host name.
func (*Agent) JSONDecoder ¶ added in v2.6.0
func (a *Agent) JSONDecoder(jsonDecoder utils.JSONUnmarshal) *Agent
JSONDecoder sets custom json decoder.
func (*Agent) JSONEncoder ¶ added in v2.6.0
func (a *Agent) JSONEncoder(jsonEncoder utils.JSONMarshal) *Agent
JSONEncoder sets custom json encoder.
func (*Agent) MaxRedirectsCount ¶ added in v2.6.0
MaxRedirectsCount sets max redirect count for GET and HEAD.
func (*Agent) MultipartForm ¶ added in v2.6.0
MultipartForm sends multipart form request with k-v and files.
It is recommended obtaining args via AcquireArgs and release it manually in performance-critical code.
func (*Agent) QueryString ¶ added in v2.6.0
QueryString sets URI query string.
func (*Agent) QueryStringBytes ¶ added in v2.6.0
QueryStringBytes sets URI query string.
func (*Agent) RefererBytes ¶ added in v2.6.0
RefererBytes sets Referer header value.
func (*Agent) RetryIf ¶ added in v2.26.0
func (a *Agent) RetryIf(retryIf RetryIfFunc) *Agent
RetryIf controls whether a retry should be attempted after an error.
By default, will use isIdempotent function from fasthttp
func (*Agent) Reuse ¶ added in v2.6.0
Reuse enables the Agent instance to be used again after one request.
If agent is reusable, then it should be released manually when it is no longer used.
func (*Agent) SendFile ¶ added in v2.6.0
SendFile reads file and appends it to multipart form request.
func (*Agent) SendFiles ¶ added in v2.6.0
SendFiles reads files and appends them to multipart form request.
Examples:
SendFile("/path/to/file1", "fieldname1", "/path/to/file2")
func (*Agent) Set ¶ added in v2.6.0
Set sets the given 'key: value' header.
Use Add for setting multiple header values under the same key.
func (*Agent) SetBytesK ¶ added in v2.6.0
SetBytesK sets the given 'key: value' header.
Use AddBytesK for setting multiple header values under the same key.
func (*Agent) SetBytesKV ¶ added in v2.6.0
SetBytesKV sets the given 'key: value' header.
Use AddBytesKV for setting multiple header values under the same key.
func (*Agent) SetBytesV ¶ added in v2.6.0
SetBytesV sets the given 'key: value' header.
Use AddBytesV for setting multiple header values under the same key.
func (*Agent) SetResponse ¶ added in v2.6.0
SetResponse sets custom response for the Agent instance.
It is recommended obtaining custom response via AcquireResponse and release it manually in performance-critical code.
func (*Agent) String ¶ added in v2.6.0
String returns the status code, string body and errors of url.
it's not safe to use Agent after calling Agent.String
func (*Agent) Struct ¶ added in v2.6.0
Struct returns the status code, bytes body and errors of url. And bytes body will be unmarshalled to given v.
it's not safe to use Agent after calling Agent.Struct
func (*Agent) UserAgentBytes ¶ added in v2.6.0
UserAgentBytes sets User-Agent header value.
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 (*App) AcquireCtx ¶
func (app *App) AcquireCtx(fctx *fasthttp.RequestCtx) *Ctx
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 ¶ added in v2.20.0
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) GetRoutes ¶ added in v2.39.0
GetRoutes Get all routes. When filterUseOption equal to true, it will filter the routes registered by the middleware.
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 ¶ added in v2.24.0
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 ¶
Listen serves HTTP requests from the given addr.
app.Listen(":8080") app.Listen("127.0.0.1:8080")
func (*App) ListenMutualTLS ¶ added in v2.28.0
ListenMutualTLS serves HTTPS requests from the given addr. certFile, keyFile and clientCertFile are the paths to TLS certificate and key file:
app.ListenMutualTLS(":8080", "./cert.pem", "./cert.key", "./client.pem")
func (*App) ListenTLS ¶ added in v2.3.0
ListenTLS serves HTTPS requests from the given addr. certFile and keyFile are the paths to TLS certificate and key file:
app.ListenTLS(":8080", "./cert.pem", "./cert.key")
func (*App) Mount ¶ added in v2.0.3
Mount attaches 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 Mount. 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.
func (*App) MountPath ¶ added in v2.40.0
The MountPath property contains one or more path patterns on which a sub-app was mounted.
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) ReleaseCtx ¶
ReleaseCtx releases the ctx back into the pool.
func (*App) Route ¶ added in v2.26.0
Route is used to define routes with a common prefix inside the common function. Uses Group method to define new sub-router.
func (*App) SetTLSHandler ¶ added in v2.37.0
func (app *App) SetTLSHandler(tlsHandler *TLSHandler)
SetTLSHandler You can use SetTLSHandler to use 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 and then shut down.
Make sure the program doesn't exit and waits instead for Shutdown to return.
Shutdown does not close keepalive connections so its recommended to set ReadTimeout to something else than 0.
func (*App) Test ¶
Test is used for internal debugging by passing a *http.Request. Timeout is optional and defaults to 1s, -1 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 "/").
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() })
This method will match all HTTP verbs: GET, POST, PUT, HEAD etc...
type Args ¶ added in v2.6.0
Args represents query arguments.
It is forbidden copying Args instances. Create new instances instead and use CopyTo().
Args instance MUST NOT be used from concurrently running goroutines. Copy from fasthttp
func AcquireArgs ¶ added in v2.6.0
func AcquireArgs() *Args
AcquireArgs returns an empty Args object from the pool.
The returned Args may be returned to the pool with ReleaseArgs when no longer needed. This allows reducing GC load. Copy from fasthttp
type Client ¶ added in v2.6.0
type Client struct { // UserAgent is used in User-Agent request header. UserAgent string // NoDefaultUserAgentHeader when set to true, causes the default // User-Agent header to be excluded from the Request. NoDefaultUserAgentHeader bool // 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 JSONEncoder utils.JSONMarshal // 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 JSONDecoder utils.JSONUnmarshal // contains filtered or unexported fields }
Client implements http client.
It is safe calling Client methods from concurrently running goroutines.
func AcquireClient ¶ added in v2.6.0
func AcquireClient() *Client
AcquireClient returns an empty Client instance from client pool.
The returned Client instance may be passed to ReleaseClient when it is no longer needed. This allows Client recycling, reduces GC pressure and usually improves performance.
type Colors ¶ added in v2.36.0
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 { // When set to true, this will spawn multiple Go processes listening on the same port. // // Default: false Prefork bool `json:"prefork"` // 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"` // Enable or disable ETag header generation, since both weak and strong etags are generated // using the same hashing method (CRC-32). Weak ETags are the default when enabled. // // Default: false ETag bool `json:"etag"` // Max body size that the server accepts. // -1 will decline any body size // // 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"` // CompressedFileSuffix adds suffix to the original file name and // tries saving the resulting compressed file under the new file name. // // Default: ".fiber.gz" CompressedFileSuffix string `json:"compressed_file_suffix"` // 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"` // When set to true, it will not print out the «Fiber» ASCII art and listening address. // // Default: false DisableStartupMessage bool `json:"disable_startup_message"` // 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 then the current limit. 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. 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:"-"` // 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:"-"` // Known networks are "tcp", "tcp4" (IPv4-only), "tcp6" (IPv6-only) // WARNING: When prefork is set to true, only "tcp4" and "tcp6" can be chose. // // Default: NetworkTCP4 Network string // 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 TrustedProxyCheck to prevent header spoofing. // If you enable EnableTrustedProxyCheck and leave TrustedProxies empty Fiber will skip // all headers that could be spoofed. // If request ip in TrustedProxies whitelist then: // 1. c.Protocol() 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.Hostname() get value from X-Forwarded-Host header // But if request ip NOT in Trusted Proxies whitelist then: // 1. c.Protocol() WON't get value from X-Forwarded-Proto, X-Forwarded-Protocol, X-Forwarded-Ssl or X-Url-Scheme header, // will return https in case when tls connection is handled by the app, of http otherwise // 2. c.IP() WON'T get value from ProxyHeader header, will return RemoteIP() from fasthttp context // 3. c.Hostname() WON'T get value from X-Forwarded-Host header, fasthttp.Request.URI().Host() // will be used to get the hostname. // // Default: false EnableTrustedProxyCheck bool `json:"enable_trusted_proxy_check"` // Read EnableTrustedProxyCheck doc. // // Default: []string TrustedProxies []string `json:"trusted_proxies"` // 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"` // If set to true, will print all routes with their method, path and handler. // Default: false EnablePrintRoutes bool `json:"enable_print_routes"` // 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"` // RequestMethods provides customizibility for HTTP methods. You can add/remove methods as you wish. // // Optional. Defaukt: DefaultMethods RequestMethods []string // contains filtered or unexported fields }
Config is a struct holding the server settings.
type Constraint ¶ added in v2.37.0
type Constraint struct { ID TypeConstraint RegexCompiler *regexp.Regexp Data []string }
func (*Constraint) CheckConstraint ¶ added in v2.37.0
func (c *Constraint) CheckConstraint(param string) bool
type ConversionError ¶ added in v2.13.0
type ConversionError = schema.ConversionError
ConversionError Conversion error exposes the internal schema.ConversionError for public use.
type Cookie ¶
type Cookie struct { Name string `json:"name"` Value string `json:"value"` Path string `json:"path"` Domain string `json:"domain"` MaxAge int `json:"max_age"` Expires time.Time `json:"expires"` Secure bool `json:"secure"` HTTPOnly bool `json:"http_only"` SameSite string `json:"same_site"` SessionOnly bool `json:"session_only"` }
Cookie data for c.Cookie
type Ctx ¶
type Ctx struct {
// contains filtered or unexported fields
}
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.
func (*Ctx) AcceptsCharsets ¶
AcceptsCharsets checks if the specified charset is acceptable.
func (*Ctx) AcceptsEncodings ¶
AcceptsEncodings checks if the specified encoding is acceptable.
func (*Ctx) AcceptsLanguages ¶
AcceptsLanguages checks if the specified language is acceptable.
func (*Ctx) AllParams ¶ added in v2.32.0
AllParams Params is used to get all route parameters. Using Params method to get params.
func (*Ctx) Append ¶
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 (*Ctx) Attachment ¶
Attachment sets the HTTP response Content-Disposition header field to attachment.
func (*Ctx) Bind ¶ added in v2.27.0
Bind Add vars to default view var map binding to template engine. Variables are read by the Render method and may be overwritten.
func (*Ctx) Body ¶
Body 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 (*Ctx) BodyParser ¶
BodyParser binds the request body to a struct. 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 will return a ErrUnprocessableEntity error
func (*Ctx) ClearCookie ¶
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 (*Ctx) ClientHelloInfo ¶ added in v2.37.0
func (c *Ctx) ClientHelloInfo() *tls.ClientHelloInfo
ClientHelloInfo return CHI from context
func (*Ctx) Context ¶
func (c *Ctx) Context() *fasthttp.RequestCtx
Context returns *fasthttp.RequestCtx that carries a deadline a cancellation signal, and other values across API boundaries.
func (*Ctx) Cookies ¶
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 (*Ctx) Download ¶
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 (*Ctx) FormFile ¶
func (c *Ctx) FormFile(key string) (*multipart.FileHeader, error)
FormFile returns the first file by key from a MultipartForm.
func (*Ctx) FormValue ¶
FormValue returns the first value by key from a MultipartForm. 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 (*Ctx) Format ¶
Format performs content-negotiation on the Accept HTTP header. It uses Accepts to select a proper format. If the header is not specified or there is no proper format, text/plain is used.
func (*Ctx) Fresh ¶
Fresh returns true when the response is still “fresh” in the client's cache, otherwise false is returned to indicate that the client cache is now stale and the full response should be sent. When a client sends the Cache-Control: no-cache request header to indicate an end-to-end reload request, this module will return false to make handling these requests transparent. https://github.com/jshttp/fresh/blob/10e0471669dbbfbfd8de65bc6efac2ddd0bfa057/index.js#L33
func (*Ctx) Get ¶
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 (*Ctx) GetReqHeaders ¶ added in v2.24.0
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 (*Ctx) GetRespHeader ¶ added in v2.17.0
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 (*Ctx) GetRespHeaders ¶ added in v2.24.0
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 (*Ctx) GetRouteURL ¶ added in v2.31.0
GetRouteURL generates URLs to named routes, with parameters. URLs are relative, for example: "/user/1831"
func (*Ctx) Hostname ¶
Hostname contains the hostname derived from the X-Forwarded-Host or Host HTTP header. Returned value is only valid within the handler. Do not store any references. Make copies or use the Immutable setting instead. Please use Config.EnableTrustedProxyCheck to prevent header spoofing, in case when your app is behind the proxy.
func (*Ctx) IP ¶
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.EnableTrustedProxyCheck to prevent header spoofing, in case when your app is behind the proxy.
func (*Ctx) IPs ¶
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 (*Ctx) Is ¶
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 (*Ctx) IsFromLocal ¶ added in v2.24.0
IsFromLocal will return true if request came from local.
func (*Ctx) IsProxyTrusted ¶ added in v2.14.0
func (*Ctx) JSON ¶
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. This method also sets the content header to application/json.
func (*Ctx) JSONP ¶
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 (*Ctx) Links ¶
Links joins the links followed by the property to populate the response's Link HTTP header field.
func (*Ctx) Locals ¶
func (c *Ctx) Locals(key interface{}, value ...interface{}) (val interface{})
Locals makes it possible to pass interface{} values under keys scoped to the request and therefore available to all following routes that match the request.
func (*Ctx) Location ¶
Location sets the response Location HTTP header to the specified path parameter.
func (*Ctx) Method ¶
Method contains a string corresponding to the HTTP method of the request: GET, POST, PUT and so on.
func (*Ctx) MultipartForm ¶
MultipartForm parse form entries from binary. This returns a map[string][]string, so given a key the value will be a string slice.
func (*Ctx) OriginalURL ¶
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 (*Ctx) Params ¶
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 (*Ctx) ParamsInt ¶ added in v2.7.0
ParamsInt is used to get an integer from the route parameters it defaults to zero if the parameter is not found or if the parameter cannot be converted to an integer If a default value is given, it will return that value in case the param doesn't exist or cannot be converted to an integer
func (*Ctx) ParamsParser ¶ added in v2.35.0
ParamsParser binds the param string to a struct.
func (*Ctx) Path ¶
Path returns the path part of the request URL. Optionally, you could override the path.
func (*Ctx) Protocol ¶
Protocol contains the request protocol string: http or https for TLS requests. Please use Config.EnableTrustedProxyCheck to prevent header spoofing, in case when your app is behind the proxy.
func (*Ctx) Query ¶
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 (*Ctx) QueryParser ¶
QueryParser binds the query string to a struct.
func (*Ctx) Redirect ¶
Redirect to the URL derived from the specified path, with specified status. If status is not specified, status defaults to 302 Found.
func (*Ctx) RedirectBack ¶ added in v2.27.0
RedirectBack to the URL to referer If status is not specified, status defaults to 302 Found.
func (*Ctx) RedirectToRoute ¶ added in v2.27.0
RedirectToRoute to the Route registered in the app with appropriate parameters If status is not specified, status defaults to 302 Found. If you want to send queries to route, you must add "queries" key typed as map[string]string to params.
func (*Ctx) Render ¶
Render a template with data and sends a text/html response. We support the following engines: html, amber, handlebars, mustache, pug
func (*Ctx) ReqHeaderParser ¶ added in v2.26.0
ReqHeaderParser binds the request header strings to a struct.
func (*Ctx) 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 (*Ctx) 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 (*Ctx) RestartRouting ¶ added in v2.27.0
RestartRouting instead of going to the next handler. This may be usefull after changing the request path. Note that handlers might be executed again.
func (*Ctx) SaveFile ¶
func (c *Ctx) SaveFile(fileheader *multipart.FileHeader, path string) error
SaveFile saves any multipart file to disk.
func (*Ctx) SaveFileToStorage ¶ added in v2.27.0
func (c *Ctx) SaveFileToStorage(fileheader *multipart.FileHeader, path string, storage Storage) error
SaveFileToStorage saves any multipart file to an external storage system.
func (*Ctx) Send ¶
Send sets the HTTP response body without copying it. From this point onward the body argument must not be changed.
func (*Ctx) SendFile ¶
SendFile transfers the file from the given path. The file is not compressed by default, enable this by passing a 'true' argument Sets the Content-Type response HTTP header field based on the filenames extension.
func (*Ctx) SendStatus ¶
SendStatus sets the HTTP status code and if the response body is empty, it sets the correct status message in the body.
func (*Ctx) SendStream ¶
SendStream sets response body stream and optional body size.
func (*Ctx) SendString ¶
SendString sets the HTTP response body for string types. This means no type assertion, recommended for faster performance
func (*Ctx) SetUserContext ¶ added in v2.11.0
SetUserContext sets a context implementation by user.
func (*Ctx) String ¶
String returns unique string representation of the ctx.
The returned value may be useful for logging.
func (*Ctx) Subdomains ¶
Subdomains returns a string slice of subdomains in the domain name of the request. The subdomain offset, which defaults to 2, is used for determining the beginning of the subdomain segments.
func (*Ctx) Type ¶
Type sets the Content-Type HTTP header to the MIME type specified by the file extension.
func (*Ctx) UserContext ¶ added in v2.11.0
UserContext returns a context implementation that was set by user earlier or returns a non-nil, empty context,if it was not set earlier.
func (*Ctx) Vary ¶
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 (*Ctx) WriteString ¶ added in v2.0.2
WriteString appends s to response body.
type EmptyFieldError ¶ added in v2.13.0
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 FormFile ¶ added in v2.6.0
type FormFile struct { // Fieldname is form file's field name Fieldname string // Name is form file's name Name string // Content is form file's content Content []byte // contains filtered or unexported fields }
FormFile represents multipart form file
func AcquireFormFile ¶ added in v2.6.0
func AcquireFormFile() *FormFile
AcquireFormFile returns an empty FormFile object from the pool.
The returned FormFile may be returned to the pool with ReleaseFormFile when no longer needed. This allows reducing GC load.
type Group ¶
type Group struct { Prefix string // contains filtered or unexported fields }
Group struct
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) Mount ¶ added in v2.0.3
Mount attaches 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 Mount.
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 ¶ added in v2.26.0
Route is used to define routes with a common prefix inside the common function. Uses Group method to define new sub-router.
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 "/").
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() })
This method will match all HTTP verbs: GET, POST, PUT, HEAD etc...
type Hooks ¶ added in v2.37.0
type Hooks struct {
// contains filtered or unexported fields
}
Hooks is a struct to use it with App.
func (*Hooks) OnFork ¶ added in v2.37.0
func (h *Hooks) OnFork(handler ...OnForkHandler)
OnFork is a hook to execute user function after fork process.
func (*Hooks) OnGroup ¶ added in v2.37.0
func (h *Hooks) OnGroup(handler ...OnGroupHandler)
OnGroup is a hook to execute user functions on each group registeration. Also you can get group properties by group parameter.
func (*Hooks) OnGroupName ¶ added in v2.37.0
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 ¶ added in v2.37.0
func (h *Hooks) OnListen(handler ...OnListenHandler)
OnListen is a hook to execute user functions on Listen, ListenTLS, Listener.
func (*Hooks) OnMount ¶ added in v2.40.0
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 ¶ added in v2.37.0
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) OnRoute ¶ added in v2.37.0
func (h *Hooks) OnRoute(handler ...OnRouteHandler)
OnRoute is a hook to execute user functions on each route registeration. Also you can get route properties by route parameter.
func (*Hooks) OnShutdown ¶ added in v2.37.0
func (h *Hooks) OnShutdown(handler ...OnShutdownHandler)
OnShutdown is a hook to execute user functions after Shutdown.
type InvalidUnmarshalError ¶ added in v2.27.0
type InvalidUnmarshalError = errors.InvalidUnmarshalError
An InvalidUnmarshalError describes an invalid argument passed to Unmarshal. (The argument to Unmarshal must be a non-nil pointer.)
type Map ¶
type Map map[string]interface{}
Map is a shortcut for map[string]interface{}, useful for JSON returns
type MarshalerError ¶ added in v2.27.0
type MarshalerError = errors.MarshalerError
A MarshalerError represents an error from calling a MarshalJSON or MarshalText method.
type MultiError ¶ added in v2.13.0
type MultiError = schema.MultiError
MultiError error exposes the internal schema.MultiError for public use.
type OnForkHandler ¶ added in v2.36.0
type OnGroupHandler ¶ added in v2.30.0
type OnGroupNameHandler ¶ added in v2.30.0
type OnGroupNameHandler = OnGroupHandler
type OnListenHandler ¶ added in v2.30.0
type OnListenHandler = func() error
type OnMountHandler ¶ added in v2.40.0
type OnNameHandler ¶ added in v2.30.0
type OnNameHandler = OnRouteHandler
type OnRouteHandler ¶ added in v2.30.0
OnRouteHandler Handlers define a function to create hooks for Fiber.
type OnShutdownHandler ¶ added in v2.30.0
type OnShutdownHandler = OnListenHandler
type ParserConfig ¶ added in v2.20.0
type ParserConfig struct { IgnoreUnknownKeys bool SetAliasTag string ParserType []ParserType ZeroEmpty bool }
ParserConfig form decoder config for SetParserDecoder
type ParserType ¶ added in v2.20.0
ParserType require two element, type and converter for register. Use ParserType with BodyParser for parsing custom type in form data.
type Request ¶ added in v2.6.0
Request represents HTTP request.
It is forbidden copying Request instances. Create new instances and use CopyTo instead.
Request instance MUST NOT be used from concurrently running goroutines. Copy from fasthttp
type Response ¶ added in v2.6.0
Response represents HTTP response.
It is forbidden copying Response instances. Create new instances and use CopyTo instead.
Response instance MUST NOT be used from concurrently running goroutines. Copy from fasthttp
func AcquireResponse ¶ added in v2.6.0
func AcquireResponse() *Response
AcquireResponse returns an empty Response instance from response pool.
The returned Response instance may be passed to ReleaseResponse when it is no longer needed. This allows Response recycling, reduces GC pressure and usually improves performance. Copy from fasthttp
type RetryIfFunc ¶ added in v2.26.0
type RetryIfFunc = fasthttp.RetryIfFunc
RetryIfFunc signature of retry if function Request argument passed to RetryIfFunc, if there are any request errors. Copy from fasthttp
type Route ¶
type Route struct { // Public fields Method string `json:"method"` // HTTP method Name string `json:"name"` // Route's name 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 ¶ added in v2.24.0
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 ...interface{}) Router Get(path string, handlers ...Handler) Router Head(path string, handlers ...Handler) Router Post(path string, handlers ...Handler) Router Put(path string, handlers ...Handler) Router Delete(path string, handlers ...Handler) Router Connect(path string, handlers ...Handler) Router Options(path string, handlers ...Handler) Router Trace(path string, handlers ...Handler) Router Patch(path string, handlers ...Handler) Router Add(method, path string, handlers ...Handler) Router Static(prefix, root string, config ...Static) Router All(path string, handlers ...Handler) Router Group(prefix string, handlers ...Handler) Router Route(prefix string, fn func(router Router), name ...string) Router Mount(prefix string, fiber *App) Router Name(name string) Router }
Router defines all router handle interface, including app and group router.
type Static ¶
type Static struct { // When set to true, the server tries minimizing CPU usage by caching compressed files. // This works differently than the github.com/gofiber/compression middleware. // Optional. Default value false Compress bool `json:"compress"` // When set to true, enables byte range requests. // Optional. Default value false ByteRange bool `json:"byte_range"` // When set to true, enables directory browsing. // Optional. Default value false. Browse bool `json:"browse"` // When set to true, enables direct download. // Optional. Default value false. Download bool `json:"download"` // The name of the index file for serving a directory. // Optional. Default value "index.html". Index string `json:"index"` // Expiration duration for inactive file handlers. // Use a negative time.Duration to disable it. // // Optional. Default value 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 value 0. MaxAge int `json:"max_age"` // ModifyResponse defines a function that allows you to alter the response. // // Optional. Default: nil ModifyResponse Handler // Next defines a function to skip this middleware when returned true. // // Optional. Default: nil Next func(c *Ctx) bool }
Static defines configuration options when defining static assets.
type Storage ¶ added in v2.1.2
type Storage interface { // Get gets the value for the given key. // `nil, nil` is returned when the key does not exist Get(key string) ([]byte, 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 // Delete deletes the value for the given key. // It returns no error if the storage does not contain the key, Delete(key string) 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 SyntaxError ¶ added in v2.27.0
type SyntaxError = errors.SyntaxError
A SyntaxError is a description of a JSON syntax error.
type TLSHandler ¶ added in v2.37.0
type TLSHandler struct {
// contains filtered or unexported fields
}
TLSHandler object
func (*TLSHandler) GetClientInfo ¶ added in v2.37.0
func (t *TLSHandler) GetClientInfo(info *tls.ClientHelloInfo) (*tls.Certificate, error)
GetClientInfo Callback function to set CHI
type TypeConstraint ¶ added in v2.37.0
type TypeConstraint int16
TypeConstraint parameter constraint types
type UnknownKeyError ¶ added in v2.13.0
type UnknownKeyError = schema.UnknownKeyError
UnknownKeyError error exposes the internal schema.UnknownKeyError for public use.
type UnmarshalTypeError ¶ added in v2.27.0
type UnmarshalTypeError = errors.UnmarshalTypeError
An UnmarshalTypeError describes a JSON value that was not appropriate for a value of a specific Go type.
type UnsupportedTypeError ¶ added in v2.27.0
type UnsupportedTypeError = errors.UnsupportedTypeError
An UnsupportedTypeError is returned by Marshal when attempting to encode an unsupported value type.
type UnsupportedValueError ¶ added in v2.27.0
type UnsupportedValueError = errors.UnsupportedValueError
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
internal
|
|
fwd
The `fwd` package provides a buffered reader and writer.
|
The `fwd` package provides a buffered reader and writer. |
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 |
msgp
This package is the support library for the msgp code generator (http://github.com/tinylib/msgp).
|
This package is the support library for the msgp code generator (http://github.com/tinylib/msgp). |
schema
Package gorilla/schema fills a struct with form values.
|
Package gorilla/schema fills a struct with form values. |
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 |
uuid
Package uuid generates and inspects UUIDs.
|
Package uuid generates and inspects UUIDs. |
wmi
Package wmi provides a WQL interface for WMI on Windows.
|
Package wmi provides a WQL interface for WMI on Windows. |
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 |