fiber

package module
v1.14.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 11, 2020 License: MIT Imports: 34 Imported by: 1,198

Documentation

Index

Constants

View Source
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.

View Source
const (
	MIMETextXML               = "text/xml"
	MIMETextHTML              = "text/html"
	MIMETextPlain             = "text/plain"
	MIMEApplicationXML        = "application/xml"
	MIMEApplicationJSON       = "application/json"
	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"
	MIMEApplicationXMLCharsetUTF8        = "application/xml; charset=utf-8"
	MIMEApplicationJSONCharsetUTF8       = "application/json; charset=utf-8"
	MIMEApplicationJavaScriptCharsetUTF8 = "application/javascript; charset=utf-8"
)

MIME types that are commonly used

View Source
const (
	StatusContinue                      = 100 // RFC 7231, 6.2.1
	StatusSwitchingProtocols            = 101 // RFC 7231, 6.2.2
	StatusProcessing                    = 102 // RFC 2518, 10.1
	StatusEarlyHints                    = 103 // RFC 8297
	StatusOK                            = 200 // RFC 7231, 6.3.1
	StatusCreated                       = 201 // RFC 7231, 6.3.2
	StatusAccepted                      = 202 // RFC 7231, 6.3.3
	StatusNonAuthoritativeInfo          = 203 // RFC 7231, 6.3.4
	StatusNoContent                     = 204 // RFC 7231, 6.3.5
	StatusResetContent                  = 205 // RFC 7231, 6.3.6
	StatusPartialContent                = 206 // RFC 7233, 4.1
	StatusMultiStatus                   = 207 // RFC 4918, 11.1
	StatusAlreadyReported               = 208 // RFC 5842, 7.1
	StatusIMUsed                        = 226 // RFC 3229, 10.4.1
	StatusMultipleChoices               = 300 // RFC 7231, 6.4.1
	StatusMovedPermanently              = 301 // RFC 7231, 6.4.2
	StatusFound                         = 302 // RFC 7231, 6.4.3
	StatusSeeOther                      = 303 // RFC 7231, 6.4.4
	StatusNotModified                   = 304 // RFC 7232, 4.1
	StatusUseProxy                      = 305 // RFC 7231, 6.4.5
	StatusTemporaryRedirect             = 307 // RFC 7231, 6.4.7
	StatusPermanentRedirect             = 308 // RFC 7538, 3
	StatusBadRequest                    = 400 // RFC 7231, 6.5.1
	StatusUnauthorized                  = 401 // RFC 7235, 3.1
	StatusPaymentRequired               = 402 // RFC 7231, 6.5.2
	StatusForbidden                     = 403 // RFC 7231, 6.5.3
	StatusNotFound                      = 404 // RFC 7231, 6.5.4
	StatusMethodNotAllowed              = 405 // RFC 7231, 6.5.5
	StatusNotAcceptable                 = 406 // RFC 7231, 6.5.6
	StatusProxyAuthRequired             = 407 // RFC 7235, 3.2
	StatusRequestTimeout                = 408 // RFC 7231, 6.5.7
	StatusConflict                      = 409 // RFC 7231, 6.5.8
	StatusGone                          = 410 // RFC 7231, 6.5.9
	StatusLengthRequired                = 411 // RFC 7231, 6.5.10
	StatusPreconditionFailed            = 412 // RFC 7232, 4.2
	StatusRequestEntityTooLarge         = 413 // RFC 7231, 6.5.11
	StatusRequestURITooLong             = 414 // RFC 7231, 6.5.12
	StatusUnsupportedMediaType          = 415 // RFC 7231, 6.5.13
	StatusRequestedRangeNotSatisfiable  = 416 // RFC 7233, 4.4
	StatusExpectationFailed             = 417 // RFC 7231, 6.5.14
	StatusTeapot                        = 418 // RFC 7168, 2.3.3
	StatusMisdirectedRequest            = 421 // RFC 7540, 9.1.2
	StatusUnprocessableEntity           = 422 // RFC 4918, 11.2
	StatusLocked                        = 423 // RFC 4918, 11.3
	StatusFailedDependency              = 424 // RFC 4918, 11.4
	StatusTooEarly                      = 425 // RFC 8470, 5.2.
	StatusUpgradeRequired               = 426 // RFC 7231, 6.5.15
	StatusPreconditionRequired          = 428 // RFC 6585, 3
	StatusTooManyRequests               = 429 // RFC 6585, 4
	StatusRequestHeaderFieldsTooLarge   = 431 // RFC 6585, 5
	StatusUnavailableForLegalReasons    = 451 // RFC 7725, 3
	StatusInternalServerError           = 500 // RFC 7231, 6.6.1
	StatusNotImplemented                = 501 // RFC 7231, 6.6.2
	StatusBadGateway                    = 502 // RFC 7231, 6.6.3
	StatusServiceUnavailable            = 503 // RFC 7231, 6.6.4
	StatusGatewayTimeout                = 504 // RFC 7231, 6.6.5
	StatusHTTPVersionNotSupported       = 505 // RFC 7231, 6.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.

View Source
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"
	HeaderFeaturePolicy                   = "Feature-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.

View Source
const Version = "1.14.6"

Version of current package

Variables

View Source
var (
	ErrRangeMalformed     = errors.New("range: malformed range header string")
	ErrRangeUnsatisfiable = errors.New("range: unsatisfiable range")
)
View Source
var (
	ErrContinue                      = NewError(StatusContinue)                      // RFC 7231, 6.2.1
	ErrSwitchingProtocols            = NewError(StatusSwitchingProtocols)            // RFC 7231, 6.2.2
	ErrProcessing                    = NewError(StatusProcessing)                    // RFC 2518, 10.1
	ErrEarlyHints                    = NewError(StatusEarlyHints)                    // RFC 8297
	ErrOK                            = NewError(StatusOK)                            // RFC 7231, 6.3.1
	ErrCreated                       = NewError(StatusCreated)                       // RFC 7231, 6.3.2
	ErrAccepted                      = NewError(StatusAccepted)                      // RFC 7231, 6.3.3
	ErrNonAuthoritativeInfo          = NewError(StatusNonAuthoritativeInfo)          // RFC 7231, 6.3.4
	ErrNoContent                     = NewError(StatusNoContent)                     // RFC 7231, 6.3.5
	ErrResetContent                  = NewError(StatusResetContent)                  // RFC 7231, 6.3.6
	ErrPartialContent                = NewError(StatusPartialContent)                // RFC 7233, 4.1
	ErrMultiStatus                   = NewError(StatusMultiStatus)                   // RFC 4918, 11.1
	ErrAlreadyReported               = NewError(StatusAlreadyReported)               // RFC 5842, 7.1
	ErrIMUsed                        = NewError(StatusIMUsed)                        // RFC 3229, 10.4.1
	ErrMultipleChoices               = NewError(StatusMultipleChoices)               // RFC 7231, 6.4.1
	ErrMovedPermanently              = NewError(StatusMovedPermanently)              // RFC 7231, 6.4.2
	ErrFound                         = NewError(StatusFound)                         // RFC 7231, 6.4.3
	ErrSeeOther                      = NewError(StatusSeeOther)                      // RFC 7231, 6.4.4
	ErrNotModified                   = NewError(StatusNotModified)                   // RFC 7232, 4.1
	ErrUseProxy                      = NewError(StatusUseProxy)                      // RFC 7231, 6.4.5
	ErrTemporaryRedirect             = NewError(StatusTemporaryRedirect)             // RFC 7231, 6.4.7
	ErrPermanentRedirect             = NewError(StatusPermanentRedirect)             // RFC 7538, 3
	ErrBadRequest                    = NewError(StatusBadRequest)                    // RFC 7231, 6.5.1
	ErrUnauthorized                  = NewError(StatusUnauthorized)                  // RFC 7235, 3.1
	ErrPaymentRequired               = NewError(StatusPaymentRequired)               // RFC 7231, 6.5.2
	ErrForbidden                     = NewError(StatusForbidden)                     // RFC 7231, 6.5.3
	ErrNotFound                      = NewError(StatusNotFound)                      // RFC 7231, 6.5.4
	ErrMethodNotAllowed              = NewError(StatusMethodNotAllowed)              // RFC 7231, 6.5.5
	ErrNotAcceptable                 = NewError(StatusNotAcceptable)                 // RFC 7231, 6.5.6
	ErrProxyAuthRequired             = NewError(StatusProxyAuthRequired)             // RFC 7235, 3.2
	ErrRequestTimeout                = NewError(StatusRequestTimeout)                // RFC 7231, 6.5.7
	ErrConflict                      = NewError(StatusConflict)                      // RFC 7231, 6.5.8
	ErrGone                          = NewError(StatusGone)                          // RFC 7231, 6.5.9
	ErrLengthRequired                = NewError(StatusLengthRequired)                // RFC 7231, 6.5.10
	ErrPreconditionFailed            = NewError(StatusPreconditionFailed)            // RFC 7232, 4.2
	ErrRequestEntityTooLarge         = NewError(StatusRequestEntityTooLarge)         // RFC 7231, 6.5.11
	ErrRequestURITooLong             = NewError(StatusRequestURITooLong)             // RFC 7231, 6.5.12
	ErrUnsupportedMediaType          = NewError(StatusUnsupportedMediaType)          // RFC 7231, 6.5.13
	ErrRequestedRangeNotSatisfiable  = NewError(StatusRequestedRangeNotSatisfiable)  // RFC 7233, 4.4
	ErrExpectationFailed             = NewError(StatusExpectationFailed)             // RFC 7231, 6.5.14
	ErrTeapot                        = NewError(StatusTeapot)                        // RFC 7168, 2.3.3
	ErrMisdirectedRequest            = NewError(StatusMisdirectedRequest)            // RFC 7540, 9.1.2
	ErrUnprocessableEntity           = NewError(StatusUnprocessableEntity)           // RFC 4918, 11.2
	ErrLocked                        = NewError(StatusLocked)                        // RFC 4918, 11.3
	ErrFailedDependency              = NewError(StatusFailedDependency)              // RFC 4918, 11.4
	ErrTooEarly                      = NewError(StatusTooEarly)                      // RFC 8470, 5.2.
	ErrUpgradeRequired               = NewError(StatusUpgradeRequired)               // RFC 7231, 6.5.15
	ErrPreconditionRequired          = NewError(StatusPreconditionRequired)          // RFC 6585, 3
	ErrTooManyRequests               = NewError(StatusTooManyRequests)               // RFC 6585, 4
	ErrRequestHeaderFieldsTooLarge   = NewError(StatusRequestHeaderFieldsTooLarge)   // RFC 6585, 5
	ErrUnavailableForLegalReasons    = NewError(StatusUnavailableForLegalReasons)    // RFC 7725, 3
	ErrInternalServerError           = NewError(StatusInternalServerError)           // RFC 7231, 6.6.1
	ErrNotImplemented                = NewError(StatusNotImplemented)                // RFC 7231, 6.6.2
	ErrBadGateway                    = NewError(StatusBadGateway)                    // RFC 7231, 6.6.3
	ErrServiceUnavailable            = NewError(StatusServiceUnavailable)            // RFC 7231, 6.6.4
	ErrGatewayTimeout                = NewError(StatusGatewayTimeout)                // RFC 7231, 6.6.5
	ErrHTTPVersionNotSupported       = NewError(StatusHTTPVersionNotSupported)       // RFC 7231, 6.6.6
	ErrVariantAlsoNegotiates         = NewError(StatusVariantAlsoNegotiates)         // RFC 2295, 8.1
	ErrInsufficientStorage           = NewError(StatusInsufficientStorage)           // RFC 4918, 11.5
	ErrLoopDetected                  = NewError(StatusLoopDetected)                  // RFC 5842, 7.2
	ErrNotExtended                   = NewError(StatusNotExtended)                   // RFC 2774, 7
	ErrNetworkAuthenticationRequired = NewError(StatusNetworkAuthenticationRequired) // RFC 6585, 6
)

Errors

Functions

This section is empty.

Types

type App added in v1.0.0

type App struct {

	// App settings
	Settings *Settings `json:"settings"`
	// contains filtered or unexported fields
}

App denotes the Fiber application.

func New

func New(settings ...*Settings) *App

New creates a new Fiber named instance.

myApp := app.New()

You can pass an optional settings by passing a *Settings struct:

myApp := app.New(&fiber.Settings{
    Prefork: true,
    ServerHeader: "Fiber",
})

func (*App) AcquireCtx added in v1.10.0

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

AcquireCtx retrieves a new Ctx from the pool.

func (*App) Add added in v1.10.0

func (app *App) Add(method, path string, handlers ...Handler) Router

Add ...

func (*App) All added in v1.0.0

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

All ...

func (*App) Connect added in v1.0.0

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

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

func (*App) Delete added in v1.0.0

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

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

func (*App) Get added in v1.0.0

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

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

func (*App) Group added in v1.0.0

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

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

func (*App) Handler added in v1.12.1

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

Handler returns the server handler.

func (*App) Head added in v1.0.0

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

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) IsChild added in v1.12.6

func (app *App) IsChild() bool

IsChild determines if the current process is a result of Prefork

func (*App) Listen added in v1.0.0

func (app *App) Listen(address interface{}, tlsconfig ...*tls.Config) error

Listen serves HTTP requests from the given addr or port. You can pass an optional *tls.Config to enable TLS.

app.Listen(8080)
app.Listen("8080")
app.Listen(":8080")
app.Listen("127.0.0.1:8080")

func (*App) Listener added in v1.12.5

func (app *App) Listener(ln net.Listener, tlsconfig ...*tls.Config) error

Listener can be used to pass a custom listener. You can pass an optional *tls.Config to enable TLS. This method does not support the Prefork feature To use Prefork, please use app.Listen()

func (*App) Options added in v1.0.0

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

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

func (*App) Patch added in v1.0.0

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

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

func (*App) Post added in v1.0.0

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

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 added in v1.0.0

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

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

func (*App) ReleaseCtx added in v1.10.0

func (app *App) ReleaseCtx(ctx *Ctx)

ReleaseCtx releases the ctx back into the pool.

func (*App) Routes added in v1.11.0

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

Routes returns all registered routes

for _, r := range app.Routes() {
	fmt.Printf("%s\t%s\n", r.Method, r.Path)
}

func (*App) Shutdown added in v1.0.0

func (app *App) Shutdown() error

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.

When Shutdown is called, Serve, ListenAndServe, and ListenAndServeTLS immediately return nil. 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) Stack added in v1.13.2

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

Handler returns the server handler.

func (*App) Static added in v1.0.0

func (app *App) Static(prefix, root string, config ...Static) Router

Static ...

func (*App) Test added in v1.0.0

func (app *App) Test(request *http.Request, msTimeout ...int) (*http.Response, error)

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 added in v1.0.0

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

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

func (*App) Use added in v1.0.0

func (app *App) Use(args ...interface{}) Router

Use registers a middleware route. Middleware matches requests beginning with the provided prefix. Providing a prefix is optional, it defaults to "/".

app.Use(handler)
app.Use("/api", handler)
app.Use("/api", handler, handler)
type Cookie struct {
	Name     string    `json:"name"`
	Value    string    `json:"value"`
	Path     string    `json:"path"`
	Domain   string    `json:"domain"`
	Expires  time.Time `json:"expires"`
	Secure   bool      `json:"secure"`
	HTTPOnly bool      `json:"http_only"`
	SameSite string    `json:"same_site"`
}

Cookie data for ctx.Cookie

type Ctx

type Ctx struct {
	Fasthttp *fasthttp.RequestCtx // Reference to *fasthttp.RequestCtx
	// 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) Accepts

func (ctx *Ctx) Accepts(offers ...string) string

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

func (*Ctx) AcceptsCharsets

func (ctx *Ctx) AcceptsCharsets(offers ...string) string

AcceptsCharsets checks if the specified charset is acceptable.

func (*Ctx) AcceptsEncodings

func (ctx *Ctx) AcceptsEncodings(offers ...string) string

AcceptsEncodings checks if the specified encoding is acceptable.

func (*Ctx) AcceptsLanguages

func (ctx *Ctx) AcceptsLanguages(offers ...string) string

AcceptsLanguages checks if the specified language is acceptable.

func (*Ctx) App added in v1.11.0

func (ctx *Ctx) App() *App

App returns the *App reference to access Settings or ErrorHandler

func (*Ctx) Append

func (ctx *Ctx) 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 (*Ctx) Attachment

func (ctx *Ctx) Attachment(filename ...string)

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

func (*Ctx) BaseURL added in v1.0.0

func (ctx *Ctx) BaseURL() string

BaseURL returns (protocol + host + base path).

func (*Ctx) Body

func (ctx *Ctx) Body() string

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 added in v1.0.0

func (ctx *Ctx) BodyParser(out interface{}) error

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

func (*Ctx) ClearCookie

func (ctx *Ctx) 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 (*Ctx) Context added in v1.10.0

func (ctx *Ctx) Context() context.Context

Context returns context.Context that carries a deadline, a cancellation signal, and other values across API boundaries.

func (*Ctx) Cookie

func (ctx *Ctx) Cookie(cookie *Cookie)

Cookie sets a cookie by passing a cookie struct.

func (*Ctx) Cookies

func (ctx *Ctx) Cookies(key string, defaultValue ...string) string

Cookies is 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

func (ctx *Ctx) 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 (*Ctx) Error added in v1.0.0

func (ctx *Ctx) Error() error

Error contains the error information passed via the Next(err) method.

func (*Ctx) FormFile

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

FormFile returns the first file by key from a MultipartForm.

func (*Ctx) FormValue

func (ctx *Ctx) FormValue(key string) (value string)

FormValue returns the first value by key from a MultipartForm. Returned value is only valid within the handler. Do not store any references. Make copies or use the Immutable setting instead.

func (*Ctx) Format

func (ctx *Ctx) Format(body interface{})

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

func (ctx *Ctx) 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/10e0471669dbbfbfd8de65bc6efac2ddd0bfa057/index.js#L33

func (*Ctx) Get

func (ctx *Ctx) 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 (*Ctx) Hostname

func (ctx *Ctx) Hostname() string

Hostname contains the hostname derived from the Host HTTP header. Returned value is only valid within the handler. Do not store any references. Make copies or use the Immutable setting instead.

func (*Ctx) IP added in v1.0.0

func (ctx *Ctx) IP() string

IP returns the remote IP address of the request.

func (*Ctx) IPs added in v1.0.0

func (ctx *Ctx) IPs() (ips []string)

IPs returns an string slice of IP addresses specified in the X-Forwarded-For request header.

func (*Ctx) Is

func (ctx *Ctx) 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 (*Ctx) JSON added in v1.0.0

func (ctx *Ctx) JSON(data interface{}) error

JSON converts any interface or string to JSON. This method also sets the content header to application/json.

func (*Ctx) JSONP added in v1.0.0

func (ctx *Ctx) JSONP(data interface{}, 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 (ctx *Ctx) Links(link ...string)

Links joins the links followed by the property to populate the response's Link HTTP header field.

func (*Ctx) Locals

func (ctx *Ctx) Locals(key string, value ...interface{}) (val interface{})

Locals makes it possible to pass interface{} values under string keys scoped to the request and therefore available to all following routes that match the request.

func (*Ctx) Location

func (ctx *Ctx) Location(path string)

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

func (*Ctx) Method

func (ctx *Ctx) Method(override ...string) string

Method contains a string corresponding to the HTTP method of the request: GET, POST, PUT and so on.

func (*Ctx) MultipartForm

func (ctx *Ctx) 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 (*Ctx) Next

func (ctx *Ctx) Next(err ...error)

Next executes the next method in the stack that matches the current route. You can pass an optional error for custom error handling.

func (*Ctx) OriginalURL added in v1.0.0

func (ctx *Ctx) 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 (*Ctx) Params

func (ctx *Ctx) 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 (*Ctx) Path

func (ctx *Ctx) Path(override ...string) string

Path returns the path part of the request URL. Optionally, you could override the path.

func (*Ctx) Protocol

func (ctx *Ctx) Protocol() string

Protocol contains the request protocol string: http or https for TLS requests.

func (*Ctx) Query

func (ctx *Ctx) 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 (*Ctx) QueryParser added in v1.13.0

func (ctx *Ctx) QueryParser(out interface{}) error

QueryParser binds the query string to a struct.

func (*Ctx) Range

func (ctx *Ctx) Range(size int) (rangeData Range, err error)

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

func (*Ctx) Redirect

func (ctx *Ctx) Redirect(location string, status ...int)

Redirect to the URL derived from the specified path, with specified status. If status is not specified, status defaults to 302 Found.

func (*Ctx) Render

func (ctx *Ctx) Render(name string, bind interface{}, layouts ...string) (err error)

Render a template with data and sends a text/html response. We support the following engines: html, amber, handlebars, mustache, pug

func (*Ctx) Route

func (ctx *Ctx) Route() *Route

Route returns the matched Route struct.

func (*Ctx) SaveFile added in v1.0.0

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

SaveFile saves any multipart file to disk.

func (*Ctx) Secure

func (ctx *Ctx) Secure() bool

Secure returns a boolean property, that is true, if a TLS connection is established.

func (*Ctx) Send

func (ctx *Ctx) Send(bodies ...interface{})

Send sets the HTTP response body. The input can be of any type, io.Reader is also supported.

func (*Ctx) SendBytes

func (ctx *Ctx) SendBytes(body []byte)

SendBytes sets the HTTP response body for []byte types without copying it. From this point onward the body argument must not be changed.

func (*Ctx) SendFile

func (ctx *Ctx) SendFile(file string, compress ...bool) error

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

func (ctx *Ctx) SendStatus(status int)

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 added in v1.10.2

func (ctx *Ctx) SendStream(stream io.Reader, size ...int)

SendStream sets response body stream and optional body size.

func (*Ctx) SendString

func (ctx *Ctx) SendString(body string)

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

func (*Ctx) Set

func (ctx *Ctx) Set(key string, val string)

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

func (*Ctx) Stale

func (ctx *Ctx) Stale() bool

Stale is not implemented yet, pull requests are welcome!

func (*Ctx) Status

func (ctx *Ctx) Status(status int) *Ctx

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

func (*Ctx) Subdomains

func (ctx *Ctx) Subdomains(offset ...int) []string

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

func (ctx *Ctx) Type(extension string, charset ...string) *Ctx

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

func (*Ctx) Vary

func (ctx *Ctx) 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 (*Ctx) Write

func (ctx *Ctx) Write(bodies ...interface{})

Write appends any input to the HTTP body response, io.Reader is also supported as input.

func (*Ctx) XHR added in v1.0.0

func (ctx *Ctx) 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 Error added in v1.11.0

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

Error represents an error that occurred while handling a request.

func NewError added in v1.11.0

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

NewError creates a new HTTPError instance.

func (*Error) Error added in v1.11.0

func (e *Error) Error() string

Error makes it compatible with `error` interface.

type Group added in v1.0.0

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

Group struct

func (*Group) Add added in v1.10.0

func (grp *Group) Add(method, path string, handlers ...Handler) Router

Add ...

func (*Group) All added in v1.0.0

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

All ...

func (*Group) Connect added in v1.0.0

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

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

func (*Group) Delete added in v1.0.0

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

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

func (*Group) Get added in v1.0.0

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

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 added in v1.0.0

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

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

func (*Group) Head added in v1.0.0

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

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) Options added in v1.0.0

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

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

func (*Group) Patch added in v1.0.0

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

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

func (*Group) Post added in v1.0.0

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

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 added in v1.0.0

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

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

func (*Group) Static added in v1.0.0

func (grp *Group) Static(prefix, root string, config ...Static) Router

Static ...

func (*Group) Trace added in v1.0.0

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

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

func (*Group) Use added in v1.0.0

func (grp *Group) Use(args ...interface{}) Router

Use registers a middleware route. Middleware matches requests beginning with the provided prefix. Providing a prefix is optional, it defaults to "/".

- group.Use(handler) - group.Use("/api", handler) - group.Use("/api", handler, handler)

type Handler added in v1.10.0

type Handler = func(*Ctx)

Handler defines a function to serve HTTP requests.

type Map added in v1.0.0

type Map map[string]interface{}

Map is a shortcut for map[string]interface{}, useful for JSON returns

type Range added in v1.8.1

type Range struct {
	Type   string
	Ranges []struct {
		Start int
		End   int
	}
}

Range data for ctx.Range

type Route added in v1.0.0

type Route struct {

	// Public fields
	Method   string    `json:"method"` // HTTP method
	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 Router added in v1.12.0

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
}

Router defines all router handle interface includes app and group router.

type Settings added in v1.0.0

type Settings struct {
	// ErrorHandler is executed when you pass an error in the Next(err) method.
	// This function is also executed when middleware.Recover() catches a panic
	// Default: func(ctx *Ctx, err error) {
	// 	code := StatusInternalServerError
	// 	if e, ok := err.(*Error); ok {
	// 		code = e.Code
	// 	}
	// 	ctx.Set(HeaderContentType, MIMETextPlainCharsetUTF8)
	// 	ctx.Status(code).SendString(err.Error())
	// }
	ErrorHandler func(*Ctx, error) `json:"-"`

	// 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.
	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.
	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 can also
	// work with urlencoded special characters.
	// 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"`

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

	// Max body size that the server accepts.
	// Default: 4 * 1024 * 1024
	BodyLimit int `json:"body_limit"`

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

	// 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_keep_alive"`

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

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

	// 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"`
}

Settings is a struct holding the server settings.

type Static added in v1.8.4

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

	// When set to true, enables byte range requests.
	// Optional. Default value false
	ByteRange bool

	// When set to true, enables directory browsing.
	// Optional. Default value false.
	Browse bool

	// The name of the index file for serving a directory.
	// Optional. Default value "index.html".
	Index string
}

Static defines configuration options when defining static assets.

type Views added in v1.11.1

type Views interface {
	Load() error
	Render(io.Writer, string, interface{}, ...string) error
}

Views is the interface that wraps the Render function.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL