package fasthttp

Import Path
	github.com/valyala/fasthttp (on go.dev)

Dependency Relation
	imports 40 packages, and imported by 2 packages

Involved Source Files args.go b2s_new.go brotli.go bytesconv.go bytesconv_64.go bytesconv_table.go client.go coarseTime.go compress.go cookie.go Package fasthttp provides fast HTTP server and client API. Fasthttp provides the following features: 1. Optimized for speed. Easily handles more than 100K qps and more than 1M concurrent keep-alive connections on modern hardware. 2. Optimized for low memory usage. 3. Easy 'Connection: Upgrade' support via RequestCtx.Hijack. 4. Server provides the following anti-DoS limits: - The number of concurrent connections. - The number of concurrent connections per client IP. - The number of requests per connection. - Request read timeout. - Response write timeout. - Maximum request header size. - Maximum request body size. - Maximum request execution time. - Maximum keep-alive connection lifetime. - Early filtering out non-GET requests. 5. A lot of additional useful info is exposed to request handler: - Server and client address. - Per-request logger. - Unique request id. - Request start time. - Connection start time. - Request sequence number for the current connection. 6. Client supports automatic retry on idempotent requests' failure. 7. Fasthttp API is designed with the ability to extend existing client and server implementations or to write custom client and server implementations from scratch. fs.go header.go headers.go http.go lbclient.go methods.go nocopy.go peripconn.go round2_64.go s2b_new.go server.go status.go stream.go streaming.go strings.go tcp.go tcpdialer.go timer.go tls.go uri.go uri_unix.go userdata.go workerpool.go
Package-Level Type Names (total 37)
/* sort by: | */
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. Add adds 'key=value' argument. Multiple values for the same key may be added. AddBytesK adds 'key=value' argument. Multiple values for the same key may be added. AddBytesKNoValue adds only 'key' as argument without the '='. Multiple values for the same key may be added. AddBytesKV adds 'key=value' argument. Multiple values for the same key may be added. AddBytesV adds 'key=value' argument. Multiple values for the same key may be added. AddNoValue adds only 'key' as argument without the '='. Multiple values for the same key may be added. AppendBytes appends query string to dst and returns the extended dst. CopyTo copies all args to dst. Del deletes argument with the given key from query args. DelBytes deletes argument with the given key from query args. GetBool returns boolean value for the given key. true is returned for "1", "t", "T", "true", "TRUE", "True", "y", "yes", "Y", "YES", "Yes", otherwise false is returned. GetUfloat returns ufloat value for the given key. GetUfloatOrZero returns ufloat value for the given key. Zero (0) is returned on error. GetUint returns uint value for the given key. GetUintOrZero returns uint value for the given key. Zero (0) is returned on error. Has returns true if the given key exists in Args. HasBytes returns true if the given key exists in Args. Len returns the number of query args. Parse parses the given string containing query args. ParseBytes parses the given b containing query args. Peek returns query arg value for the given key. The returned value is valid until the Args is reused or released (ReleaseArgs). Do not store references to the returned value. Make copies instead. PeekBytes returns query arg value for the given key. The returned value is valid until the Args is reused or released (ReleaseArgs). Do not store references to the returned value. Make copies instead. PeekMulti returns all the arg values for the given key. PeekMultiBytes returns all the arg values for the given key. QueryString returns query string for the args. The returned value is valid until the Args is reused or released (ReleaseArgs). Do not store references to the returned value. Make copies instead. Reset clears query args. Set sets 'key=value' argument. SetBytesK sets 'key=value' argument. SetBytesKNoValue sets 'key' argument. SetBytesKV sets 'key=value' argument. SetBytesV sets 'key=value' argument. SetNoValue sets only 'key' as argument without the '='. Only key in argument, like key1&key2 SetUint sets uint value for the given key. SetUintBytes sets uint value for the given key. Sort sorts Args by key and then value using 'f' as comparison function. For example args.Sort(bytes.Compare) String returns string representation of query args. VisitAll calls f for each existing arg. f must not retain references to key and value after returning. Make key and/or value copies if you need storing them after returning. WriteTo writes query string to w. WriteTo implements io.WriterTo interface. *Args : github.com/ChrisTrenkamp/goxpath/tree.Result *Args : github.com/opentracing/opentracing-go.TextMapWriter *Args : fmt.Stringer *Args : io.WriterTo func AcquireArgs() *Args func (*Request).PostArgs() *Args func (*RequestCtx).PostArgs() *Args func (*RequestCtx).QueryArgs() *Args func (*URI).QueryArgs() *Args func github.com/gofiber/fiber/v2.AcquireArgs() *fiber.Args func Post(dst []byte, url string, postArgs *Args) (statusCode int, body []byte, err error) func ReleaseArgs(a *Args) func (*Args).CopyTo(dst *Args) func (*Client).Post(dst []byte, url string, postArgs *Args) (statusCode int, body []byte, err error) func (*HostClient).Post(dst []byte, url string, postArgs *Args) (statusCode int, body []byte, err error) func github.com/gofiber/fiber/v2.ReleaseArgs(a *fiber.Args) func github.com/gofiber/fiber/v2.(*Agent).Form(args *fiber.Args) *fiber.Agent func github.com/gofiber/fiber/v2.(*Agent).MultipartForm(args *fiber.Args) *fiber.Agent
BalancingClient is the interface for clients, which may be passed to LBClient.Clients. ( BalancingClient) DoDeadline(req *Request, resp *Response, deadline time.Time) error ( BalancingClient) PendingRequests() int *HostClient *PipelineClient github.com/gofiber/fiber/v2.Agent func (*LBClient).AddClient(c BalancingClient) int
Client implements http client. Copying Client by value is prohibited. Create new instance instead. It is safe calling Client methods from concurrently running goroutines. The fields of a Client should not be changed while it is in use. ConfigureClient configures the fasthttp.HostClient. Connection pool strategy. Can be either LIFO or FIFO (default). Callback for establishing new connections to hosts. Default Dial is used if not set. Attempt to connect to both ipv4 and ipv6 addresses if set to true. This option is used only if default TCP dialer is used, i.e. if Dial is blank. By default client connects only to ipv4 addresses, since unfortunately ipv6 remains broken in many networks worldwide :) Header names are passed as-is without normalization if this option is set. Disabled header names' normalization may be useful only for proxying responses to other clients expecting case-sensitive header names. See https://github.com/valyala/fasthttp/issues/57 for details. By default request and response header names are normalized, i.e. The first letter and the first letters following dashes are uppercased, while all the other letters are lowercased. Examples: * HOST -> Host * content-type -> Content-Type * cONTENT-lenGTH -> Content-Length Path values are sent as-is without normalization Disabled path normalization may be useful for proxying incoming requests to servers that are expecting paths to be forwarded as-is. By default path values are normalized, i.e. extra slashes are removed, special characters are encoded. Keep-alive connections are closed after this duration. By default connection duration is unlimited. Maximum duration for waiting for a free connection. By default will not waiting, return ErrNoFreeConns immediately Maximum number of connections per each host which may be established. DefaultMaxConnsPerHost is used if not set. Maximum number of attempts for idempotent calls DefaultMaxIdemponentCallAttempts is used if not set. Idle keep-alive connections are closed after this duration. By default idle connections are closed after DefaultMaxIdleConnDuration. Maximum response body size. The client returns ErrBodyTooLarge if this limit is greater than 0 and response body is greater than the limit. By default response body size is unlimited. Client name. Used in User-Agent request header. Default client name is used if not set. NoDefaultUserAgentHeader when set to true, causes the default User-Agent header to be excluded from the Request. Per-connection buffer size for responses' reading. This also limits the maximum header size. Default buffer size is used if 0. Maximum duration for full response reading (including body). By default response read timeout is unlimited. RetryIf controls whether a retry should be attempted after an error. By default will use isIdempotent function StreamResponseBody enables response body streaming TLS config for https connections. Default TLS config is used if not set. Per-connection buffer size for requests' writing. Default buffer size is used if 0. Maximum duration for full request writing (including body). By default request write timeout is unlimited. CloseIdleConnections closes any connections which were previously connected from previous requests but are now sitting idle in a "keep-alive" state. It does not interrupt any connections currently in use. Do performs the given http request and fills the given http response. Request must contain at least non-zero RequestURI with full url (including scheme and host) or non-zero Host header + RequestURI. Client determines the server to be requested in the following order: - from RequestURI if it contains full url with scheme and host; - from Host header otherwise. Response is ignored if resp is nil. The function doesn't follow redirects. Use Get* for following redirects. ErrNoFreeConns is returned if all Client.MaxConnsPerHost connections to the requested host are busy. It is recommended obtaining req and resp via AcquireRequest and AcquireResponse in performance-critical code. DoDeadline performs the given request and waits for response until the given deadline. Request must contain at least non-zero RequestURI with full url (including scheme and host) or non-zero Host header + RequestURI. Client determines the server to be requested in the following order: - from RequestURI if it contains full url with scheme and host; - from Host header otherwise. The function doesn't follow redirects. Use Get* for following redirects. Response is ignored if resp is nil. ErrTimeout is returned if the response wasn't returned until the given deadline. Immediately returns ErrTimeout if the deadline has already been reached. ErrNoFreeConns is returned if all Client.MaxConnsPerHost connections to the requested host are busy. It is recommended obtaining req and resp via AcquireRequest and AcquireResponse in performance-critical code. DoRedirects performs the given http request and fills the given http response, following up to maxRedirectsCount redirects. When the redirect count exceeds maxRedirectsCount, ErrTooManyRedirects is returned. Request must contain at least non-zero RequestURI with full url (including scheme and host) or non-zero Host header + RequestURI. Client determines the server to be requested in the following order: - from RequestURI if it contains full url with scheme and host; - from Host header otherwise. Response is ignored if resp is nil. ErrNoFreeConns is returned if all DefaultMaxConnsPerHost connections to the requested host are busy. It is recommended obtaining req and resp via AcquireRequest and AcquireResponse in performance-critical code. DoTimeout performs the given request and waits for response during the given timeout duration. Request must contain at least non-zero RequestURI with full url (including scheme and host) or non-zero Host header + RequestURI. Client determines the server to be requested in the following order: - from RequestURI if it contains full url with scheme and host; - from Host header otherwise. The function doesn't follow redirects. Use Get* for following redirects. Response is ignored if resp is nil. ErrTimeout is returned if the response wasn't returned during the given timeout. Immediately returns ErrTimeout if timeout value is negative. ErrNoFreeConns is returned if all Client.MaxConnsPerHost connections to the requested host are busy. It is recommended obtaining req and resp via AcquireRequest and AcquireResponse in performance-critical code. Get returns the status code and body of url. The contents of dst will be replaced by the body and returned, if the dst is too small a new slice will be allocated. The function follows redirects. Use Do* for manually handling redirects. GetDeadline returns the status code and body of url. The contents of dst will be replaced by the body and returned, if the dst is too small a new slice will be allocated. The function follows redirects. Use Do* for manually handling redirects. ErrTimeout error is returned if url contents couldn't be fetched until the given deadline. GetTimeout returns the status code and body of url. The contents of dst will be replaced by the body and returned, if the dst is too small a new slice will be allocated. The function follows redirects. Use Do* for manually handling redirects. ErrTimeout error is returned if url contents couldn't be fetched during the given timeout. Post sends POST request to the given url with the given POST arguments. The contents of dst will be replaced by the body and returned, if the dst is too small a new slice will be allocated. The function follows redirects. Use Do* for manually handling redirects. Empty POST body is sent if postArgs is nil.
ConnPoolStrategyType define strategy of connection pool enqueue/dequeue const FIFO const LIFO
A ConnState represents the state of a client connection to a server. It's used by the optional Server.ConnState hook. ( ConnState) String() string ConnState : github.com/ChrisTrenkamp/goxpath/tree.Result ConnState : fmt.Stringer const StateActive const StateClosed const StateHijacked const StateIdle const StateNew
CookieSameSite is an enum for the mode in which the SameSite flag should be set for the given cookie. See https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00 for details. func (*Cookie).SameSite() CookieSameSite func (*Cookie).SetSameSite(mode CookieSameSite) const CookieSameSiteDefaultMode const CookieSameSiteDisabled const CookieSameSiteLaxMode const CookieSameSiteNoneMode const CookieSameSiteStrictMode
DialFunc must establish connection to addr. There is no need in establishing TLS (SSL) connection for https. The client automatically converts connection to TLS if HostClient.IsTLS is set. TCP address passed to DialFunc always contains host and port. Example TCP addr values: - foobar.com:80 - foobar.com:443 - foobar.com:8080
ErrBodyStreamWritePanic is returned when panic happens during writing body stream. ( ErrBodyStreamWritePanic) Error() builtin.string ErrBodyStreamWritePanic : error
ErrBrokenChunk is returned when server receives a broken chunked body (Transfer-Encoding: chunked). ( ErrBrokenChunk) Error() builtin.string ErrBrokenChunk : error
ErrNothingRead is returned when a keep-alive connection is closed, either because the remote closed it or because of a read timeout. ( ErrNothingRead) Error() builtin.string ErrNothingRead : error
ErrSmallBuffer is returned when the provided buffer size is too small for reading request and/or response headers. ReadBufferSize value from Server or clients should reduce the number of such errors. ( ErrSmallBuffer) Error() builtin.string ErrSmallBuffer : error
( EscapeError) Error() string EscapeError : error
type FormValueFunc (func)
FS represents settings for request handler serving static files from the local filesystem. It is prohibited copying FS values. Create new values instead. Enables byte range requests if set to true. Byte range requests are disabled by default. AllowEmptyRoot controls what happens when Root is empty. When false (default) it will default to the current working directory. An empty root is mostly useful when you want to use absolute paths on windows that are on different filesystems. On linux setting your Root to "/" already allows you to use absolute paths on any filesystem. Expiration duration for inactive file handlers. FSHandlerCacheDuration is used by default. If CleanStop is set, the channel can be closed to stop the cleanup handlers for the FS RequestHandlers created with NewRequestHandler. NEVER close this channel while the handler is still being used! Transparently compresses responses if set to true. The server tries minimizing CPU usage by caching compressed files. It adds CompressedFileSuffix suffix to the original file name and tries saving the resulting compressed file under the new file name. So it is advisable to give the server write access to Root and to all inner folders in order to minimize CPU usage when serving compressed responses. Transparent compression is disabled by default. Uses brotli encoding and fallbacks to gzip in responses if set to true, uses gzip if set to false. This value has sense only if Compress is set. Brotli encoding is disabled by default. Path to the compressed root directory to serve files from. If this value is empty, Root is used. Suffix to add to the name of cached compressed file. This value has sense only if Compress is set. FSCompressedFileSuffix is used by default. Suffixes list to add to compressedFileSuffix depending on encoding This value has sense only if Compress is set. FSCompressedFileSuffixes is used by default. Index pages for directories without files matching IndexNames are automatically generated if set. Directory index generation may be quite slow for directories with many files (more than 1K), so it is discouraged enabling index pages' generation for such directories. By default index pages aren't generated. List of index file names to try opening during directory access. For example: * index.html * index.htm * my-super-index.xml By default the list is empty. PathNotFound fires when file is not found in filesystem this functions tries to replace "Cannot open requested path" server response giving to the programmer the control of server flow. By default PathNotFound returns "Cannot open requested path" Path rewriting function. By default request path is not modified. Path to the root directory to serve files from. NewRequestHandler returns new request handler with the given FS settings. The returned handler caches requested file handles for FS.CacheDuration. Make sure your program has enough 'max open files' limit aka 'ulimit -n' if FS.Root folder contains many files. Do not create multiple request handlers from a single FS instance - just reuse a single request handler.
HijackHandler must process the hijacked connection c. If KeepHijackedConns is disabled, which is by default, the connection c is automatically closed after returning from HijackHandler. The connection c must not be used after returning from the handler, if KeepHijackedConns is disabled. When KeepHijackedConns enabled, fasthttp will not Close() the connection, you must do it when you need it. You must not use c in any way after calling Close(). func (*RequestCtx).Hijack(handler HijackHandler)
HostClient balances http requests among hosts listed in Addr. HostClient may be used for balancing load among multiple upstream hosts. While multiple addresses passed to HostClient.Addr may be used for balancing load among them, it would be better using LBClient instead, since HostClient may unevenly balance load among upstream hosts. It is forbidden copying HostClient instances. Create new instances instead. It is safe calling HostClient methods from concurrently running goroutines. Comma-separated list of upstream HTTP server host addresses, which are passed to Dial in a round-robin manner. Each address may contain port if default dialer is used. For example, - foobar.com:80 - foobar.com:443 - foobar.com:8080 Connection pool strategy. Can be either LIFO or FIFO (default). Callback for establishing new connection to the host. Default Dial is used if not set. Attempt to connect to both ipv4 and ipv6 host addresses if set to true. This option is used only if default TCP dialer is used, i.e. if Dial is blank. By default client connects only to ipv4 addresses, since unfortunately ipv6 remains broken in many networks worldwide :) Header names are passed as-is without normalization if this option is set. Disabled header names' normalization may be useful only for proxying responses to other clients expecting case-sensitive header names. See https://github.com/valyala/fasthttp/issues/57 for details. By default request and response header names are normalized, i.e. The first letter and the first letters following dashes are uppercased, while all the other letters are lowercased. Examples: * HOST -> Host * content-type -> Content-Type * cONTENT-lenGTH -> Content-Length Path values are sent as-is without normalization Disabled path normalization may be useful for proxying incoming requests to servers that are expecting paths to be forwarded as-is. By default path values are normalized, i.e. extra slashes are removed, special characters are encoded. Whether to use TLS (aka SSL or HTTPS) for host connections. Keep-alive connections are closed after this duration. By default connection duration is unlimited. Maximum duration for waiting for a free connection. By default will not waiting, return ErrNoFreeConns immediately Maximum number of connections which may be established to all hosts listed in Addr. You can change this value while the HostClient is being used with HostClient.SetMaxConns(value) DefaultMaxConnsPerHost is used if not set. Maximum number of attempts for idempotent calls DefaultMaxIdemponentCallAttempts is used if not set. Idle keep-alive connections are closed after this duration. By default idle connections are closed after DefaultMaxIdleConnDuration. Maximum response body size. The client returns ErrBodyTooLarge if this limit is greater than 0 and response body is greater than the limit. By default response body size is unlimited. Client name. Used in User-Agent request header. NoDefaultUserAgentHeader when set to true, causes the default User-Agent header to be excluded from the Request. Per-connection buffer size for responses' reading. This also limits the maximum header size. Default buffer size is used if 0. Maximum duration for full response reading (including body). By default response read timeout is unlimited. RetryIf controls whether a retry should be attempted after an error. By default will use isIdempotent function Will not log potentially sensitive content in error logs This option is useful for servers that handle sensitive data in the request/response. Client logs full errors by default. StreamResponseBody enables response body streaming Optional TLS config. Transport defines a transport-like mechanism that wraps every request/response. Per-connection buffer size for requests' writing. Default buffer size is used if 0. Maximum duration for full request writing (including body). By default request write timeout is unlimited. CloseIdleConnections closes any connections which were previously connected from previous requests but are now sitting idle in a "keep-alive" state. It does not interrupt any connections currently in use. ConnsCount returns connection count of HostClient Do performs the given http request and sets the corresponding response. Request must contain at least non-zero RequestURI with full url (including scheme and host) or non-zero Host header + RequestURI. The function doesn't follow redirects. Use Get* for following redirects. Response is ignored if resp is nil. ErrNoFreeConns is returned if all HostClient.MaxConns connections to the host are busy. It is recommended obtaining req and resp via AcquireRequest and AcquireResponse in performance-critical code. DoDeadline performs the given request and waits for response until the given deadline. Request must contain at least non-zero RequestURI with full url (including scheme and host) or non-zero Host header + RequestURI. The function doesn't follow redirects. Use Get* for following redirects. Response is ignored if resp is nil. ErrTimeout is returned if the response wasn't returned until the given deadline. Immediately returns ErrTimeout if the deadline has already been reached. ErrNoFreeConns is returned if all HostClient.MaxConns connections to the host are busy. It is recommended obtaining req and resp via AcquireRequest and AcquireResponse in performance-critical code. DoRedirects performs the given http request and fills the given http response, following up to maxRedirectsCount redirects. When the redirect count exceeds maxRedirectsCount, ErrTooManyRedirects is returned. Request must contain at least non-zero RequestURI with full url (including scheme and host) or non-zero Host header + RequestURI. Client determines the server to be requested in the following order: - from RequestURI if it contains full url with scheme and host; - from Host header otherwise. Response is ignored if resp is nil. ErrNoFreeConns is returned if all DefaultMaxConnsPerHost connections to the requested host are busy. It is recommended obtaining req and resp via AcquireRequest and AcquireResponse in performance-critical code. DoTimeout performs the given request and waits for response during the given timeout duration. Request must contain at least non-zero RequestURI with full url (including scheme and host) or non-zero Host header + RequestURI. The function doesn't follow redirects. Use Get* for following redirects. Response is ignored if resp is nil. ErrTimeout is returned if the response wasn't returned during the given timeout. Immediately returns ErrTimeout if timeout value is negative. ErrNoFreeConns is returned if all HostClient.MaxConns connections to the host are busy. It is recommended obtaining req and resp via AcquireRequest and AcquireResponse in performance-critical code. Get returns the status code and body of url. The contents of dst will be replaced by the body and returned, if the dst is too small a new slice will be allocated. The function follows redirects. Use Do* for manually handling redirects. GetDeadline returns the status code and body of url. The contents of dst will be replaced by the body and returned, if the dst is too small a new slice will be allocated. The function follows redirects. Use Do* for manually handling redirects. ErrTimeout error is returned if url contents couldn't be fetched until the given deadline. GetTimeout returns the status code and body of url. The contents of dst will be replaced by the body and returned, if the dst is too small a new slice will be allocated. The function follows redirects. Use Do* for manually handling redirects. ErrTimeout error is returned if url contents couldn't be fetched during the given timeout. LastUseTime returns time the client was last used PendingRequests returns the current number of requests the client is executing. This function may be used for balancing load among multiple HostClient instances. Post sends POST request to the given url with the given POST arguments. The contents of dst will be replaced by the body and returned, if the dst is too small a new slice will be allocated. The function follows redirects. Use Do* for manually handling redirects. Empty POST body is sent if postArgs is nil. SetMaxConns sets up the maximum number of connections which may be established to all hosts listed in Addr. *HostClient : BalancingClient func RoundTripper.RoundTrip(hc *HostClient, req *Request, resp *Response) (retry bool, err error)
( InvalidHostError) Error() string InvalidHostError : error
LBClient balances requests among available LBClient.Clients. It has the following features: - Balances load among available clients using 'least loaded' + 'least total' hybrid technique. - Dynamically decreases load on unhealthy clients. It is forbidden copying LBClient instances. Create new instances instead. It is safe calling LBClient methods from concurrently running goroutines. Clients must contain non-zero clients list. Incoming requests are balanced among these clients. HealthCheck is a callback called after each request. The request, response and the error returned by the client is passed to HealthCheck, so the callback may determine whether the client is healthy. Load on the current client is decreased if HealthCheck returns false. By default HealthCheck returns false if err != nil. Timeout is the request timeout used when calling LBClient.Do. DefaultLBClientTimeout is used by default. AddClient adds a new client to the balanced clients returns the new total number of clients Do calculates timeout using LBClient.Timeout and calls DoTimeout on the least loaded client. DoDeadline calls DoDeadline on the least loaded client DoTimeout calculates deadline and calls DoDeadline on the least loaded client RemoveClients removes clients using the provided callback if rc returns true, the passed client will be removed returns the new total number of clients
Logger is used for logging formatted messages. ( Logger) Printf(string, ...interface{}) gorm.io/gorm/logger.Writer (interface) *log.Logger Logger : gorm.io/gorm/logger.Writer func (*RequestCtx).Logger() Logger func (*RequestCtx).Init(req *Request, remoteAddr net.Addr, logger Logger) func (*RequestCtx).Init2(conn net.Conn, logger Logger, reduceMemoryUsage bool)
PathRewriteFunc must return new request path based on arbitrary ctx info such as ctx.Path(). Path rewriter is used in FS for translating the current request to the local filesystem path relative to FS.Root. The returned path must not contain '/../' substrings due to security reasons, since such paths may refer files outside FS.Root. The returned path may refer to ctx members. For example, ctx.Path(). func NewPathPrefixStripper(prefixSize int) PathRewriteFunc func NewPathSlashesStripper(slashesCount int) PathRewriteFunc func NewVHostPathRewriter(slashesCount int) PathRewriteFunc
PipelineClient pipelines requests over a limited set of concurrent connections to the given Addr. This client may be used in highly loaded HTTP-based RPC systems for reducing context switches and network level overhead. See https://en.wikipedia.org/wiki/HTTP_pipelining for details. It is forbidden copying PipelineClient instances. Create new instances instead. It is safe calling PipelineClient methods from concurrently running goroutines. Address of the host to connect to. Callback for connection establishing to the host. Default Dial is used if not set. Attempt to connect to both ipv4 and ipv6 host addresses if set to true. This option is used only if default TCP dialer is used, i.e. if Dial is blank. By default client connects only to ipv4 addresses, since unfortunately ipv6 remains broken in many networks worldwide :) Response header names are passed as-is without normalization if this option is set. Disabled header names' normalization may be useful only for proxying responses to other clients expecting case-sensitive header names. See https://github.com/valyala/fasthttp/issues/57 for details. By default request and response header names are normalized, i.e. The first letter and the first letters following dashes are uppercased, while all the other letters are lowercased. Examples: * HOST -> Host * content-type -> Content-Type * cONTENT-lenGTH -> Content-Length Path values are sent as-is without normalization Disabled path normalization may be useful for proxying incoming requests to servers that are expecting paths to be forwarded as-is. By default path values are normalized, i.e. extra slashes are removed, special characters are encoded. Whether to use TLS (aka SSL or HTTPS) for host connections. Logger for logging client errors. By default standard logger from log package is used. The maximum delay before sending pipelined requests as a batch to the server. By default requests are sent immediately to the server. The maximum number of concurrent connections to the Addr. A single connection is used by default. Idle connection to the host is closed after this duration. By default idle connection is closed after DefaultMaxIdleConnDuration. The maximum number of pending pipelined requests over a single connection to Addr. DefaultMaxPendingRequests is used by default. PipelineClient name. Used in User-Agent request header. NoDefaultUserAgentHeader when set to true, causes the default User-Agent header to be excluded from the Request. Buffer size for responses' reading. This also limits the maximum header size. Default buffer size is used if 0. Maximum duration for full response reading (including body). By default response read timeout is unlimited. Optional TLS config. Buffer size for requests' writing. Default buffer size is used if 0. Maximum duration for full request writing (including body). By default request write timeout is unlimited. Do performs the given http request and sets the corresponding response. Request must contain at least non-zero RequestURI with full url (including scheme and host) or non-zero Host header + RequestURI. The function doesn't follow redirects. Use Get* for following redirects. Response is ignored if resp is nil. It is recommended obtaining req and resp via AcquireRequest and AcquireResponse in performance-critical code. DoDeadline performs the given request and waits for response until the given deadline. Request must contain at least non-zero RequestURI with full url (including scheme and host) or non-zero Host header + RequestURI. The function doesn't follow redirects. Response is ignored if resp is nil. ErrTimeout is returned if the response wasn't returned until the given deadline. It is recommended obtaining req and resp via AcquireRequest and AcquireResponse in performance-critical code. DoTimeout performs the given request and waits for response during the given timeout duration. Request must contain at least non-zero RequestURI with full url (including scheme and host) or non-zero Host header + RequestURI. The function doesn't follow redirects. Response is ignored if resp is nil. ErrTimeout is returned if the response wasn't returned during the given timeout. It is recommended obtaining req and resp via AcquireRequest and AcquireResponse in performance-critical code. PendingRequests returns the current number of pending requests pipelined to the server. This number may exceed MaxPendingRequests*MaxConns by up to two times, since each connection to the server may keep up to MaxPendingRequests requests in the queue before sending them to the server. This function may be used for balancing load among multiple PipelineClient instances. *PipelineClient : BalancingClient
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. Request header Copying Header by value is forbidden. Use pointer to Header instead. Use Host header (request.Header.SetHost) instead of the host from SetRequestURI, SetHost, or URI().SetHost AppendBody appends p to request body. It is safe re-using p after the function returns. AppendBodyString appends s to request body. Body returns request body. The returned value is valid until the request is released, either though ReleaseRequest or your request handler returning. Do not store references to returned value. Make copies instead. BodyGunzip returns un-gzipped body data. This method may be used if the request header contains 'Content-Encoding: gzip' for reading un-gzipped body. Use Body for reading gzipped request body. BodyInflate returns inflated body data. This method may be used if the response header contains 'Content-Encoding: deflate' for reading inflated request body. Use Body for reading deflated request body. BodyStream returns io.Reader You must CloseBodyStream or ReleaseRequest after you use it. BodyUnbrotli returns un-brotlied body data. This method may be used if the request header contains 'Content-Encoding: br' for reading un-brotlied body. Use Body for reading brotlied request body. BodyUncompressed returns body data and if needed decompress it from gzip, deflate or Brotli. This method may be used if the response header contains 'Content-Encoding' for reading uncompressed request body. Use Body for reading the raw request body. BodyWriteTo writes request body to w. BodyWriter returns writer for populating request body. (*Request) CloseBodyStream() error ConnectionClose returns true if 'Connection: close' header is set. ContinueReadBody reads request body if request header contains 'Expect: 100-continue'. The caller must send StatusContinue response before calling this method. If maxBodySize > 0 and the body size exceeds maxBodySize, then ErrBodyTooLarge is returned. ContinueReadBodyStream reads request body if request header contains 'Expect: 100-continue'. The caller must send StatusContinue response before calling this method. If maxBodySize > 0 and the body size exceeds maxBodySize, then ErrBodyTooLarge is returned. CopyTo copies req contents to dst except of body stream. Host returns the host for the given request. IsBodyStream returns true if body is set via SetBodyStream* MayContinue returns true if the request contains 'Expect: 100-continue' header. The caller must do one of the following actions if MayContinue returns true: - Either send StatusExpectationFailed response if request headers don't satisfy the caller. - Or send StatusContinue response before reading request body with ContinueReadBody. - Or close the connection. MultipartForm returns request's multipart form. Returns ErrNoMultipartForm if request's Content-Type isn't 'multipart/form-data'. RemoveMultipartFormFiles must be called after returned multipart form is processed. PostArgs returns POST arguments. Read reads request (including body) from the given r. RemoveMultipartFormFiles or Reset must be called after reading multipart/form-data request in order to delete temporarily uploaded files. If MayContinue returns true, the caller must: - Either send StatusExpectationFailed response if request headers don't satisfy the caller. - Or send StatusContinue response before reading request body with ContinueReadBody. - Or close the connection. io.EOF is returned if r is closed before reading the first header byte. ReadBody reads request body from the given r, limiting the body size. If maxBodySize > 0 and the body size exceeds maxBodySize, then ErrBodyTooLarge is returned. ReadLimitBody reads request from the given r, limiting the body size. If maxBodySize > 0 and the body size exceeds maxBodySize, then ErrBodyTooLarge is returned. RemoveMultipartFormFiles or Reset must be called after reading multipart/form-data request in order to delete temporarily uploaded files. If MayContinue returns true, the caller must: - Either send StatusExpectationFailed response if request headers don't satisfy the caller. - Or send StatusContinue response before reading request body with ContinueReadBody. - Or close the connection. io.EOF is returned if r is closed before reading the first header byte. ReleaseBody retires the request body if it is greater than "size" bytes. This permits GC to reclaim the large buffer. If used, must be before ReleaseRequest. Use this method only if you really understand how it works. The majority of workloads don't need this method. RemoveMultipartFormFiles removes multipart/form-data temporary files associated with the request. RequestURI returns request's URI. Reset clears request contents. ResetBody resets request body. SetBody sets request body. It is safe re-using body argument after the function returns. SetBodyRaw sets response body, but without copying it. From this point onward the body argument must not be changed. SetBodyStream 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. See also SetBodyStreamWriter. SetBodyStreamWriter registers the given sw for populating request body. This function may be used in the following cases: - if request body is too big (more than 10MB). - if request body is streamed from slow external sources. - if request body must be streamed to the server in chunks (aka `http client push` or `chunked transfer-encoding`). Note that GET and HEAD requests cannot have body. See also SetBodyStream. SetBodyString sets request body. SetConnectionClose sets 'Connection: close' header. SetHost sets host for the request. SetHostBytes sets host for the request. SetRequestURI sets RequestURI. SetRequestURIBytes sets RequestURI. SetTimeout sets timeout for the request. req.SetTimeout(t); c.Do(&req, &resp) is equivalent to c.DoTimeout(&req, &resp, t) SetURI initializes request URI Use this method if a single URI may be reused across multiple requests. Otherwise, you can just use SetRequestURI() and it will be parsed as new URI. The URI is copied and can be safely modified later. String returns request representation. Returns error message instead of request representation on error. Use Write instead of String for performance-critical code. SwapBody swaps request body with the given body and returns the previous request body. It is forbidden to use the body passed to SwapBody after the function returns. URI returns request URI Write writes request to w. Write doesn't flush request to w for performance reasons. See also WriteTo. WriteTo writes request to w. It implements io.WriterTo. *Request : github.com/ChrisTrenkamp/goxpath/tree.Result *Request : fmt.Stringer *Request : io.WriterTo func AcquireRequest() *Request func github.com/gofiber/fiber/v2.(*Agent).Request() *fiber.Request func github.com/gofiber/fiber/v2.(*Ctx).Request() *Request func Do(req *Request, resp *Response) error func DoDeadline(req *Request, resp *Response, deadline time.Time) error func DoRedirects(req *Request, resp *Response, maxRedirectsCount int) error func DoTimeout(req *Request, resp *Response, timeout time.Duration) error func ReleaseRequest(req *Request) func BalancingClient.DoDeadline(req *Request, resp *Response, deadline time.Time) error func (*Client).Do(req *Request, resp *Response) error func (*Client).DoDeadline(req *Request, resp *Response, deadline time.Time) error func (*Client).DoRedirects(req *Request, resp *Response, maxRedirectsCount int) error func (*Client).DoTimeout(req *Request, resp *Response, timeout time.Duration) error func (*HostClient).Do(req *Request, resp *Response) error func (*HostClient).DoDeadline(req *Request, resp *Response, deadline time.Time) error func (*HostClient).DoRedirects(req *Request, resp *Response, maxRedirectsCount int) error func (*HostClient).DoTimeout(req *Request, resp *Response, timeout time.Duration) error func (*LBClient).Do(req *Request, resp *Response) error func (*LBClient).DoDeadline(req *Request, resp *Response, deadline time.Time) error func (*LBClient).DoTimeout(req *Request, resp *Response, timeout time.Duration) error func (*PipelineClient).Do(req *Request, resp *Response) error func (*PipelineClient).DoDeadline(req *Request, resp *Response, deadline time.Time) error func (*PipelineClient).DoTimeout(req *Request, resp *Response, timeout time.Duration) error func (*Request).CopyTo(dst *Request) func (*RequestCtx).Init(req *Request, remoteAddr net.Addr, logger Logger) func RoundTripper.RoundTrip(hc *HostClient, req *Request, resp *Response) (retry bool, err error)
RequestConfig configure the per request deadline and body limits Maximum request body size. a zero value means that default values will be honored ReadTimeout is the maximum duration for reading the entire request body. a zero value means that default values will be honored WriteTimeout is the maximum duration before timing out writes of the response. a zero value means that default values will be honored
RequestCtx contains incoming request and manages outgoing response. It is forbidden copying RequestCtx instances. RequestHandler should avoid holding references to incoming RequestCtx and/or its members after the return. If holding RequestCtx references after the return is unavoidable (for instance, ctx is passed to a separate goroutine and ctx lifetime cannot be controlled), then the RequestHandler MUST call ctx.TimeoutError() before return. It is unsafe modifying/reading RequestCtx instance from concurrently running goroutines. The only exception is TimeoutError*, which may be called while other goroutines accessing RequestCtx. Incoming request. Copying Request by value is forbidden. Use pointer to Request instead. Outgoing response. Copying Response by value is forbidden. Use pointer to Response instead. Conn returns a reference to the underlying net.Conn. WARNING: Only use this method if you know what you are doing! Reading from or writing to the returned connection will end badly! ConnID returns unique connection ID. This ID may be used to match distinct requests to the same incoming connection. ConnRequestNum returns request sequence number for the current connection. Sequence starts with 1. ConnTime returns the time the server started serving the connection the current request came from. Deadline returns the time when work done on behalf of this context should be canceled. Deadline returns ok==false when no deadline is set. Successive calls to Deadline return the same results. This method always returns 0, false and is only present to make RequestCtx implement the context interface. Done returns a channel that's closed when work done on behalf of this context should be canceled. Done may return nil if this context can never be canceled. Successive calls to Done return the same value. Note: Because creating a new channel for every request is just too expensive, so RequestCtx.s.done is only closed when the server is shutting down Err returns a non-nil error value after Done is closed, successive calls to Err return the same error. If Done is not yet closed, Err returns nil. If Done is closed, Err returns a non-nil error explaining why: Canceled if the context was canceled (via server Shutdown) or DeadlineExceeded if the context's deadline passed. Note: Because creating a new channel for every request is just too expensive, so RequestCtx.s.done is only closed when the server is shutting down Error sets response status code to the given value and sets response body to the given message. Warning: this will reset the response headers and body already set! FormFile returns uploaded file associated with the given multipart form key. The file is automatically deleted after returning from RequestHandler, so either move or copy uploaded file into new place if you want retaining it. Use SaveMultipartFile function for permanently saving uploaded file. The returned file header is valid until your request handler returns. FormValue returns form value associated with the given key. The value is searched in the following places: - Query string. - POST or PUT body. There are more fine-grained methods for obtaining form values: - QueryArgs for obtaining values from query string. - PostArgs for obtaining values from POST or PUT body. - MultipartForm for obtaining values from multipart form. - FormFile for obtaining uploaded files. The returned value is valid until your request handler returns. Hijack registers the given handler for connection hijacking. The handler is called after returning from RequestHandler and sending http response. The current connection is passed to the handler. The connection is automatically closed after returning from the handler. The server skips calling the handler in the following cases: - 'Connection: close' header exists in either request or response. - Unexpected error during response writing to the connection. The server stops processing requests from hijacked connections. Server limits such as Concurrency, ReadTimeout, WriteTimeout, etc. aren't applied to hijacked connections. The handler must not retain references to ctx members. Arbitrary 'Connection: Upgrade' protocols may be implemented with HijackHandler. For instance, - WebSocket ( https://en.wikipedia.org/wiki/WebSocket ) - HTTP/2.0 ( https://en.wikipedia.org/wiki/HTTP/2 ) HijackSetNoResponse changes the behavior of hijacking a request. If HijackSetNoResponse is called with false fasthttp will send a response to the client before calling the HijackHandler (default). If HijackSetNoResponse is called with true no response is send back before calling the HijackHandler supplied in the Hijack function. Hijacked returns true after Hijack is called. Host returns requested host. The returned bytes are valid until your request handler returns. ID returns unique ID of the request. IfModifiedSince returns true if lastModified exceeds 'If-Modified-Since' value from the request header. The function returns true also 'If-Modified-Since' request header is missing. Init prepares ctx for passing to RequestHandler. remoteAddr and logger are optional. They are used by RequestCtx.Logger(). This function is intended for custom Server implementations. Init2 prepares ctx for passing to RequestHandler. conn is used only for determining local and remote addresses. This function is intended for custom Server implementations. See https://github.com/valyala/httpteleport for details. IsBodyStream returns true if response body is set via SetBodyStream*. IsConnect returns true if request method is CONNECT. IsDelete returns true if request method is DELETE. IsGet returns true if request method is GET. IsHead returns true if request method is HEAD. IsOptions returns true if request method is OPTIONS. IsPatch returns true if request method is PATCH. IsPost returns true if request method is POST. IsPut returns true if request method is PUT. IsTLS returns true if the underlying connection is tls.Conn. tls.Conn is an encrypted connection (aka SSL, HTTPS). IsTrace returns true if request method is TRACE. LastTimeoutErrorResponse returns the last timeout response set via TimeoutError* call. This function is intended for custom server implementations. LocalAddr returns server address for the given request. Always returns non-nil result. LocalIP returns the server ip the request came to. Always returns non-nil result. Logger returns logger, which may be used for logging arbitrary request-specific messages inside RequestHandler. Each message logged via returned logger contains request-specific information such as request id, request duration, local address, remote address, request method and request url. It is safe re-using returned logger for logging multiple messages for the current request. The returned logger is valid until your request handler returns. Method return request method. Returned value is valid until your request handler returns. MultipartForm returns request's multipart form. Returns ErrNoMultipartForm if request's content-type isn't 'multipart/form-data'. All uploaded temporary files are automatically deleted after returning from RequestHandler. Either move or copy uploaded files into new place if you want retaining them. Use SaveMultipartFile function for permanently saving uploaded file. The returned form is valid until your request handler returns. See also FormFile and FormValue. NotFound resets response and sets '404 Not Found' response status code. NotModified resets response and sets '304 Not Modified' response status code. Path returns requested path. The returned bytes are valid until your request handler returns. PostArgs returns POST arguments. It doesn't return query arguments from RequestURI - use QueryArgs for this. See also QueryArgs, FormValue and FormFile. These args are valid until your request handler returns. PostBody returns POST request body. The returned bytes are valid until your request handler returns. QueryArgs returns query arguments from RequestURI. It doesn't return POST'ed arguments - use PostArgs() for this. See also PostArgs, FormValue and FormFile. These args are valid until your request handler returns. Redirect sets 'Location: uri' response header and sets the given statusCode. statusCode must have one of the following values: - StatusMovedPermanently (301) - StatusFound (302) - StatusSeeOther (303) - StatusTemporaryRedirect (307) - StatusPermanentRedirect (308) All other statusCode values are replaced by StatusFound (302). The redirect uri may be either absolute or relative to the current request uri. Fasthttp will always send an absolute uri back to the client. To send a relative uri you can use the following code: strLocation = []byte("Location") // Put this with your top level var () declarations. ctx.Response.Header.SetCanonical(strLocation, "/relative?uri") ctx.Response.SetStatusCode(fasthttp.StatusMovedPermanently) RedirectBytes sets 'Location: uri' response header and sets the given statusCode. statusCode must have one of the following values: - StatusMovedPermanently (301) - StatusFound (302) - StatusSeeOther (303) - StatusTemporaryRedirect (307) - StatusPermanentRedirect (308) All other statusCode values are replaced by StatusFound (302). The redirect uri may be either absolute or relative to the current request uri. Fasthttp will always send an absolute uri back to the client. To send a relative uri you can use the following code: strLocation = []byte("Location") // Put this with your top level var () declarations. ctx.Response.Header.SetCanonical(strLocation, "/relative?uri") ctx.Response.SetStatusCode(fasthttp.StatusMovedPermanently) Referer returns request referer. The returned bytes are valid until your request handler returns. RemoteAddr returns client address for the given request. Always returns non-nil result. RemoteIP returns the client ip the request came from. Always returns non-nil result. RemoveUserValue removes the given key and the value under it in ctx. RemoveUserValueBytes removes the given key and the value under it in ctx. (*RequestCtx) RequestBodyStream() io.Reader RequestURI returns RequestURI. The returned bytes are valid until your request handler returns. ResetBody resets response body contents. ResetUserValues allows to reset user values from Request Context SendFile sends local file contents from the given path as response body. This is a shortcut to ServeFile(ctx, path). SendFile logs all the errors via ctx.Logger. See also ServeFile, FSHandler and FS. WARNING: do not pass any user supplied paths to this function! WARNING: if path is based on user input users will be able to request any file on your filesystem! Use fasthttp.FS with a sane Root instead. SendFileBytes sends local file contents from the given path as response body. This is a shortcut to ServeFileBytes(ctx, path). SendFileBytes logs all the errors via ctx.Logger. See also ServeFileBytes, FSHandler and FS. WARNING: do not pass any user supplied paths to this function! WARNING: if path is based on user input users will be able to request any file on your filesystem! Use fasthttp.FS with a sane Root instead. SetBody sets response body to the given value. It is safe re-using body argument after the function returns. SetBodyStream sets response body stream and, optionally body size. bodyStream.Close() is called after finishing reading all body data if it implements io.Closer. If bodySize is >= 0, then bodySize bytes must be provided by bodyStream before returning io.EOF. If bodySize < 0, then bodyStream is read until io.EOF. See also SetBodyStreamWriter. SetBodyStreamWriter registers the given stream writer for populating response body. Access to RequestCtx and/or its members is forbidden from sw. This function may be used in the following cases: - if response body is too big (more than 10MB). - if response body is streamed from slow external sources. - if response body must be streamed to the client in chunks. (aka `http server push`). SetBodyString sets response body to the given value. SetConnectionClose sets 'Connection: close' response header and closes connection after the RequestHandler returns. SetContentType sets response Content-Type. SetContentTypeBytes sets response Content-Type. It is safe modifying contentType buffer after function return. SetRemoteAddr sets remote address to the given value. Set nil value to restore default behaviour for using connection remote address. SetStatusCode sets response status code. SetUserValue stores the given value (arbitrary object) under the given key in ctx. The value stored in ctx may be obtained by UserValue*. This functionality may be useful for passing arbitrary values between functions involved in request processing. All the values are removed from ctx after returning from the top RequestHandler. Additionally, Close method is called on each value implementing io.Closer before removing the value from ctx. SetUserValueBytes stores the given value (arbitrary object) under the given key in ctx. The value stored in ctx may be obtained by UserValue*. This functionality may be useful for passing arbitrary values between functions involved in request processing. All the values stored in ctx are deleted after returning from RequestHandler. String returns unique string representation of the ctx. The returned value may be useful for logging. Success sets response Content-Type and body to the given values. SuccessString sets response Content-Type and body to the given values. TLSConnectionState returns TLS connection state. The function returns nil if the underlying connection isn't tls.Conn. The returned state may be used for verifying TLS version, client certificates, etc. Time returns RequestHandler call time. TimeoutError sets response status code to StatusRequestTimeout and sets body to the given msg. All response modifications after TimeoutError call are ignored. TimeoutError MUST be called before returning from RequestHandler if there are references to ctx and/or its members in other goroutines remain. Usage of this function is discouraged. Prefer eliminating ctx references from pending goroutines instead of using this function. TimeoutErrorWithCode sets response body to msg and response status code to statusCode. All response modifications after TimeoutErrorWithCode call are ignored. TimeoutErrorWithCode MUST be called before returning from RequestHandler if there are references to ctx and/or its members in other goroutines remain. Usage of this function is discouraged. Prefer eliminating ctx references from pending goroutines instead of using this function. TimeoutErrorWithResponse marks the ctx as timed out and sends the given response to the client. All ctx modifications after TimeoutErrorWithResponse call are ignored. TimeoutErrorWithResponse MUST be called before returning from RequestHandler if there are references to ctx and/or its members in other goroutines remain. Usage of this function is discouraged. Prefer eliminating ctx references from pending goroutines instead of using this function. URI returns requested uri. This uri is valid until your request handler returns. UserAgent returns User-Agent header value from the request. The returned bytes are valid until your request handler returns. UserValue returns the value stored via SetUserValue* under the given key. UserValueBytes returns the value stored via SetUserValue* under the given key. Value returns the value associated with this context for key, or nil if no value is associated with key. Successive calls to Value with the same key returns the same result. This method is present to make RequestCtx implement the context interface. This method is the same as calling ctx.UserValue(key) VisitUserValues calls visitor for each existing userValue with a key that is a string or []byte. visitor must not retain references to key and value after returning. Make key and/or value copies if you need storing them after returning. VisitUserValuesAll calls visitor for each existing userValue. visitor must not retain references to key and value after returning. Make key and/or value copies if you need storing them after returning. Write writes p into response body. WriteString appends s to response body. *RequestCtx : github.com/ChrisTrenkamp/goxpath/tree.Result *RequestCtx : context.Context *RequestCtx : fmt.Stringer *RequestCtx : internal/bisect.Writer *RequestCtx : io.StringWriter *RequestCtx : io.Writer func github.com/gofiber/fiber/v2.(*Ctx).Context() *RequestCtx func ServeFile(ctx *RequestCtx, path string) func ServeFileBytes(ctx *RequestCtx, path []byte) func ServeFileBytesUncompressed(ctx *RequestCtx, path []byte) func ServeFileUncompressed(ctx *RequestCtx, path string) func github.com/gofiber/fiber/v2.(*App).AcquireCtx(fctx *RequestCtx) *fiber.Ctx
RequestHandler must process incoming requests. RequestHandler must call ctx.TimeoutError() before returning if it keeps references to ctx and/or its members after the return. Consider wrapping RequestHandler into TimeoutHandler if response time must be limited. func CompressHandler(h RequestHandler) RequestHandler func CompressHandlerBrotliLevel(h RequestHandler, brotliLevel, otherLevel int) RequestHandler func CompressHandlerLevel(h RequestHandler, level int) RequestHandler func FSHandler(root string, stripSlashes int) RequestHandler func TimeoutHandler(h RequestHandler, timeout time.Duration, msg string) RequestHandler func TimeoutWithCodeHandler(h RequestHandler, timeout time.Duration, msg string, statusCode int) RequestHandler func (*FS).NewRequestHandler() RequestHandler func github.com/gofiber/fiber/v2.(*App).Handler() RequestHandler func CompressHandler(h RequestHandler) RequestHandler func CompressHandlerBrotliLevel(h RequestHandler, brotliLevel, otherLevel int) RequestHandler func CompressHandlerLevel(h RequestHandler, level int) RequestHandler func ListenAndServe(addr string, handler RequestHandler) error func ListenAndServeTLS(addr, certFile, keyFile string, handler RequestHandler) error func ListenAndServeTLSEmbed(addr string, certData, keyData []byte, handler RequestHandler) error func ListenAndServeUNIX(addr string, mode os.FileMode, handler RequestHandler) error func Serve(ln net.Listener, handler RequestHandler) error func ServeConn(c net.Conn, handler RequestHandler) error func ServeTLS(ln net.Listener, certFile, keyFile string, handler RequestHandler) error func ServeTLSEmbed(ln net.Listener, certData, keyData []byte, handler RequestHandler) error func TimeoutHandler(h RequestHandler, timeout time.Duration, msg string) RequestHandler func TimeoutWithCodeHandler(h RequestHandler, timeout time.Duration, msg string, statusCode int) RequestHandler
RequestHeader represents HTTP request header. It is forbidden copying RequestHeader instances. Create new instances instead and use CopyTo. RequestHeader instance MUST NOT be used from concurrently running goroutines. 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. If the header is set as a Trailer (forbidden trailers will not be set, see AddTrailer for more details), it will be sent after the chunked request body. 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. If the header is set as a Trailer (forbidden trailers will not be set, see AddTrailer for more details), it will be sent after the chunked request body. 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. the Content-Type, Content-Length, Connection, Cookie, Transfer-Encoding, Host and User-Agent headers can only be set once and will overwrite the previous value. If the header is set as a Trailer (forbidden trailers will not be set, see AddTrailer for more details), it will be sent after the chunked request body. 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. If the header is set as a Trailer (forbidden trailers will not be set, see AddTrailer for more details), it will be sent after the chunked request body. AddTrailer add Trailer header value for chunked request to indicate which headers will be sent after the body. Use Set to set the trailer header later. Trailers are only supported with chunked transfer. Trailers allow the sender to include additional headers at the end of chunked messages. The following trailers are forbidden: 1. necessary for message framing (e.g., Transfer-Encoding and Content-Length), 2. routing (e.g., Host), 3. request modifiers (e.g., controls and conditionals in Section 5 of [RFC7231]), 4. authentication (e.g., see [RFC7235] and [RFC6265]), 5. response control data (e.g., see Section 7.1 of [RFC7231]), 6. determining how to process the payload (e.g., Content-Encoding, Content-Type, Content-Range, and Trailer) Return ErrBadTrailer if contain any forbidden trailers. AddTrailerBytes add Trailer header value for chunked request to indicate which headers will be sent after the body. Use Set to set the trailer header later. Trailers are only supported with chunked transfer. Trailers allow the sender to include additional headers at the end of chunked messages. The following trailers are forbidden: 1. necessary for message framing (e.g., Transfer-Encoding and Content-Length), 2. routing (e.g., Host), 3. request modifiers (e.g., controls and conditionals in Section 5 of [RFC7231]), 4. authentication (e.g., see [RFC7235] and [RFC6265]), 5. response control data (e.g., see Section 7.1 of [RFC7231]), 6. determining how to process the payload (e.g., Content-Encoding, Content-Type, Content-Range, and Trailer) Return ErrBadTrailer if contain any forbidden trailers. AppendBytes appends request header representation to dst and returns the extended dst. ConnectionClose returns true if 'Connection: close' header is set. ConnectionUpgrade returns true if 'Connection: Upgrade' header is set. ContentEncoding returns Content-Encoding header value. ContentLength returns Content-Length header value. It may be negative: -1 means Transfer-Encoding: chunked. ContentType returns Content-Type header value. Cookie returns cookie for the given key. CookieBytes returns cookie for the given key. CopyTo copies all the headers to dst. Del deletes header with the given key. DelAllCookies removes all the cookies from request headers. DelBytes deletes header with the given key. DelCookie removes cookie under the given key. DelCookieBytes removes cookie under the given key. DisableNormalizing disables header names' normalization. By default all the header names are normalized by uppercasing the first letter and all the first letters following dashes, while lowercasing all the other letters. Examples: - CONNECTION -> Connection - conteNT-tYPE -> Content-Type - foo-bar-baz -> Foo-Bar-Baz Disable header names' normalization only if know what are you doing. DisableSpecialHeader disables special header processing. fasthttp will not set any special headers for you, such as Host, Content-Type, User-Agent, etc. You must set everything yourself. If RequestHeader.Read() is called, special headers will be ignored. This can be used to control case and order of special headers. This is generally not recommended. EnableNormalizing enables header names' normalization. Header names are normalized by uppercasing the first letter and all the first letters following dashes, while lowercasing all the other letters. Examples: - CONNECTION -> Connection - conteNT-tYPE -> Content-Type - foo-bar-baz -> Foo-Bar-Baz This is enabled by default unless disabled using DisableNormalizing() EnableSpecialHeader enables special header processing. fasthttp will send Host, Content-Type, User-Agent, etc headers for you. This is suggested and enabled by default. HasAcceptEncoding returns true if the header contains the given Accept-Encoding value. HasAcceptEncodingBytes returns true if the header contains the given Accept-Encoding value. Header returns request header representation. Headers that set as Trailer will not represent. Use TrailerHeader for trailers. The returned value is valid until the request is released, either though ReleaseRequest or your request handler returning. Do not store references to returned value. Make copies instead. Host returns Host header value. IsConnect returns true if request method is CONNECT. IsDelete returns true if request method is DELETE. IsGet returns true if request method is GET. IsHTTP11 returns true if the request is HTTP/1.1. IsHead returns true if request method is HEAD. IsOptions returns true if request method is OPTIONS. IsPatch returns true if request method is PATCH. IsPost returns true if request method is POST. IsPut returns true if request method is PUT. IsTrace returns true if request method is TRACE. Len returns the number of headers set, i.e. the number of times f is called in VisitAll. Method returns HTTP request method. MultipartFormBoundary returns boundary part from 'multipart/form-data; boundary=...' Content-Type. Peek returns header value for the given key. The returned value is valid until the request is released, either though ReleaseRequest or your request handler returning. Do not store references to returned value. Make copies instead. PeekAll returns all header value for the given key. The returned value is valid until the request is released, either though ReleaseRequest or your request handler returning. Any future calls to the Peek* will modify the returned value. Do not store references to returned value. Make copies instead. PeekBytes returns header value for the given key. The returned value is valid until the request is released, either though ReleaseRequest or your request handler returning. Do not store references to returned value. Make copies instead. PeekKeys return all header keys. The returned value is valid until the request is released, either though ReleaseRequest or your request handler returning. Any future calls to the Peek* will modify the returned value. Do not store references to returned value. Make copies instead. PeekTrailerKeys return all trailer keys. The returned value is valid until the request is released, either though ReleaseRequest or your request handler returning. Any future calls to the Peek* will modify the returned value. Do not store references to returned value. Make copies instead. Protocol returns HTTP protocol. RawHeaders returns raw header key/value bytes. Depending on server configuration, header keys may be normalized to capital-case in place. This copy is set aside during parsing, so empty slice is returned for all cases where parsing did not happen. Similarly, request line is not stored during parsing and can not be returned. The slice is not safe to use after the handler returns. Read reads request header from r. io.EOF is returned if r is closed before reading the first header byte. ReadTrailer reads request trailer header from r. io.EOF is returned if r is closed before reading the first byte. Referer returns Referer header value. RequestURI returns RequestURI from the first HTTP request line. Reset clears request header. ResetConnectionClose clears 'Connection: close' header if it exists. Set sets the given 'key: value' header. If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details), it will be sent after the chunked request body. Use Add for setting multiple header values under the same key. SetByteRange sets 'Range: bytes=startPos-endPos' header. - If startPos is negative, then 'bytes=-startPos' value is set. - If endPos is negative, then 'bytes=startPos-' value is set. SetBytesK sets the given 'key: value' header. If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details), it will be sent after the chunked request body. Use AddBytesK for setting multiple header values under the same key. SetBytesKV sets the given 'key: value' header. If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details), it will be sent after the chunked request body. Use AddBytesKV for setting multiple header values under the same key. SetBytesV sets the given 'key: value' header. If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details), it will be sent after the chunked request body. Use AddBytesV for setting multiple header values under the same key. SetCanonical sets the given 'key: value' header assuming that key is in canonical form. If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details), it will be sent after the chunked request body. SetConnectionClose sets 'Connection: close' header. SetContentEncoding sets Content-Encoding header value. SetContentEncodingBytes sets Content-Encoding header value. SetContentLength sets Content-Length header value. Negative content-length sets 'Transfer-Encoding: chunked' header. SetContentType sets Content-Type header value. SetContentTypeBytes sets Content-Type header value. SetCookie sets 'key: value' cookies. SetCookieBytesK sets 'key: value' cookies. SetCookieBytesKV sets 'key: value' cookies. SetHost sets Host header value. SetHostBytes sets Host header value. SetMethod sets HTTP request method. SetMethodBytes sets HTTP request method. SetMultipartFormBoundary sets the following Content-Type: 'multipart/form-data; boundary=...' where ... is substituted by the given boundary. SetMultipartFormBoundaryBytes sets the following Content-Type: 'multipart/form-data; boundary=...' where ... is substituted by the given boundary. SetNoDefaultContentType allows you to control if a default Content-Type header will be set (false) or not (true). SetProtocol sets HTTP request protocol. SetProtocolBytes sets HTTP request protocol. SetReferer sets Referer header value. SetRefererBytes sets Referer header value. SetRequestURI sets RequestURI for the first HTTP request line. RequestURI must be properly encoded. Use URI.RequestURI for constructing proper RequestURI if unsure. SetRequestURIBytes sets RequestURI for the first HTTP request line. RequestURI must be properly encoded. Use URI.RequestURI for constructing proper RequestURI if unsure. SetTrailer sets Trailer header value for chunked request to indicate which headers will be sent after the body. Use Set to set the trailer header later. Trailers are only supported with chunked transfer. Trailers allow the sender to include additional headers at the end of chunked messages. The following trailers are forbidden: 1. necessary for message framing (e.g., Transfer-Encoding and Content-Length), 2. routing (e.g., Host), 3. request modifiers (e.g., controls and conditionals in Section 5 of [RFC7231]), 4. authentication (e.g., see [RFC7235] and [RFC6265]), 5. response control data (e.g., see Section 7.1 of [RFC7231]), 6. determining how to process the payload (e.g., Content-Encoding, Content-Type, Content-Range, and Trailer) Return ErrBadTrailer if contain any forbidden trailers. SetTrailerBytes sets Trailer header value for chunked request to indicate which headers will be sent after the body. Use Set to set the trailer header later. Trailers are only supported with chunked transfer. Trailers allow the sender to include additional headers at the end of chunked messages. The following trailers are forbidden: 1. necessary for message framing (e.g., Transfer-Encoding and Content-Length), 2. routing (e.g., Host), 3. request modifiers (e.g., controls and conditionals in Section 5 of [RFC7231]), 4. authentication (e.g., see [RFC7235] and [RFC6265]), 5. response control data (e.g., see Section 7.1 of [RFC7231]), 6. determining how to process the payload (e.g., Content-Encoding, Content-Type, Content-Range, and Trailer) Return ErrBadTrailer if contain any forbidden trailers. SetUserAgent sets User-Agent header value. SetUserAgentBytes sets User-Agent header value. String returns request header representation. TrailerHeader returns request trailer header representation. Trailers will only be received with chunked transfer. The returned value is valid until the request is released, either though ReleaseRequest or your request handler returning. Do not store references to returned value. Make copies instead. UserAgent returns User-Agent header value. VisitAll calls f for each header. f must not retain references to key and/or value after returning. Copy key and/or value contents before returning if you need retaining them. To get the headers in order they were received use VisitAllInOrder. VisitAllCookie calls f for each request cookie. f must not retain references to key and/or value after returning. VisitAllInOrder calls f for each header in the order they were received. f must not retain references to key and/or value after returning. Copy key and/or value contents before returning if you need retaining them. This function is slightly slower than VisitAll because it has to reparse the raw headers to get the order. VisitAllTrailer calls f for each request Trailer. f must not retain references to value after returning. Write writes request header to w. WriteTo writes request header to w. WriteTo implements io.WriterTo interface. *RequestHeader : github.com/ChrisTrenkamp/goxpath/tree.Result *RequestHeader : github.com/opentracing/opentracing-go.TextMapWriter *RequestHeader : fmt.Stringer *RequestHeader : io.WriterTo func (*RequestHeader).CopyTo(dst *RequestHeader)
Resolver represents interface of the tcp resolver. ( Resolver) LookupIPAddr(context.Context, string) (names []net.IPAddr, err error) *net.Resolver
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. Response header Copying Header by value is forbidden. Use pointer to Header instead. Flush headers as soon as possible without waiting for first body bytes. Relevant for bodyStream only. Response.Read() skips reading body if set to true. Use it for reading HEAD responses. Response.Write() skips writing body if set to true. Use it for writing HEAD responses. StreamBody enables response body streaming. Use SetBodyStream to set the body stream. AppendBody appends p to response body. It is safe re-using p after the function returns. AppendBodyString appends s to response body. Body returns response body. The returned value is valid until the response is released, either though ReleaseResponse or your request handler returning. Do not store references to returned value. Make copies instead. BodyGunzip returns un-gzipped body data. This method may be used if the response header contains 'Content-Encoding: gzip' for reading un-gzipped body. Use Body for reading gzipped response body. BodyInflate returns inflated body data. This method may be used if the response header contains 'Content-Encoding: deflate' for reading inflated response body. Use Body for reading deflated response body. BodyStream returns io.Reader You must CloseBodyStream or ReleaseResponse after you use it. BodyUnbrotli returns un-brotlied body data. This method may be used if the response header contains 'Content-Encoding: br' for reading un-brotlied body. Use Body for reading brotlied response body. BodyUncompressed returns body data and if needed decompress it from gzip, deflate or Brotli. This method may be used if the response header contains 'Content-Encoding' for reading uncompressed response body. Use Body for reading the raw response body. BodyWriteTo writes response body to w. BodyWriter returns writer for populating response body. If used inside RequestHandler, the returned writer must not be used after returning from RequestHandler. Use RequestCtx.Write or SetBodyStreamWriter in this case. (*Response) CloseBodyStream() error ConnectionClose returns true if 'Connection: close' header is set. CopyTo copies resp contents to dst except of body stream. IsBodyStream returns true if body is set via SetBodyStream* LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it. Read reads response (including body) from the given r. io.EOF is returned if r is closed before reading the first header byte. ReadBody reads response body from the given r, limiting the body size. If maxBodySize > 0 and the body size exceeds maxBodySize, then ErrBodyTooLarge is returned. ReadLimitBody reads response headers from the given r, then reads the body using the ReadBody function and limiting the body size. If resp.SkipBody is true then it skips reading the response body. If maxBodySize > 0 and the body size exceeds maxBodySize, then ErrBodyTooLarge is returned. io.EOF is returned if r is closed before reading the first header byte. ReleaseBody retires the response body if it is greater than "size" bytes. This permits GC to reclaim the large buffer. If used, must be before ReleaseResponse. Use this method only if you really understand how it works. The majority of workloads don't need this method. RemoteAddr returns the remote network address. The Addr returned is shared by all invocations of RemoteAddr, so do not modify it. Reset clears response contents. ResetBody resets response body. SendFile registers file on the given path to be used as response body when Write is called. Note that SendFile doesn't set Content-Type, so set it yourself with Header.SetContentType. SetBody sets response body. It is safe re-using body argument after the function returns. SetBodyRaw sets response body, but without copying it. From this point onward the body argument must not be changed. SetBodyStream sets response 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. See also SetBodyStreamWriter. SetBodyStreamWriter registers the given sw for populating response body. This function may be used in the following cases: - if response body is too big (more than 10MB). - if response body is streamed from slow external sources. - if response body must be streamed to the client in chunks (aka `http server push` or `chunked transfer-encoding`). See also SetBodyStream. SetBodyString sets response body. SetConnectionClose sets 'Connection: close' header. SetStatusCode sets response status code. StatusCode returns response status code. String returns response representation. Returns error message instead of response representation on error. Use Write instead of String for performance-critical code. SwapBody swaps response body with the given body and returns the previous response body. It is forbidden to use the body passed to SwapBody after the function returns. Write writes response to w. Write doesn't flush response to w for performance reasons. See also WriteTo. WriteDeflate writes response with deflated body to w. The method deflates response body and sets 'Content-Encoding: deflate' header before writing response to w. WriteDeflate doesn't flush response to w for performance reasons. WriteDeflateLevel writes response with deflated body to w. Level is the desired compression level: - CompressNoCompression - CompressBestSpeed - CompressBestCompression - CompressDefaultCompression - CompressHuffmanOnly The method deflates response body and sets 'Content-Encoding: deflate' header before writing response to w. WriteDeflateLevel doesn't flush response to w for performance reasons. WriteGzip writes response with gzipped body to w. The method gzips response body and sets 'Content-Encoding: gzip' header before writing response to w. WriteGzip doesn't flush response to w for performance reasons. WriteGzipLevel writes response with gzipped body to w. Level is the desired compression level: - CompressNoCompression - CompressBestSpeed - CompressBestCompression - CompressDefaultCompression - CompressHuffmanOnly The method gzips response body and sets 'Content-Encoding: gzip' header before writing response to w. WriteGzipLevel doesn't flush response to w for performance reasons. WriteTo writes response to w. It implements io.WriterTo. *Response : github.com/ChrisTrenkamp/goxpath/tree.Result *Response : fmt.Stringer *Response : io.WriterTo func AcquireResponse() *Response func (*RequestCtx).LastTimeoutErrorResponse() *Response func github.com/gofiber/fiber/v2.AcquireResponse() *fiber.Response func github.com/gofiber/fiber/v2.(*Ctx).Response() *Response func Do(req *Request, resp *Response) error func DoDeadline(req *Request, resp *Response, deadline time.Time) error func DoRedirects(req *Request, resp *Response, maxRedirectsCount int) error func DoTimeout(req *Request, resp *Response, timeout time.Duration) error func ReleaseResponse(resp *Response) func BalancingClient.DoDeadline(req *Request, resp *Response, deadline time.Time) error func (*Client).Do(req *Request, resp *Response) error func (*Client).DoDeadline(req *Request, resp *Response, deadline time.Time) error func (*Client).DoRedirects(req *Request, resp *Response, maxRedirectsCount int) error func (*Client).DoTimeout(req *Request, resp *Response, timeout time.Duration) error func (*HostClient).Do(req *Request, resp *Response) error func (*HostClient).DoDeadline(req *Request, resp *Response, deadline time.Time) error func (*HostClient).DoRedirects(req *Request, resp *Response, maxRedirectsCount int) error func (*HostClient).DoTimeout(req *Request, resp *Response, timeout time.Duration) error func (*LBClient).Do(req *Request, resp *Response) error func (*LBClient).DoDeadline(req *Request, resp *Response, deadline time.Time) error func (*LBClient).DoTimeout(req *Request, resp *Response, timeout time.Duration) error func (*PipelineClient).Do(req *Request, resp *Response) error func (*PipelineClient).DoDeadline(req *Request, resp *Response, deadline time.Time) error func (*PipelineClient).DoTimeout(req *Request, resp *Response, timeout time.Duration) error func (*RequestCtx).TimeoutErrorWithResponse(resp *Response) func (*Response).CopyTo(dst *Response) func RoundTripper.RoundTrip(hc *HostClient, req *Request, resp *Response) (retry bool, err error) func github.com/gofiber/fiber/v2.ReleaseResponse(resp *fiber.Response) func github.com/gofiber/fiber/v2.(*Agent).SetResponse(customResp *fiber.Response) *fiber.Agent
ResponseHeader represents HTTP response header. It is forbidden copying ResponseHeader instances. Create new instances instead and use CopyTo. ResponseHeader instance MUST NOT be used from concurrently running goroutines. 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. the Content-Type, Content-Length, Connection, Server, Set-Cookie, Transfer-Encoding and Date headers can only be set once and will overwrite the previous value. If the header is set as a Trailer (forbidden trailers will not be set, see AddTrailer for more details), it will be sent after the chunked response body. 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. the Content-Type, Content-Length, Connection, Server, Set-Cookie, Transfer-Encoding and Date headers can only be set once and will overwrite the previous value. If the header is set as a Trailer (forbidden trailers will not be set, see AddTrailer for more details), it will be sent after the chunked response body. 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. the Content-Type, Content-Length, Connection, Server, Set-Cookie, Transfer-Encoding and Date headers can only be set once and will overwrite the previous value. If the header is set as a Trailer (forbidden trailers will not be set, see AddTrailer for more details), it will be sent after the chunked response body. 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. the Content-Type, Content-Length, Connection, Server, Set-Cookie, Transfer-Encoding and Date headers can only be set once and will overwrite the previous value. If the header is set as a Trailer (forbidden trailers will not be set, see AddTrailer for more details), it will be sent after the chunked response body. AddTrailer add Trailer header value for chunked response to indicate which headers will be sent after the body. Use Set to set the trailer header later. Trailers are only supported with chunked transfer. Trailers allow the sender to include additional headers at the end of chunked messages. The following trailers are forbidden: 1. necessary for message framing (e.g., Transfer-Encoding and Content-Length), 2. routing (e.g., Host), 3. request modifiers (e.g., controls and conditionals in Section 5 of [RFC7231]), 4. authentication (e.g., see [RFC7235] and [RFC6265]), 5. response control data (e.g., see Section 7.1 of [RFC7231]), 6. determining how to process the payload (e.g., Content-Encoding, Content-Type, Content-Range, and Trailer) Return ErrBadTrailer if contain any forbidden trailers. AddTrailerBytes add Trailer header value for chunked response to indicate which headers will be sent after the body. Use Set to set the trailer header later. Trailers are only supported with chunked transfer. Trailers allow the sender to include additional headers at the end of chunked messages. The following trailers are forbidden: 1. necessary for message framing (e.g., Transfer-Encoding and Content-Length), 2. routing (e.g., Host), 3. request modifiers (e.g., controls and conditionals in Section 5 of [RFC7231]), 4. authentication (e.g., see [RFC7235] and [RFC6265]), 5. response control data (e.g., see Section 7.1 of [RFC7231]), 6. determining how to process the payload (e.g., Content-Encoding, Content-Type, Content-Range, and Trailer) Return ErrBadTrailer if contain any forbidden trailers. AppendBytes appends response header representation to dst and returns the extended dst. ConnectionClose returns true if 'Connection: close' header is set. ConnectionUpgrade returns true if 'Connection: Upgrade' header is set. ContentEncoding returns Content-Encoding header value. ContentLength returns Content-Length header value. It may be negative: -1 means Transfer-Encoding: chunked. -2 means Transfer-Encoding: identity. ContentType returns Content-Type header value. Cookie fills cookie for the given cookie.Key. Returns false if cookie with the given cookie.Key is missing. CopyTo copies all the headers to dst. Del deletes header with the given key. DelAllCookies removes all the cookies from response headers. DelBytes deletes header with the given key. DelClientCookie instructs the client to remove the given cookie. This doesn't work for a cookie with specific domain or path, you should delete it manually like: c := AcquireCookie() c.SetKey(key) c.SetDomain("example.com") c.SetPath("/path") c.SetExpire(CookieExpireDelete) h.SetCookie(c) ReleaseCookie(c) Use DelCookie if you want just removing the cookie from response header. DelClientCookieBytes instructs the client to remove the given cookie. This doesn't work for a cookie with specific domain or path, you should delete it manually like: c := AcquireCookie() c.SetKey(key) c.SetDomain("example.com") c.SetPath("/path") c.SetExpire(CookieExpireDelete) h.SetCookie(c) ReleaseCookie(c) Use DelCookieBytes if you want just removing the cookie from response header. DelCookie removes cookie under the given key from response header. Note that DelCookie doesn't remove the cookie from the client. Use DelClientCookie instead. DelCookieBytes removes cookie under the given key from response header. Note that DelCookieBytes doesn't remove the cookie from the client. Use DelClientCookieBytes instead. DisableNormalizing disables header names' normalization. By default all the header names are normalized by uppercasing the first letter and all the first letters following dashes, while lowercasing all the other letters. Examples: - CONNECTION -> Connection - conteNT-tYPE -> Content-Type - foo-bar-baz -> Foo-Bar-Baz Disable header names' normalization only if know what are you doing. EnableNormalizing enables header names' normalization. Header names are normalized by uppercasing the first letter and all the first letters following dashes, while lowercasing all the other letters. Examples: - CONNECTION -> Connection - conteNT-tYPE -> Content-Type - foo-bar-baz -> Foo-Bar-Baz This is enabled by default unless disabled using DisableNormalizing() Header returns response header representation. Headers that set as Trailer will not represent. Use TrailerHeader for trailers. The returned value is valid until the request is released, either though ReleaseRequest or your request handler returning. Do not store references to returned value. Make copies instead. IsHTTP11 returns true if the response is HTTP/1.1. Len returns the number of headers set, i.e. the number of times f is called in VisitAll. Peek returns header value for the given key. The returned value is valid until the response is released, either though ReleaseResponse or your request handler returning. Do not store references to the returned value. Make copies instead. PeekAll returns all header value for the given key. The returned value is valid until the request is released, either though ReleaseResponse or your request handler returning. Any future calls to the Peek* will modify the returned value. Do not store references to returned value. Make copies instead. PeekBytes returns header value for the given key. The returned value is valid until the response is released, either though ReleaseResponse or your request handler returning. Do not store references to returned value. Make copies instead. PeekCookie is able to returns cookie by a given key from response. PeekKeys return all header keys. The returned value is valid until the request is released, either though ReleaseResponse or your request handler returning. Any future calls to the Peek* will modify the returned value. Do not store references to returned value. Make copies instead. PeekTrailerKeys return all trailer keys. The returned value is valid until the request is released, either though ReleaseResponse or your request handler returning. Any future calls to the Peek* will modify the returned value. Do not store references to returned value. Make copies instead. Protocol returns response protocol bytes. Read reads response header from r. io.EOF is returned if r is closed before reading the first header byte. ReadTrailer reads response trailer header from r. io.EOF is returned if r is closed before reading the first byte. Reset clears response header. ResetConnectionClose clears 'Connection: close' header if it exists. Server returns Server header value. Set sets the given 'key: value' header. If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details), it will be sent after the chunked response body. Use Add for setting multiple header values under the same key. SetBytesK sets the given 'key: value' header. If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details), it will be sent after the chunked response body. Use AddBytesK for setting multiple header values under the same key. SetBytesKV sets the given 'key: value' header. If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details), it will be sent after the chunked response body. Use AddBytesKV for setting multiple header values under the same key. SetBytesV sets the given 'key: value' header. If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details), it will be sent after the chunked response body. Use AddBytesV for setting multiple header values under the same key. SetCanonical sets the given 'key: value' header assuming that key is in canonical form. If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details), it will be sent after the chunked response body. SetConnectionClose sets 'Connection: close' header. SetContentEncoding sets Content-Encoding header value. SetContentEncodingBytes sets Content-Encoding header value. SetContentLength sets Content-Length header value. Content-Length may be negative: -1 means Transfer-Encoding: chunked. -2 means Transfer-Encoding: identity. SetContentRange sets 'Content-Range: bytes startPos-endPos/contentLength' header. SetContentType sets Content-Type header value. SetContentTypeBytes sets Content-Type header value. SetCookie sets the given response cookie. It is safe re-using the cookie after the function returns. SetLastModified sets 'Last-Modified' header to the given value. SetNoDefaultContentType allows you to control if a default Content-Type header will be set (false) or not (true). SetProtocol sets response protocol bytes. SetServer sets Server header value. SetServerBytes sets Server header value. SetStatusCode sets response status code. SetStatusMessage sets response status message bytes. SetTrailer sets header Trailer value for chunked response to indicate which headers will be sent after the body. Use Set to set the trailer header later. Trailers are only supported with chunked transfer. Trailers allow the sender to include additional headers at the end of chunked messages. The following trailers are forbidden: 1. necessary for message framing (e.g., Transfer-Encoding and Content-Length), 2. routing (e.g., Host), 3. request modifiers (e.g., controls and conditionals in Section 5 of [RFC7231]), 4. authentication (e.g., see [RFC7235] and [RFC6265]), 5. response control data (e.g., see Section 7.1 of [RFC7231]), 6. determining how to process the payload (e.g., Content-Encoding, Content-Type, Content-Range, and Trailer) Return ErrBadTrailer if contain any forbidden trailers. SetTrailerBytes sets Trailer header value for chunked response to indicate which headers will be sent after the body. Use Set to set the trailer header later. Trailers are only supported with chunked transfer. Trailers allow the sender to include additional headers at the end of chunked messages. The following trailers are forbidden: 1. necessary for message framing (e.g., Transfer-Encoding and Content-Length), 2. routing (e.g., Host), 3. request modifiers (e.g., controls and conditionals in Section 5 of [RFC7231]), 4. authentication (e.g., see [RFC7235] and [RFC6265]), 5. response control data (e.g., see Section 7.1 of [RFC7231]), 6. determining how to process the payload (e.g., Content-Encoding, Content-Type, Content-Range, and Trailer) Return ErrBadTrailer if contain any forbidden trailers. StatusCode returns response status code. StatusMessage returns response status message. String returns response header representation. TrailerHeader returns response trailer header representation. Trailers will only be received with chunked transfer. The returned value is valid until the request is released, either though ReleaseRequest or your request handler returning. Do not store references to returned value. Make copies instead. VisitAll calls f for each header. f must not retain references to key and/or value after returning. Copy key and/or value contents before returning if you need retaining them. VisitAllCookie calls f for each response cookie. Cookie name is passed in key and the whole Set-Cookie header value is passed in value on each f invocation. Value may be parsed with Cookie.ParseBytes(). f must not retain references to key and/or value after returning. VisitAllTrailer calls f for each response Trailer. f must not retain references to value after returning. Write writes response header to w. WriteTo writes response header to w. WriteTo implements io.WriterTo interface. *ResponseHeader : github.com/ChrisTrenkamp/goxpath/tree.Result *ResponseHeader : github.com/opentracing/opentracing-go.TextMapWriter *ResponseHeader : fmt.Stringer *ResponseHeader : io.WriterTo func (*ResponseHeader).CopyTo(dst *ResponseHeader)
RetryIfFunc signature of retry if function Request argument passed to RetryIfFunc, if there are any request errors. func github.com/gofiber/fiber/v2.(*Agent).RetryIf(retryIf fiber.RetryIfFunc) *fiber.Agent
RoundTripper wraps every request/response. ( RoundTripper) RoundTrip(hc *HostClient, req *Request, resp *Response) (retry bool, err error) var DefaultTransport
ServeHandler must process tls.Config.NextProto negotiated requests. func (*Server).NextProto(key string, nph ServeHandler)
Server implements HTTP server. Default Server settings should satisfy the majority of Server users. Adjust Server settings only if you really understand the consequences. It is forbidden copying Server instances. Create new Server instances instead. It is safe to call Server methods from concurrently running goroutines. CloseOnShutdown when true adds a `Connection: close` header when the server is shutting down. The maximum number of concurrent connections the server may serve. DefaultConcurrency is used if not set. Concurrency only works if you either call Serve once, or only ServeConn multiple times. It works with ListenAndServe as well. ConnState specifies an optional callback function that is called when a client connection changes state. See the ConnState type and associated constants for details. ContinueHandler is called after receiving the Expect 100 Continue Header https://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html#sec8.2.3 https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.1.1 Using ContinueHandler a server can make decisioning on whether or not to read a potentially large request body based on the headers The default is to automatically read request bodies of Expect 100 Continue requests like they are normal requests Header names are passed as-is without normalization if this option is set. Disabled header names' normalization may be useful only for proxying incoming requests to other servers expecting case-sensitive header names. See https://github.com/valyala/fasthttp/issues/57 for details. By default request and response header names are normalized, i.e. The first letter and the first letters following dashes are uppercased, while all the other letters are lowercased. Examples: * HOST -> Host * content-type -> Content-Type * cONTENT-lenGTH -> Content-Length Whether to disable keep-alive connections. The server will close all the incoming connections after sending the first response to client if this option is set to true. By default keep-alive connections are enabled. 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. ErrorHandler for returning a response in case of an error while receiving or parsing the request. The following is a non-exhaustive list of errors that can be expected as argument: * io.EOF * io.ErrUnexpectedEOF * ErrGetOnly * ErrSmallBuffer * ErrBodyTooLarge * ErrBrokenChunks FormValueFunc, which is used by RequestCtx.FormValue and support for customizing the behaviour of the RequestCtx.FormValue function. NetHttpFormValueFunc gives a FormValueFunc func implementation that is consistent with net/http. Rejects all non-GET requests if set to true. This option is useful as anti-DoS protection for servers accepting only GET requests and HEAD requests. The request size is limited by ReadBufferSize if GetOnly is set. Server accepts all the requests by default. Handler for processing incoming requests. Take into account that no `panic` recovery is done by `fasthttp` (thus any `panic` will take down the entire server). Instead the user should use `recover` to handle these situations. HeaderReceived is called after receiving the header non zero RequestConfig field values will overwrite the default configs IdleTimeout is 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. KeepHijackedConns is an opt-in disable of connection close by fasthttp after connections' HijackHandler returns. This allows to save goroutines, e.g. when fasthttp used to upgrade http connections to WS and connection goes to another handler, which will close it when needed. Logs all errors, including the most frequent 'connection reset by peer', 'broken pipe' and 'connection timeout' errors. Such errors are common in production serving real-world clients. By default the most frequent errors such as 'connection reset by peer', 'broken pipe' and 'connection timeout' are suppressed in order to limit output log traffic. Logger, which is used by RequestCtx.Logger(). By default standard logger from log package is used. Maximum number of concurrent client connections allowed per IP. By default unlimited number of concurrent connections may be established to the server from a single IP address. MaxIdleWorkerDuration is the maximum idle time of a single worker in the underlying worker pool of the Server. Idle workers beyond this time will be cleared. MaxKeepaliveDuration is a no-op and only left here for backwards compatibility. Deprecated: Use IdleTimeout instead. Maximum request body size. The server rejects requests with bodies exceeding this limit. Request body size is limited by DefaultMaxRequestBodySize by default. Maximum number of requests served per connection. The server closes connection after the last request. 'Connection: close' header is added to the last response. By default unlimited number of requests may be served per connection. Server name for sending in response headers. Default server name is used if left blank. NoDefaultContentType, when set to true, causes the default Content-Type header to be excluded from the Response. The default Content-Type header value is the internal default value. When set to true, the Content-Type will not be present. NoDefaultDate, when set to true, causes the default Date header to be excluded from the Response. The default Date header value is the current date value. When set to true, the Date will not be present. NoDefaultServerHeader, when set to true, causes the default Server header to be excluded from the Response. The default Server header value is the value of the Name field or an internal default value in its absence. With this option set to true, the only time a Server header will be sent is if a non-zero length value is explicitly provided during a request. 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 buffer size is used if not set. ReadTimeout is the amount of time allowed to read the full request including body. The connection's read deadline is reset when the connection opens, or for keep-alive connections after the first byte has been read. By default request read timeout is unlimited. 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%. Aggressive memory usage reduction is disabled by default. Will not log potentially sensitive content in error logs This option is useful for servers that handle sensitive data in the request/response. Server logs all full errors by default. SleepWhenConcurrencyLimitsExceeded is a duration to be slept of if the concurrency limit in exceeded (default [when is 0]: don't sleep and accept new connections immediately). StreamRequestBody enables request body streaming, and calls the handler sooner when given body is larger than the current limit. Whether to enable tcp keep-alive connections. Whether the operating system should send tcp keep-alive messages on the tcp connection. By default tcp keep-alive connections are disabled. Period between tcp keep-alive messages. TCP keep-alive period is determined by operation system by default. TLSConfig optionally provides a TLS configuration for use by ServeTLS, ServeTLSEmbed, ListenAndServeTLS, ListenAndServeTLSEmbed, AppendCert, AppendCertEmbed and NextProto. Note that this value is cloned by ServeTLS, ServeTLSEmbed, ListenAndServeTLS and ListenAndServeTLSEmbed, so it's not possible to modify the configuration with methods like tls.Config.SetSessionTicketKeys. To use SetSessionTicketKeys, use Server.Serve with a TLS Listener instead. Per-connection buffer size for responses' writing. Default buffer size is used if not set. WriteTimeout is the maximum duration before timing out writes of the response. It is reset after the request handler has returned. By default response write timeout is unlimited. AppendCert appends certificate and keyfile to TLS Configuration. This function allows programmer to handle multiple domains in one server structure. See examples/multidomain AppendCertEmbed does the same as AppendCert but using in-memory data. GetCurrentConcurrency returns a number of currently served connections. This function is intended be used by monitoring systems GetOpenConnectionsCount returns a number of opened connections. This function is intended be used by monitoring systems ListenAndServe serves HTTP requests from the given TCP4 addr. Pass custom listener to Serve if you need listening on non-TCP4 media such as IPv6. Accepted connections are configured to enable TCP keep-alives. ListenAndServeTLS serves HTTPS requests from the given TCP4 addr. certFile and keyFile are paths to TLS certificate and key files. Pass custom listener to Serve if you need listening on non-TCP4 media such as IPv6. If the certFile or keyFile has not been provided to the server structure, the function will use the previously added TLS configuration. Accepted connections are configured to enable TCP keep-alives. ListenAndServeTLSEmbed serves HTTPS requests from the given TCP4 addr. certData and keyData must contain valid TLS certificate and key data. Pass custom listener to Serve if you need listening on arbitrary media such as IPv6. If the certFile or keyFile has not been provided the server structure, the function will use previously added TLS configuration. Accepted connections are configured to enable TCP keep-alives. ListenAndServeUNIX serves HTTP requests from the given UNIX addr. The function deletes existing file at addr before starting serving. The server sets the given file mode for the UNIX addr. NextProto adds nph to be processed when key is negotiated when TLS connection is established. This function can only be called before the server is started. Serve serves incoming connections from the given listener. Serve blocks until the given listener returns permanent error. ServeConn serves HTTP requests from the given connection. ServeConn returns nil if all requests from the c are successfully served. It returns non-nil error otherwise. Connection c must immediately propagate all the data passed to Write() to the client. Otherwise requests' processing may hang. ServeConn closes c before returning. ServeTLS serves HTTPS requests from the given listener. certFile and keyFile are paths to TLS certificate and key files. If the certFile or keyFile has not been provided the server structure, the function will use previously added TLS configuration. ServeTLSEmbed serves HTTPS requests from the given listener. certData and keyData must contain valid TLS certificate and key data. If the certFile or keyFile has not been provided the server structure, the function will use previously added TLS configuration. 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 it's recommended to set ReadTimeout and IdleTimeout to something else than 0. ShutdownWithContext gracefully shuts down the server without interrupting any active connections. ShutdownWithContext works by first closing all open listeners and then waiting for all connections to return to idle or context timeout and then shut down. When ShutdownWithContext is called, Serve, ListenAndServe, and ListenAndServeTLS immediately return nil. Make sure the program doesn't exit and waits instead for Shutdown to return. ShutdownWithContext does not close keepalive connections so it's recommended to set ReadTimeout and IdleTimeout to something else than 0. func github.com/gofiber/fiber/v2.(*App).Server() *Server
StreamWriter must write data to w. Usually StreamWriter writes data to w in a loop (aka 'data streaming'). StreamWriter must return immediately if w returns error. Since the written data is buffered, do not forget calling w.Flush when the data must be propagated to reader. func NewStreamReader(sw StreamWriter) io.ReadCloser func (*Request).SetBodyStreamWriter(sw StreamWriter) func (*RequestCtx).SetBodyStreamWriter(sw StreamWriter) func (*Response).SetBodyStreamWriter(sw StreamWriter)
TCPDialer contains options to control a group of Dial calls. Concurrency controls the maximum number of concurrent Dials that can be performed using this object. Setting this to 0 means unlimited. WARNING: This can only be changed before the first Dial. Changes made after the first Dial will not affect anything. DNSCacheDuration may be used to override the default DNS cache duration (DefaultDNSCacheDuration) LocalAddr is the local address to use when dialing an address. If nil, a local address is automatically chosen. This may be used to override DNS resolving policy, like this: var dialer = &fasthttp.TCPDialer{ Resolver: &net.Resolver{ PreferGo: true, StrictErrors: false, Dial: func (ctx context.Context, network, address string) (net.Conn, error) { d := net.Dialer{} return d.DialContext(ctx, "udp", "8.8.8.8:53") }, }, } Dial dials the given TCP addr using tcp4. This function has the following additional features comparing to net.Dial: - It reduces load on DNS resolver by caching resolved TCP addressed for DNSCacheDuration. - It dials all the resolved TCP addresses in round-robin manner until connection is established. This may be useful if certain addresses are temporarily unreachable. - It returns ErrDialTimeout if connection cannot be established during DefaultDialTimeout seconds. Use DialTimeout for customizing dial timeout. This dialer is intended for custom code wrapping before passing to Client.Dial or HostClient.Dial. For instance, per-host counters and/or limits may be implemented by such wrappers. The addr passed to the function must contain port. Example addr values: - foobar.baz:443 - foo.bar:80 - aaa.com:8080 DialDualStack dials the given TCP addr using both tcp4 and tcp6. This function has the following additional features comparing to net.Dial: - It reduces load on DNS resolver by caching resolved TCP addressed for DNSCacheDuration. - It dials all the resolved TCP addresses in round-robin manner until connection is established. This may be useful if certain addresses are temporarily unreachable. - It returns ErrDialTimeout if connection cannot be established during DefaultDialTimeout seconds. Use DialDualStackTimeout for custom dial timeout. This dialer is intended for custom code wrapping before passing to Client.Dial or HostClient.Dial. For instance, per-host counters and/or limits may be implemented by such wrappers. The addr passed to the function must contain port. Example addr values: - foobar.baz:443 - foo.bar:80 - aaa.com:8080 DialDualStackTimeout dials the given TCP addr using both tcp4 and tcp6 using the given timeout. This function has the following additional features comparing to net.Dial: - It reduces load on DNS resolver by caching resolved TCP addressed for DNSCacheDuration. - It dials all the resolved TCP addresses in round-robin manner until connection is established. This may be useful if certain addresses are temporarily unreachable. This dialer is intended for custom code wrapping before passing to Client.Dial or HostClient.Dial. For instance, per-host counters and/or limits may be implemented by such wrappers. The addr passed to the function must contain port. Example addr values: - foobar.baz:443 - foo.bar:80 - aaa.com:8080 DialTimeout dials the given TCP addr using tcp4 using the given timeout. This function has the following additional features comparing to net.Dial: - It reduces load on DNS resolver by caching resolved TCP addressed for DNSCacheDuration. - It dials all the resolved TCP addresses in round-robin manner until connection is established. This may be useful if certain addresses are temporarily unreachable. This dialer is intended for custom code wrapping before passing to Client.Dial or HostClient.Dial. For instance, per-host counters and/or limits may be implemented by such wrappers. The addr passed to the function must contain port. Example addr values: - foobar.baz:443 - foo.bar:80 - aaa.com:8080
URI represents URI :) . It is forbidden copying URI instances. Create new instance and use CopyTo instead. URI instance MUST NOT be used from concurrently running goroutines. Path values are sent as-is without normalization Disabled path normalization may be useful for proxying incoming requests to servers that are expecting paths to be forwarded as-is. By default path values are normalized, i.e. extra slashes are removed, special characters are encoded. AppendBytes appends full uri to dst and returns the extended dst. CopyTo copies uri contents to dst. FullURI returns full uri in the form {Scheme}://{Host}{RequestURI}#{Hash}. The returned bytes are valid until the next URI method call. Hash returns URI hash, i.e. qwe of http://aaa.com/foo/bar?baz=123#qwe . The returned bytes are valid until the next URI method call. Host returns host part, i.e. aaa.com of http://aaa.com/foo/bar?baz=123#qwe . Host is always lowercased. The returned bytes are valid until the next URI method call. LastPathSegment returns the last part of uri path after '/'. Examples: - For /foo/bar/baz.html path returns baz.html. - For /foo/bar/ returns empty byte slice. - For /foobar.js returns foobar.js. The returned bytes are valid until the next URI method call. Parse initializes URI from the given host and uri. host may be nil. In this case uri must contain fully qualified uri, i.e. with scheme and host. http is assumed if scheme is omitted. uri may contain e.g. RequestURI without scheme and host if host is non-empty. Password returns URI password The returned bytes are valid until the next URI method call. Path returns URI path, i.e. /foo/bar of http://aaa.com/foo/bar?baz=123#qwe . The returned path is always urldecoded and normalized, i.e. '//f%20obar/baz/../zzz' becomes '/f obar/zzz'. The returned bytes are valid until the next URI method call. PathOriginal returns the original path from requestURI passed to URI.Parse(). The returned bytes are valid until the next URI method call. QueryArgs returns query args. The returned args are valid until the next URI method call. QueryString returns URI query string, i.e. baz=123 of http://aaa.com/foo/bar?baz=123#qwe . The returned bytes are valid until the next URI method call. RequestURI returns RequestURI - i.e. URI without Scheme and Host. Reset clears uri. Scheme returns URI scheme, i.e. http of http://aaa.com/foo/bar?baz=123#qwe . Returned scheme is always lowercased. The returned bytes are valid until the next URI method call. SetHash sets URI hash. SetHashBytes sets URI hash. SetHost sets host for the uri. SetHostBytes sets host for the uri. SetPassword sets URI password. SetPasswordBytes sets URI password. SetPath sets URI path. SetPathBytes sets URI path. SetQueryString sets URI query string. SetQueryStringBytes sets URI query string. SetScheme sets URI scheme, i.e. http, https, ftp, etc. SetSchemeBytes sets URI scheme, i.e. http, https, ftp, etc. SetUsername sets URI username. SetUsernameBytes sets URI username. String returns full uri. Update updates uri. The following newURI types are accepted: - Absolute, i.e. http://foobar.com/aaa/bb?cc . In this case the original uri is replaced by newURI. - Absolute without scheme, i.e. //foobar.com/aaa/bb?cc. In this case the original scheme is preserved. - Missing host, i.e. /aaa/bb?cc . In this case only RequestURI part of the original uri is replaced. - Relative path, i.e. xx?yy=abc . In this case the original RequestURI is updated according to the new relative path. UpdateBytes updates uri. The following newURI types are accepted: - Absolute, i.e. http://foobar.com/aaa/bb?cc . In this case the original uri is replaced by newURI. - Absolute without scheme, i.e. //foobar.com/aaa/bb?cc. In this case the original scheme is preserved. - Missing host, i.e. /aaa/bb?cc . In this case only RequestURI part of the original uri is replaced. - Relative path, i.e. xx?yy=abc . In this case the original RequestURI is updated according to the new relative path. Username returns URI username The returned bytes are valid until the next URI method call. WriteTo writes full uri to w. WriteTo implements io.WriterTo interface. *URI : github.com/ChrisTrenkamp/goxpath/tree.Result *URI : fmt.Stringer *URI : io.WriterTo func AcquireURI() *URI func (*Request).URI() *URI func (*RequestCtx).URI() *URI func ReleaseURI(u *URI) func (*Request).SetURI(newURI *URI) func (*URI).CopyTo(dst *URI)
Package-Level Functions (total 87)
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.
AcquireCookie returns an empty Cookie object from the pool. The returned object may be returned back to the pool with ReleaseCookie. This allows reducing GC load.
AcquireRequest returns an empty Request instance from request pool. The returned Request instance may be passed to ReleaseRequest when it is no longer needed. This allows Request recycling, reduces GC pressure and usually improves performance.
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.
AcquireTimer returns a time.Timer from the pool and updates it to send the current time on its channel after at least timeout. The returned Timer may be returned to the pool with ReleaseTimer when no longer needed. This allows reducing GC load.
AcquireURI returns an empty URI instance from the pool. Release the URI with ReleaseURI after the URI is no longer needed. This allows reducing GC load.
AddMissingPort adds a port to a host if it is missing. A literal IPv6 address in hostport must be enclosed in square brackets, as in "[::1]:80", "[::1%lo0]:80".
AppendBrotliBytes appends brotlied src to dst and returns the resulting dst.
AppendBrotliBytesLevel appends brotlied src to dst using the given compression level and returns the resulting dst. Supported compression levels are: - CompressBrotliNoCompression - CompressBrotliBestSpeed - CompressBrotliBestCompression - CompressBrotliDefaultCompression
AppendDeflateBytes appends deflated src to dst and returns the resulting dst.
AppendDeflateBytesLevel appends deflated src to dst using the given compression level and returns the resulting dst. Supported compression levels are: - CompressNoCompression - CompressBestSpeed - CompressBestCompression - CompressDefaultCompression - CompressHuffmanOnly
AppendGunzipBytes appends gunzipped src to dst and returns the resulting dst.
AppendGzipBytes appends gzipped src to dst and returns the resulting dst.
AppendGzipBytesLevel appends gzipped src to dst using the given compression level and returns the resulting dst. Supported compression levels are: - CompressNoCompression - CompressBestSpeed - CompressBestCompression - CompressDefaultCompression - CompressHuffmanOnly
AppendHTMLEscape appends html-escaped s to dst and returns the extended dst.
AppendHTMLEscapeBytes appends html-escaped s to dst and returns the extended dst.
AppendHTTPDate appends HTTP-compliant (RFC1123) representation of date to dst and returns the extended dst.
AppendInflateBytes appends inflated src to dst and returns the resulting dst.
AppendIPv4 appends string representation of the given ip v4 to dst and returns the extended dst.
AppendNormalizedHeaderKey appends normalized header key (name) to dst and returns the resulting dst. Normalized header key starts with uppercase letter. The first letters after dashes are also uppercased. All the other letters are lowercased. Examples: - coNTENT-TYPe -> Content-Type - HOST -> Host - foo-bar-baz -> Foo-Bar-Baz
AppendNormalizedHeaderKeyBytes appends normalized header key (name) to dst and returns the resulting dst. Normalized header key starts with uppercase letter. The first letters after dashes are also uppercased. All the other letters are lowercased. Examples: - coNTENT-TYPe -> Content-Type - HOST -> Host - foo-bar-baz -> Foo-Bar-Baz
AppendQuotedArg appends url-encoded src to dst and returns appended dst.
AppendUint appends n to dst and returns the extended dst.
AppendUnbrotliBytes appends unbrotlied src to dst and returns the resulting dst.
AppendUnquotedArg appends url-decoded src to dst and returns appended dst. dst may point to src. In this case src will be overwritten.
CoarseTimeNow returns the current time truncated to the nearest second. Deprecated: This is slower than calling time.Now() directly. This is now time.Now().Truncate(time.Second) shortcut.
CompressHandler returns RequestHandler that transparently compresses response body generated by h if the request contains 'gzip' or 'deflate' 'Accept-Encoding' header.
CompressHandlerBrotliLevel returns RequestHandler that transparently compresses response body generated by h if the request contains a 'br', 'gzip' or 'deflate' 'Accept-Encoding' header. brotliLevel is the desired compression level for brotli. - CompressBrotliNoCompression - CompressBrotliBestSpeed - CompressBrotliBestCompression - CompressBrotliDefaultCompression otherLevel is the desired compression level for gzip and deflate. - CompressNoCompression - CompressBestSpeed - CompressBestCompression - CompressDefaultCompression - CompressHuffmanOnly
CompressHandlerLevel returns RequestHandler that transparently compresses response body generated by h if the request contains a 'gzip' or 'deflate' 'Accept-Encoding' header. Level is the desired compression level: - CompressNoCompression - CompressBestSpeed - CompressBestCompression - CompressDefaultCompression - CompressHuffmanOnly
Dial dials the given TCP addr using tcp4. This function has the following additional features comparing to net.Dial: - It reduces load on DNS resolver by caching resolved TCP addressed for DNSCacheDuration. - It dials all the resolved TCP addresses in round-robin manner until connection is established. This may be useful if certain addresses are temporarily unreachable. - It returns ErrDialTimeout if connection cannot be established during DefaultDialTimeout seconds. Use DialTimeout for customizing dial timeout. This dialer is intended for custom code wrapping before passing to Client.Dial or HostClient.Dial. For instance, per-host counters and/or limits may be implemented by such wrappers. The addr passed to the function must contain port. Example addr values: - foobar.baz:443 - foo.bar:80 - aaa.com:8080
DialDualStack dials the given TCP addr using both tcp4 and tcp6. This function has the following additional features comparing to net.Dial: - It reduces load on DNS resolver by caching resolved TCP addressed for DNSCacheDuration. - It dials all the resolved TCP addresses in round-robin manner until connection is established. This may be useful if certain addresses are temporarily unreachable. - It returns ErrDialTimeout if connection cannot be established during DefaultDialTimeout seconds. Use DialDualStackTimeout for custom dial timeout. This dialer is intended for custom code wrapping before passing to Client.Dial or HostClient.Dial. For instance, per-host counters and/or limits may be implemented by such wrappers. The addr passed to the function must contain port. Example addr values: - foobar.baz:443 - foo.bar:80 - aaa.com:8080
DialDualStackTimeout dials the given TCP addr using both tcp4 and tcp6 using the given timeout. This function has the following additional features comparing to net.Dial: - It reduces load on DNS resolver by caching resolved TCP addressed for DNSCacheDuration. - It dials all the resolved TCP addresses in round-robin manner until connection is established. This may be useful if certain addresses are temporarily unreachable. This dialer is intended for custom code wrapping before passing to Client.Dial or HostClient.Dial. For instance, per-host counters and/or limits may be implemented by such wrappers. The addr passed to the function must contain port. Example addr values: - foobar.baz:443 - foo.bar:80 - aaa.com:8080
DialTimeout dials the given TCP addr using tcp4 using the given timeout. This function has the following additional features comparing to net.Dial: - It reduces load on DNS resolver by caching resolved TCP addressed for DNSCacheDuration. - It dials all the resolved TCP addresses in round-robin manner until connection is established. This may be useful if certain addresses are temporarily unreachable. This dialer is intended for custom code wrapping before passing to Client.Dial or HostClient.Dial. For instance, per-host counters and/or limits may be implemented by such wrappers. The addr passed to the function must contain port. Example addr values: - foobar.baz:443 - foo.bar:80 - aaa.com:8080
Do performs the given http request and fills the given http response. Request must contain at least non-zero RequestURI with full url (including scheme and host) or non-zero Host header + RequestURI. Client determines the server to be requested in the following order: - from RequestURI if it contains full url with scheme and host; - from Host header otherwise. The function doesn't follow redirects. Use Get* for following redirects. Response is ignored if resp is nil. ErrNoFreeConns is returned if all DefaultMaxConnsPerHost connections to the requested host are busy. It is recommended obtaining req and resp via AcquireRequest and AcquireResponse in performance-critical code.
DoDeadline performs the given request and waits for response until the given deadline. Request must contain at least non-zero RequestURI with full url (including scheme and host) or non-zero Host header + RequestURI. Client determines the server to be requested in the following order: - from RequestURI if it contains full url with scheme and host; - from Host header otherwise. The function doesn't follow redirects. Use Get* for following redirects. Response is ignored if resp is nil. ErrTimeout is returned if the response wasn't returned until the given deadline. ErrNoFreeConns is returned if all DefaultMaxConnsPerHost connections to the requested host are busy. It is recommended obtaining req and resp via AcquireRequest and AcquireResponse in performance-critical code.
DoRedirects performs the given http request and fills the given http response, following up to maxRedirectsCount redirects. When the redirect count exceeds maxRedirectsCount, ErrTooManyRedirects is returned. Request must contain at least non-zero RequestURI with full url (including scheme and host) or non-zero Host header + RequestURI. Client determines the server to be requested in the following order: - from RequestURI if it contains full url with scheme and host; - from Host header otherwise. Response is ignored if resp is nil. ErrNoFreeConns is returned if all DefaultMaxConnsPerHost connections to the requested host are busy. It is recommended obtaining req and resp via AcquireRequest and AcquireResponse in performance-critical code.
DoTimeout performs the given request and waits for response during the given timeout duration. Request must contain at least non-zero RequestURI with full url (including scheme and host) or non-zero Host header + RequestURI. Client determines the server to be requested in the following order: - from RequestURI if it contains full url with scheme and host; - from Host header otherwise. The function doesn't follow redirects. Use Get* for following redirects. Response is ignored if resp is nil. ErrTimeout is returned if the response wasn't returned during the given timeout. ErrNoFreeConns is returned if all DefaultMaxConnsPerHost connections to the requested host are busy. It is recommended obtaining req and resp via AcquireRequest and AcquireResponse in performance-critical code.
FileLastModified returns last modified time for the file.
FSHandler returns request handler serving static files from the given root folder. stripSlashes indicates how many leading slashes must be stripped from requested path before searching requested file in the root folder. Examples: - stripSlashes = 0, original path: "/foo/bar", result: "/foo/bar" - stripSlashes = 1, original path: "/foo/bar", result: "/bar" - stripSlashes = 2, original path: "/foo/bar", result: "" The returned request handler automatically generates index pages for directories without index.html. The returned handler caches requested file handles for FSHandlerCacheDuration. Make sure your program has enough 'max open files' limit aka 'ulimit -n' if root folder contains many files. Do not create multiple request handler instances for the same (root, stripSlashes) arguments - just reuse a single instance. Otherwise goroutine leak will occur.
GenerateTestCertificate generates a test certificate and private key based on the given host.
Get returns the status code and body of url. The contents of dst will be replaced by the body and returned, if the dst is too small a new slice will be allocated. The function follows redirects. Use Do* for manually handling redirects.
GetDeadline returns the status code and body of url. The contents of dst will be replaced by the body and returned, if the dst is too small a new slice will be allocated. The function follows redirects. Use Do* for manually handling redirects. ErrTimeout error is returned if url contents couldn't be fetched until the given deadline.
GetTimeout returns the status code and body of url. The contents of dst will be replaced by the body and returned, if the dst is too small a new slice will be allocated. The function follows redirects. Use Do* for manually handling redirects. ErrTimeout error is returned if url contents couldn't be fetched during the given timeout.
ListenAndServe serves HTTP requests from the given TCP addr using the given handler.
ListenAndServeTLS serves HTTPS requests from the given TCP addr using the given handler. certFile and keyFile are paths to TLS certificate and key files.
ListenAndServeTLSEmbed serves HTTPS requests from the given TCP addr using the given handler. certData and keyData must contain valid TLS certificate and key data.
ListenAndServeUNIX serves HTTP requests from the given UNIX addr using the given handler. The function deletes existing file at addr before starting serving. The server sets the given file mode for the UNIX addr.
NewPathPrefixStripper returns path rewriter, which removes prefixSize bytes from the path prefix. Examples: - prefixSize = 0, original path: "/foo/bar", result: "/foo/bar" - prefixSize = 3, original path: "/foo/bar", result: "o/bar" - prefixSize = 7, original path: "/foo/bar", result: "r" The returned path rewriter may be used as FS.PathRewrite .
NewPathSlashesStripper returns path rewriter, which strips slashesCount leading slashes from the path. Examples: - slashesCount = 0, original path: "/foo/bar", result: "/foo/bar" - slashesCount = 1, original path: "/foo/bar", result: "/bar" - slashesCount = 2, original path: "/foo/bar", result: "" The returned path rewriter may be used as FS.PathRewrite .
NewStreamReader returns a reader, which replays all the data generated by sw. The returned reader may be passed to Response.SetBodyStream. Close must be called on the returned reader after all the required data has been read. Otherwise goroutine leak may occur. See also Response.SetBodyStreamWriter.
NewVHostPathRewriter returns path rewriter, which strips slashesCount leading slashes from the path and prepends the path with request's host, thus simplifying virtual hosting for static files. Examples: - host=foobar.com, slashesCount=0, original path="/foo/bar". Resulting path: "/foobar.com/foo/bar" - host=img.aaa.com, slashesCount=1, original path="/images/123/456.jpg" Resulting path: "/img.aaa.com/123/456.jpg"
ParseByteRange parses 'Range: bytes=...' header value. It follows https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35 .
ParseHTTPDate parses HTTP-compliant (RFC1123) date.
ParseIPv4 parses ip address from ipStr into dst and returns the extended dst.
ParseUfloat parses unsigned float from buf.
ParseUint parses uint from buf.
Post sends POST request to the given url with the given POST arguments. The contents of dst will be replaced by the body and returned, if the dst is too small a new slice will be allocated. The function follows redirects. Use Do* for manually handling redirects. Empty POST body is sent if postArgs is nil.
ReleaseArgs returns the object acquired via AcquireArgs to the pool. Do not access the released Args object, otherwise data races may occur.
ReleaseCookie returns the Cookie object acquired with AcquireCookie back to the pool. Do not access released Cookie object, otherwise data races may occur.
ReleaseRequest returns req acquired via AcquireRequest to request pool. It is forbidden accessing req and/or its' members after returning it to request pool.
ReleaseResponse return resp acquired via AcquireResponse to response pool. It is forbidden accessing resp and/or its' members after returning it to response pool.
ReleaseTimer returns the time.Timer acquired via AcquireTimer to the pool and prevents the Timer from firing. Do not access the released time.Timer or read from its channel otherwise data races may occur.
ReleaseURI releases the URI acquired via AcquireURI. The released URI mustn't be used after releasing it, otherwise data races may occur.
SaveMultipartFile saves multipart file fh under the given filename path.
Serve serves incoming connections from the given listener using the given handler. Serve blocks until the given listener returns permanent error.
ServeConn serves HTTP requests from the given connection using the given handler. ServeConn returns nil if all requests from the c are successfully served. It returns non-nil error otherwise. Connection c must immediately propagate all the data passed to Write() to the client. Otherwise requests' processing may hang. ServeConn closes c before returning.
ServeFile returns HTTP response containing compressed file contents from the given path. HTTP response may contain uncompressed file contents in the following cases: - Missing 'Accept-Encoding: gzip' request header. - No write access to directory containing the file. Directory contents is returned if path points to directory. Use ServeFileUncompressed is you don't need serving compressed file contents. See also RequestCtx.SendFile. WARNING: do not pass any user supplied paths to this function! WARNING: if path is based on user input users will be able to request any file on your filesystem! Use fasthttp.FS with a sane Root instead.
ServeFileBytes returns HTTP response containing compressed file contents from the given path. HTTP response may contain uncompressed file contents in the following cases: - Missing 'Accept-Encoding: gzip' request header. - No write access to directory containing the file. Directory contents is returned if path points to directory. Use ServeFileBytesUncompressed is you don't need serving compressed file contents. See also RequestCtx.SendFileBytes. WARNING: do not pass any user supplied paths to this function! WARNING: if path is based on user input users will be able to request any file on your filesystem! Use fasthttp.FS with a sane Root instead.
ServeFileBytesUncompressed returns HTTP response containing file contents from the given path. Directory contents is returned if path points to directory. ServeFileBytes may be used for saving network traffic when serving files with good compression ratio. See also RequestCtx.SendFileBytes. WARNING: do not pass any user supplied paths to this function! WARNING: if path is based on user input users will be able to request any file on your filesystem! Use fasthttp.FS with a sane Root instead.
ServeFileUncompressed returns HTTP response containing file contents from the given path. Directory contents is returned if path points to directory. ServeFile may be used for saving network traffic when serving files with good compression ratio. See also RequestCtx.SendFile. WARNING: do not pass any user supplied paths to this function! WARNING: if path is based on user input users will be able to request any file on your filesystem! Use fasthttp.FS with a sane Root instead.
ServeTLS serves HTTPS requests from the given net.Listener using the given handler. certFile and keyFile are paths to TLS certificate and key files.
ServeTLSEmbed serves HTTPS requests from the given net.Listener using the given handler. certData and keyData must contain valid TLS certificate and key data.
SetBodySizePoolLimit set the max body size for bodies to be returned to the pool. If the body size is larger it will be released instead of put back into the pool for reuse.
StatusCodeIsRedirect returns true if the status code indicates a redirect.
StatusMessage returns HTTP status message for the given status code.
TimeoutHandler creates RequestHandler, which returns StatusRequestTimeout error with the given msg to the client if h didn't return during the given duration. The returned handler may return StatusTooManyRequests error with the given msg to the client if there are more than Server.Concurrency concurrent handlers h are running at the moment.
TimeoutWithCodeHandler creates RequestHandler, which returns an error with the given msg and status code to the client if h didn't return during the given duration. The returned handler may return StatusTooManyRequests error with the given msg to the client if there are more than Server.Concurrency concurrent handlers h are running at the moment.
WriteBrotli writes brotlied p to w and returns the number of compressed bytes written to w.
WriteBrotliLevel writes brotlied p to w using the given compression level and returns the number of compressed bytes written to w. Supported compression levels are: - CompressBrotliNoCompression - CompressBrotliBestSpeed - CompressBrotliBestCompression - CompressBrotliDefaultCompression
WriteDeflate writes deflated p to w and returns the number of compressed bytes written to w.
WriteDeflateLevel writes deflated p to w using the given compression level and returns the number of compressed bytes written to w. Supported compression levels are: - CompressNoCompression - CompressBestSpeed - CompressBestCompression - CompressDefaultCompression - CompressHuffmanOnly
WriteGunzip writes ungzipped p to w and returns the number of uncompressed bytes written to w.
WriteGzip writes gzipped p to w and returns the number of compressed bytes written to w.
WriteGzipLevel writes gzipped p to w using the given compression level and returns the number of compressed bytes written to w. Supported compression levels are: - CompressNoCompression - CompressBestSpeed - CompressBestCompression - CompressDefaultCompression - CompressHuffmanOnly
WriteInflate writes inflated p to w and returns the number of uncompressed bytes written to w.
WriteMultipartForm writes the given multipart form f with the given boundary to w.
WriteUnbrotli writes unbrotlied p to w and returns the number of uncompressed bytes written to w.
Package-Level Variables (total 26)
CookieExpireDelete may be set on Cookie.Expire for expiring the given cookie.
CookieExpireUnlimited indicates that the cookie doesn't expire.
Deprecated: ErrAlreadyServing is never returned from Serve. See issue #633.
ErrBodyTooLarge is returned if either request or response body exceeds the given limit.
ErrConcurrencyLimit may be returned from ServeConn if the number of concurrently served connections exceeds Server.Concurrency.
ErrConnectionClosed may be returned from client methods if the server closes connection before returning the first response byte. If you see this error, then either fix the server by returning 'Connection: close' response header before closing the connection or add 'Connection: close' request header before sending requests to broken server.
ErrConnPoolStrategyNotImpl is returned when HostClient.ConnPoolStrategy is not implement yet. If you see this error, then you need to check your HostClient configuration.
ErrDialTimeout is returned when TCP dialing is timed out.
ErrGetOnly is returned when server expects only GET requests, but some other type of request came (Server.GetOnly option is true).
HostClients are only able to follow redirects to the same protocol.
ErrMissingFile may be returned from FormFile when the is no uploaded file associated with the given multipart form key.
ErrMissingLocation is returned by clients when the Location header is missing on an HTTP response with a redirect status code.
ErrNoArgValue is returned when Args value with the given key is missing.
ErrNoFreeConns is returned when no free connections available to the given host. Increase the allowed number of connections per host if you see this error.
ErrNoMultipartForm means that the request's Content-Type isn't 'multipart/form-data'.
ErrPerIPConnLimit may be returned from ServeConn if the number of connections per ip exceeds Server.MaxConnsPerIP.
ErrPipelineOverflow may be returned from PipelineClient.Do* if the requests' queue is overflown.
ErrTimeout is returned from timed out calls.
ErrTLSHandshakeTimeout indicates there is a timeout from tls handshake.
ErrTooManyRedirects is returned by clients when the number of redirects followed exceed the max count.
FSCompressedFileSuffixes is the suffixes FS adds to the original file names depending on encoding when trying to store compressed file under the new file name. See FS.Compress for details.
NetHttpFormValueFunc gives consistent behavior with net/http. POST and PUT body parameters take precedence over URL query string values.
Package-Level Constants (total 221)
Supported compression levels.
Supported compression levels.
Supported compression levels.
Supported compression levels.
Choose a default brotli compression level comparable to CompressDefaultCompression (gzip 6) See: https://github.com/valyala/fasthttp/issues/798#issuecomment-626293806
Supported compression levels.
Supported compression levels.
Supported compression levels.
Supported compression levels.
CookieSameSiteDefaultMode sets the SameSite flag
CookieSameSiteDisabled removes the SameSite flag
CookieSameSiteLaxMode sets the SameSite flag with the "Lax" parameter
CookieSameSiteNoneMode sets the SameSite flag with the "None" parameter see https://tools.ietf.org/html/draft-west-cookie-incrementalism-00
CookieSameSiteStrictMode sets the SameSite flag with the "Strict" parameter
DefaultConcurrency is the maximum number of concurrent connections the Server may serve by default (i.e. if Server.Concurrency isn't set).
DefaultDialTimeout is timeout used by Dial and DialDualStack for establishing TCP connections.
DefaultDNSCacheDuration is the duration for caching resolved TCP addresses by Dial* functions.
DefaultLBClientTimeout is the default request timeout used by LBClient when calling LBClient.Do. The timeout may be overridden via LBClient.Timeout.
DefaultMaxConnsPerHost is the maximum number of concurrent connections http client may establish per host by default (i.e. if Client.MaxConnsPerHost isn't set).
DefaultMaxIdemponentCallAttempts is the default idempotent calls attempts count.
DefaultMaxIdleConnDuration is the default duration before idle keep-alive connection is closed.
DefaultMaxPendingRequests is the default value for PipelineClient.MaxPendingRequests.
DefaultMaxRequestBodySize is the maximum request body size the server reads by default. See Server.MaxRequestBodySize for details.
FSCompressedFileSuffix is the suffix FS adds to the original file names when trying to store compressed file under the new file name. See FS.Compress for details.
FSHandlerCacheDuration is the default expiration duration for inactive file handlers opened by FS.
Content negotiation
Client hints
Headers
Headers
Headers
Headers
Other
Headers
Range requests
Headers
CORS
Headers
Headers
Headers
Headers
Headers
Headers
Headers
Caching
Response context
Headers
Authentication
Headers
Headers
Connection management
Downloads
Headers
Message body information
Headers
Headers
Headers
Headers
Security
Headers
Headers
Controls
Headers
Headers
Do Not Track
Headers
Headers
Conditionals
Headers
Headers
Headers
Headers
Proxies
Request context
Headers
Headers
Headers
Headers
Headers
Headers
Headers
Headers
Headers
Server-sent event
Headers
Redirects
Headers
Headers
Headers
Headers
Headers
Headers
Headers
Headers
Headers
Headers
Headers
Headers
Headers
Headers
Headers
Headers
Headers
Headers
WebSockets
Headers
Headers
Headers
Headers
Headers
Headers
Headers
Headers
Headers
Headers
Headers
Transfer coding
Headers
Headers
Headers
Headers
Headers
Headers
Headers
Headers
Headers
Headers
Headers
Headers
Headers
Headers
Headers
Headers
Headers
Headers
Headers
Headers
Headers
Headers
Headers
Headers
Headers
Headers
Headers
HTTP methods were copied from net/http.
HTTP methods were copied from net/http.
HTTP methods were copied from net/http.
HTTP methods were copied from net/http.
HTTP methods were copied from net/http.
HTTP methods were copied from net/http.
HTTP methods were copied from net/http.
HTTP methods were copied from net/http.
HTTP methods were copied from net/http.
StateActive represents a connection that has read 1 or more bytes of a request. The Server.ConnState hook for StateActive fires before the request has entered a handler and doesn't fire again until the request has been handled. After the request is handled, the state transitions to StateClosed, StateHijacked, or StateIdle. For HTTP/2, StateActive fires on the transition from zero to one active request, and only transitions away once all active requests are complete. That means that ConnState cannot be used to do per-request work; ConnState only notes the overall state of the connection.
StateClosed represents a closed connection. This is a terminal state. Hijacked connections do not transition to StateClosed.
StateHijacked represents a hijacked connection. This is a terminal state. It does not transition to StateClosed.
StateIdle represents a connection that has finished handling a request and is in the keep-alive state, waiting for a new request. Connections transition from StateIdle to either StateActive or StateClosed.
StateNew represents a new connection that is expected to send a request immediately. Connections begin at this state and then transition to either StateActive or StateClosed.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.
HTTP status codes were stolen from net/http.