Package fasthttp provides fast HTTP server and client API.
Fasthttp provides the following features:
Optimized for speed. Easily handles more than 100K qps and more than 1M concurrent keep-alive connections on modern hardware.
Optimized for low memory usage.
Easy 'Connection: Upgrade' support via RequestCtx.Hijack.
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.
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.
Client supports automatic retry on idempotent requests' failure.
Fasthttp API is designed with the ability to extend existing client and server implementations or to write custom client and server implementations from scratch.
Supported compression levels.
Supported compression levels.
View Sourceconst ( HeaderXPermittedCrossDomainPolicies = "X-Permitted-Cross-Domain-Policies" HeaderContentDisposition = "Content-Disposition" HeaderLocation = "Location" )
Headers.
View Sourceconst ( MethodGet = "GET" MethodHead = "HEAD" MethodPost = "POST" MethodPut = "PUT" MethodPatch = "PATCH" MethodDelete = "DELETE" MethodConnect = "CONNECT" MethodOptions = "OPTIONS" MethodTrace = "TRACE" )
HTTP methods were copied from net/http.
View Sourceconst ( StatusContinue = 100 StatusSwitchingProtocols = 101 StatusProcessing = 102 StatusEarlyHints = 103 StatusOK = 200 StatusCreated = 201 StatusAccepted = 202 StatusNonAuthoritativeInfo = 203 StatusNoContent = 204 StatusResetContent = 205 StatusPartialContent = 206 StatusMultiStatus = 207 StatusAlreadyReported = 208 StatusIMUsed = 226 StatusMultipleChoices = 300 StatusMovedPermanently = 301 StatusFound = 302 StatusSeeOther = 303 StatusNotModified = 304 StatusUseProxy = 305 StatusTemporaryRedirect = 307 StatusPermanentRedirect = 308 StatusBadRequest = 400 StatusUnauthorized = 401 StatusPaymentRequired = 402 StatusForbidden = 403 StatusNotFound = 404 StatusMethodNotAllowed = 405 StatusNotAcceptable = 406 StatusProxyAuthRequired = 407 StatusRequestTimeout = 408 StatusConflict = 409 StatusGone = 410 StatusLengthRequired = 411 StatusPreconditionFailed = 412 StatusRequestEntityTooLarge = 413 StatusRequestURITooLong = 414 StatusUnsupportedMediaType = 415 StatusRequestedRangeNotSatisfiable = 416 StatusExpectationFailed = 417 StatusTeapot = 418 StatusMisdirectedRequest = 421 StatusUnprocessableEntity = 422 StatusLocked = 423 StatusFailedDependency = 424 StatusUpgradeRequired = 426 StatusPreconditionRequired = 428 StatusTooManyRequests = 429 StatusUnavailableForLegalReasons = 451 StatusInternalServerError = 500 StatusNotImplemented = 501 StatusBadGateway = 502 StatusServiceUnavailable = 503 StatusGatewayTimeout = 504 StatusHTTPVersionNotSupported = 505 StatusVariantAlsoNegotiates = 506 StatusInsufficientStorage = 507 StatusLoopDetected = 508 StatusNotExtended = 510 StatusNetworkAuthenticationRequired = 511 )
HTTP status codes were stolen from net/http.
View Sourceconst ( CompressZstdSpeedNotSet = iota CompressZstdBestSpeed CompressZstdDefault CompressZstdSpeedBetter CompressZstdBestCompression )
DefaultConcurrency is the maximum number of concurrent connections the Server may serve by default (i.e. if Server.Concurrency isn't set).
DefaultDNSCacheDuration is the duration for caching resolved TCP addresses by Dial* functions.
DefaultDialTimeout is timeout used by Dial and DialDualStack for establishing TCP connections.
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.
View Sourceconst DefaultMaxRequestBodySize = 4 * 1024 * 1024
DefaultMaxRequestBodySize is the maximum request body size the server reads by default.
See Server.MaxRequestBodySize for details.
View Sourceconst FSCompressedFileSuffix = ".fasthttp.gz"
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.
View Sourcevar ( ErrMissingLocation = errors.New("missing Location header for http redirect") ErrTooManyRedirects = errors.New("too many redirects detected when doing the request") ErrHostClientRedirectToDifferentScheme = errors.New("HostClient can't follow redirects to a different protocol," + " please use Client instead") )View Source
var ( ErrNoFreeConns = errors.New("no free connections available to host") ErrConnectionClosed = errors.New("the server closed connection before returning the first response byte. " + "Make sure the server returns 'Connection: close' response header before closing the connection") ErrConnPoolStrategyNotImpl = errors.New("connection pool strategy is not implement") )View Source
var ( ErrPerIPConnLimit = errors.New("too many connections per ip") ErrConcurrencyLimit = errors.New("cannot serve the connection because Server.Concurrency concurrent connections are served") )
ErrAlreadyServing is deprecated. Deprecated: ErrAlreadyServing is never returned from Serve. See issue #633.
ErrBodyTooLarge is returned if either request or response body exceeds the given limit.
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).
View Sourcevar ErrMissingFile = errors.New("there is no uploaded file associated with the given key")
ErrMissingFile may be returned from FormFile when the is no uploaded file associated with the given multipart form key.
ErrNoArgValue is returned when Args value with the given key is missing.
View Sourcevar ErrNoMultipartForm = errors.New("request Content-Type has bad boundary or is not multipart/form-data")
ErrNoMultipartForm means that the request's Content-Type isn't 'multipart/form-data'.
View Sourcevar ErrPipelineOverflow = errors.New("pipelined requests' queue has been overflowed. Increase MaxConns and/or MaxPendingRequests")
ErrPipelineOverflow may be returned from PipelineClient.Do* if the requests' queue is overflowed.
ErrTLSHandshakeTimeout indicates there is a timeout from tls handshake.
ErrTimeout is returned from timed out calls.
View Sourcevar FSCompressedFileSuffixes = map[string]string{ "gzip": ".fasthttp.gz", "br": ".fasthttp.br", "zstd": ".fasthttp.zst", }
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.
View Sourcevar ( NetHttpFormValueFunc = func(ctx *RequestCtx, key string) []byte { v := ctx.PostArgs().Peek(key) if len(v) > 0 { return v } mf, err := ctx.MultipartForm() if err == nil && mf.Value != nil { vv := mf.Value[key] if len(vv) > 0 { return []byte(vv[0]) } } v = ctx.QueryArgs().Peek(key) if len(v) > 0 { return v } return nil } )
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.
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".
func AppendBrotliBytes(dst, src []byte) []byte
AppendBrotliBytes appends brotlied src to dst and returns the resulting dst.
func AppendBrotliBytesLevel(dst, src []byte, level int) []byte
AppendBrotliBytesLevel appends brotlied src to dst using the given compression level and returns the resulting dst.
Supported compression levels are:
func AppendDeflateBytes(dst, src []byte) []byte
AppendDeflateBytes appends deflated src to dst and returns the resulting dst.
func AppendDeflateBytesLevel(dst, src []byte, level int) []byte
AppendDeflateBytesLevel appends deflated src to dst using the given compression level and returns the resulting dst.
Supported compression levels are:
AppendGunzipBytes appends gunzipped src to dst and returns the resulting dst.
func AppendGzipBytes(dst, src []byte) []byte
AppendGzipBytes appends gzipped src to dst and returns the resulting dst.
func AppendGzipBytesLevel(dst, src []byte, level int) []byte
AppendGzipBytesLevel appends gzipped src to dst using the given compression level and returns the resulting dst.
Supported compression levels are:
AppendHTMLEscape appends html-escaped s to dst and returns the extended dst.
func AppendHTMLEscapeBytes(dst, s []byte) []byte
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.
AppendIPv4 appends string representation of the given ip v4 to dst and returns the extended dst.
AppendInflateBytes appends inflated src to dst and returns the resulting 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:
func AppendNormalizedHeaderKeyBytes(dst, key []byte) []byte
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:
func AppendQuotedArg(dst, src []byte) []byte
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.
func AppendUnquotedArg(dst, src []byte) []byte
AppendUnquotedArg appends url-decoded src to dst and returns appended dst.
dst may point to src. In this case src will be overwritten.
AppendUnzstdBytes appends unzstd src to dst and returns the resulting dst.
func AppendZstdBytes(dst, src []byte) []byte
AppendZstdBytes appends zstd src to dst and returns the resulting dst.
func AppendZstdBytesLevel(dst, src []byte, level int) []byte
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.
Dial dials the given TCP addr using tcp4.
This function has the following additional features comparing to net.Dial:
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:
DialDualStack dials the given TCP addr using both tcp4 and tcp6.
This function has the following additional features comparing to net.Dial:
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:
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:
This dialer is intended for custom code wrapping before passing to Client.DialTimeout or HostClient.DialTimeout.
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:
DialTimeout dials the given TCP addr using tcp4 using the given timeout.
This function has the following additional features comparing to net.Dial:
This dialer is intended for custom code wrapping before passing to Client.DialTimeout or HostClient.DialTimeout.
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:
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:
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:
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:
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:
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.
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.
func ListenAndServe ¶ListenAndServe serves HTTP requests from the given TCP addr using the given handler.
package main import ( "fmt" "log" "github.com/valyala/fasthttp" ) func main() { // The server will listen for incoming requests on this address. listenAddr := "127.0.0.1:80" // This function will be called by the server for each incoming request. // // RequestCtx provides a lot of functionality related to http request // processing. See RequestCtx docs for details. requestHandler := func(ctx *fasthttp.RequestCtx) { fmt.Fprintf(ctx, "Hello, world! Requested path is %q", ctx.Path()) } // Start the server with default settings. // Create Server instance for adjusting server settings. // // ListenAndServe returns only on error, so usually it blocks forever. if err := fasthttp.ListenAndServe(listenAddr, requestHandler); err != nil { log.Fatalf("error in ListenAndServe: %v", err) } }func ListenAndServeTLS ¶
ListenAndServeTLS serves HTTPS requests from the given TCP addr using the given handler.
certFile and keyFile are paths to TLS certificate and key files.
func ListenAndServeTLSEmbed ¶ListenAndServeTLSEmbed serves HTTPS requests from the given TCP addr using the given handler.
certData and keyData must contain valid TLS certificate and key data.
func ListenAndServeUNIX ¶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.
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.
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.
func ReleaseArgs(a *Args)
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.
package main import ( "fmt" "log" "net" "github.com/valyala/fasthttp" ) func main() { // Create network listener for accepting incoming requests. // // Note that you are not limited by TCP listener - arbitrary // net.Listener may be used by the server. // For example, unix socket listener or TLS listener. ln, err := net.Listen("tcp4", "127.0.0.1:8080") if err != nil { log.Fatalf("error in net.Listen: %v", err) } // This function will be called by the server for each incoming request. // // RequestCtx provides a lot of functionality related to http request // processing. See RequestCtx docs for details. requestHandler := func(ctx *fasthttp.RequestCtx) { fmt.Fprintf(ctx, "Hello, world! Requested path is %q", ctx.Path()) } // Start the server with default settings. // Create Server instance for adjusting server settings. // // Serve returns on ln.Close() or error, so usually it blocks forever. if err := fasthttp.Serve(ln, requestHandler); err != nil { log.Fatalf("error in Serve: %v", err) } }
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.
ServeFS returns HTTP response containing compressed file contents from the given fs.FS's path.
HTTP response may contain uncompressed file contents in the following cases:
Directory contents is returned if path points to directory.
See also ServeFile.
ServeFile returns HTTP response containing compressed file contents from the given path.
HTTP response may contain uncompressed file contents in the following cases:
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:
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.
func SetBodySizePoolLimit ¶ added in v1.34.0func SetBodySizePoolLimit(reqBodyLimit, respBodyLimit int)
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.
func StatusCodeIsRedirect(statusCode int) bool
StatusCodeIsRedirect returns true if the status code indicates a redirect.
StatusMessage returns HTTP status message for the given status code.
func VisitHeaderParams(b []byte, f func(key, value []byte) bool)
VisitHeaderParams calls f for each parameter in the given header bytes. It stops processing when f returns false or an invalid parameter is found. Parameter values may be quoted, in which case \ is treated as an escape character, and the value is unquoted before being passed to value. See: https://www.rfc-editor.org/rfc/rfc9110#section-5.6.6
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.
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:
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:
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:
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.
WriteUnzstd writes unzstd p to w and returns the number of uncompressed bytes written to w.
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.
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.
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.
func (a *Args) AddBytesKNoValue(key []byte)
AddBytesKNoValue adds only 'key' as argument without the '='.
Multiple values for the same key may be added.
func (a *Args) AddBytesKV(key, value []byte)
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.
All returns an iterator over key-value pairs from args.
The key and value may invalid outside the iteration loop. Make copies if you need to use them after the loop ends.
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.
Set sets 'key=value' argument.
SetBytesK sets 'key=value' argument.
func (a *Args) SetBytesKNoValue(key []byte)
SetBytesKNoValue sets 'key' argument.
func (a *Args) SetBytesKV(key, value []byte)
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.
func (a *Args) VisitAll(f func(key, value []byte))
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.
Deprecated: Use All instead.
WriteTo writes query string to w.
WriteTo implements io.WriterTo interface.
BalancingClient is the interface for clients, which may be passed to LBClient.Clients.
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.
func (c *Client) CloseIdleConnections()
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:
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:
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:
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:
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.
type ConnPoolStrategyType int
ConnPoolStrategyType define strategy of connection pool enqueue/dequeue.
A ConnState represents the state of a client connection to a server. It's used by the optional Server.ConnState hook.
const ( StateNew ConnState = iota StateActive StateIdle StateHijacked StateClosed )
Cookie represents HTTP response cookie.
Do not copy Cookie objects. Create new object and use CopyTo instead.
Cookie instance MUST NOT be used from concurrently running goroutines.
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.
AppendBytes appends cookie representation to dst and returns the extended dst.
Cookie returns cookie representation.
The returned value is valid until the Cookie reused or released (ReleaseCookie). Do not store references to the returned value. Make copies instead.
CopyTo copies src cookie to c.
func (*Cookie) Domain ¶Domain returns cookie domain.
The returned value is valid until the Cookie reused or released (ReleaseCookie). Do not store references to the returned value. Make copies instead.
Expire returns cookie expiration time.
CookieExpireUnlimited is returned if cookie doesn't expire.
HTTPOnly returns true if the cookie is http only.
Key returns cookie name.
The returned value is valid until the Cookie reused or released (ReleaseCookie). Do not store references to the returned value. Make copies instead.
MaxAge returns the seconds until the cookie is meant to expire or 0 if no max age.
Parse parses Set-Cookie header.
ParseBytes parses Set-Cookie header.
Partitioned returns true if the cookie is partitioned.
Path returns cookie path.
SameSite returns the SameSite mode.
Secure returns true if the cookie is secure.
func (*Cookie) SetDomain ¶SetDomain sets cookie domain.
SetExpire sets cookie expiration time.
Set expiration time to CookieExpireDelete for expiring (deleting) the cookie on the client.
By default cookie lifetime is limited by browser session.
SetHTTPOnly sets cookie's httpOnly flag to the given value.
SetKeyBytes sets cookie name.
SetMaxAge sets cookie expiration time based on seconds. This takes precedence over any absolute expiry set on the cookie.
'max-age' is set when the maxAge is non-zero. That is, if maxAge = 0, the 'max-age' is unset. If maxAge < 0, it indicates that the cookie should be deleted immediately, equivalent to 'max-age=0'. This behavior is consistent with the Go standard library's net/http package.
SetPartitioned sets the cookie's Partitioned flag to the given value. Set value Partitioned to true will set Secure to true and Path to / also to avoid browser rejection.
SetPath sets cookie path.
SetPathBytes sets cookie path.
SetSameSite sets the cookie's SameSite flag to the given value. Set value CookieSameSiteNoneMode will set Secure to true also to avoid browser rejection.
SetSecure sets cookie's secure flag to the given value.
SetValue sets cookie value.
SetValueBytes sets cookie value.
String returns cookie representation.
Value returns cookie value.
The returned value is valid until the Cookie reused or released (ReleaseCookie). Do not store references to the returned value. Make copies instead.
WriteTo writes cookie representation to w.
WriteTo implements io.WriterTo interface.
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:
DialFuncWithTimeout must establish connection to addr. Unlike DialFunc, it also accepts a timeout.
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 DialFuncWithTimeout always contains host and port. Example TCP addr values:
type ErrBodyStreamWritePanic struct { }
ErrBodyStreamWritePanic is returned when panic happens during writing body stream.
type ErrBrokenChunk struct { }
ErrBrokenChunk is returned when server receives a broken chunked body (Transfer-Encoding: chunked).
type ErrDialWithUpstream struct { Upstream string }
ErrDialWithUpstream wraps dial error with upstream info.
Should use errors.As to get upstream information from error:
hc := fasthttp.HostClient{Addr: "foo.com,bar.com"} err := hc.Do(req, res) var dialErr *fasthttp.ErrDialWithUpstream if errors.As(err, &dialErr) { upstream = dialErr.Upstream // 34.206.39.153:80 }
type ErrNothingRead struct { }
ErrNothingRead is returned when a keep-alive connection is closed, either because the remote closed it or because of a read timeout.
type ErrSmallBuffer struct { }
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.
FS represents settings for request handler serving static files from the local filesystem.
It is prohibited copying FS values. Create new values instead.
package main import ( "log" "github.com/valyala/fasthttp" ) func main() { fs := &fasthttp.FS{ // Path to directory to serve. Root: "/var/www/static-site", // Generate index pages if client requests directory contents. GenerateIndexPages: true, // Enable transparent compression to save network traffic. Compress: true, } // Create request handler for serving static files. h := fs.NewRequestHandler() // Start the server. if err := fasthttp.ListenAndServe(":8080", h); err != nil { log.Fatalf("error in ListenAndServe: %v", err) } }func (*FS) NewRequestHandler ¶
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.
type HijackHandler ¶type HijackHandler func(c net.Conn)
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().
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.
package main import ( "log" "github.com/valyala/fasthttp" ) func main() { // Prepare a client, which fetches webpages via HTTP proxy listening // on the localhost:8080. c := &fasthttp.HostClient{ Addr: "localhost:8080", } // Fetch google page via local proxy. statusCode, body, err := c.Get(nil, "http://google.com/foo/bar") if err != nil { log.Fatalf("Error when loading google page through local proxy: %v", err) } if statusCode != fasthttp.StatusOK { log.Fatalf("Unexpected status code: %d. Expecting %d", statusCode, fasthttp.StatusOK) } useResponseBody(body) // Fetch foobar page via local proxy. Reuse body buffer. statusCode, body, err = c.Get(body, "http://foobar.com/google/com") if err != nil { log.Fatalf("Error when loading foobar page through local proxy: %v", err) } if statusCode != fasthttp.StatusOK { log.Fatalf("Unexpected status code: %d. Expecting %d", statusCode, fasthttp.StatusOK) } useResponseBody(body) } func useResponseBody(body []byte) { // Do something with body :) }
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:
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.
LBClient balances requests among available LBClient.Clients.
It has the following features:
It is forbidden copying LBClient instances. Create new instances instead.
It is safe calling LBClient methods from concurrently running goroutines.
// Requests will be spread among these servers. servers := []string{ "google.com:80", "foobar.com:8080", "127.0.0.1:123", } // Prepare clients for each server var lbc fasthttp.LBClient for _, addr := range servers { c := &fasthttp.HostClient{ Addr: addr, } lbc.Clients = append(lbc.Clients, c) } // Send requests to load-balanced servers var req fasthttp.Request var resp fasthttp.Response for i := 0; i < 10; i++ { url := fmt.Sprintf("http://abcedfg/foo/bar/%d", i) req.SetRequestURI(url) if err := lbc.Do(&req, &resp); err != nil { log.Fatalf("Error when sending request: %v", err) } if resp.StatusCode() != fasthttp.StatusOK { log.Fatalf("unexpected status code: %d. Expecting %d", resp.StatusCode(), fasthttp.StatusOK) } useResponseBody(resp.Body()) }
AddClient adds a new client to the balanced clients and 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.
type Logger interface { Printf(format string, args ...any) }
Logger is used for logging formatted messages.
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().
NewPathPrefixStripper returns path rewriter, which removes prefixSize bytes from the path prefix.
Examples:
The returned path rewriter may be used as FS.PathRewrite .
NewPathSlashesStripper returns path rewriter, which strips slashesCount leading slashes from the path.
Examples:
The returned path rewriter may be used as FS.PathRewrite .
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"
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.
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.
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.
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.
func (*Request) AppendBody ¶AppendBody appends p to request body.
It is safe re-using p after the function returns.
func (*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.
func (*Request) BodyGunzip ¶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.
func (*Request) BodyInflate ¶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.
func (*Request) BodyStream ¶ added in v1.46.0BodyStream returns io.Reader.
You must CloseBodyStream or ReleaseRequest after you use it.
func (*Request) BodyUnbrotli ¶ added in v1.13.0BodyUnbrotli 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.
func (*Request) BodyUncompressed ¶ added in v1.38.0BodyUncompressed 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.
func (*Request) BodyWriteTo ¶BodyWriteTo writes request body to w.
func (*Request) BodyWriter ¶BodyWriter returns writer for populating request body.
ConnectionClose returns true if 'Connection: close' header is set.
func (*Request) ContinueReadBody ¶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.
func (*Request) ContinueReadBodyStream ¶ added in v1.20.0ContinueReadBodyStream 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.
GetTimeOut retrieves the timeout duration set for the Request.
This method returns a time.Duration that determines how long the request can wait before it times out. In the default use case, the timeout applies to the entire request lifecycle, including both receiving the response headers and the response body.
Host returns the host for the given request.
func (*Request) IsBodyStream ¶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:
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:
io.EOF is returned if r is closed before reading the first header byte.
func (*Request) ReadBody ¶ added in v1.32.0ReadBody reads request body from the given r, limiting the body size.
If maxBodySize > 0 and the body size exceeds maxBodySize, then ErrBodyTooLarge is returned.
func (*Request) ReadLimitBody ¶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:
io.EOF is returned if r is closed before reading the first header byte.
func (*Request) ReleaseBody ¶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.
func (req *Request) RemoveMultipartFormFiles()
RemoveMultipartFormFiles removes multipart/form-data temporary files associated with the request.
RemoveUserValue removes the given key and the value under it in Request.
RemoveUserValueBytes removes the given key and the value under it in Request.
RequestURI returns request's URI.
Reset clears request contents.
func (*Request) ResetBody ¶ResetBody resets request body.
func (req *Request) ResetUserValues()
ResetUserValues allows to reset user values from Request Context.
func (*Request) SetBody ¶SetBody sets request body.
It is safe re-using body argument after the function returns.
func (*Request) SetBodyRaw ¶ added in v1.17.0SetBodyRaw sets response body, but without copying it.
From this point onward the body argument must not be changed.
func (*Request) SetBodyStream ¶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.
func (*Request) SetBodyStreamWriter ¶SetBodyStreamWriter registers the given sw for populating request body.
This function may be used in the following cases:
Note that GET and HEAD requests cannot have body.
See also SetBodyStream.
func (req *Request) SetConnectionClose()
SetConnectionClose sets 'Connection: close' header.
SetHost sets host for the request.
SetHostBytes sets host for the request.
SetRequestURI sets RequestURI.
func (req *Request) SetRequestURIBytes(requestURI []byte)
SetRequestURIBytes sets RequestURI.
SetTimeout sets timeout for the request.
The following code:
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.
SetUserValue stores the given value (arbitrary object) under the given key in Request.
The value stored in Request 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 Request after returning from the top RequestHandler. Additionally, Close method is called on each value implementing io.Closer before removing the value from Request.
SetUserValueBytes stores the given value (arbitrary object) under the given key in Request.
The value stored in Request 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 Request are deleted after returning from RequestHandler.
String returns request representation.
Returns error message instead of request representation on error.
Use Write instead of String for performance-critical code.
func (*Request) SwapBody ¶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.
UserValue returns the value stored via SetUserValue* under the given key.
UserValueBytes returns the value stored via SetUserValue* under the given 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 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.
RequestConfig configure the per request deadline and body limits.
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.
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.
EarlyHints allows the server to hint to the browser what resources a page would need so the browser can preload them while waiting for the server's full response. Only Link headers already written to the response will be transmitted as Early Hints.
This is a HTTP/2+ feature but all browsers will either understand it or safely ignore it.
NOTE: Older HTTP/1.1 non-browser clients may face compatibility issues.
See: https://developer.chrome.com/docs/web-platform/early-hints and https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Link#syntax
Example:
func(ctx *fasthttp.RequestCtx) { ctx.Response.Header.Add("Link", "<https://fonts.google.com>; rel=preconnect") ctx.EarlyHints() time.Sleep(5*time.Second) // some time-consuming task ctx.SetStatusCode(fasthttp.StatusOK) ctx.SetBody([]byte("<html><head></head><body><h1>Hello from Fasthttp</h1></body></html>")) }
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:
There are more fine-grained methods for obtaining form values:
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:
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,
package main import ( "fmt" "log" "net" "github.com/valyala/fasthttp" ) func main() { // hijackHandler is called on hijacked connection. hijackHandler := func(c net.Conn) { fmt.Fprintf(c, "This message is sent over a hijacked connection to the client %s\n", c.RemoteAddr()) fmt.Fprintf(c, "Send me something and I'll echo it to you\n") var buf [1]byte for { if _, err := c.Read(buf[:]); err != nil { log.Printf("error when reading from hijacked connection: %v", err) return } fmt.Fprintf(c, "You sent me %q. Waiting for new data\n", buf[:]) } } // requestHandler is called for each incoming request. requestHandler := func(ctx *fasthttp.RequestCtx) { path := ctx.Path() switch { case string(path) == "/hijack": // Note that the connection is hijacked only after // returning from requestHandler and sending http response. ctx.Hijack(hijackHandler) // The connection will be hijacked after sending this response. fmt.Fprintf(ctx, "Hijacked the connection!") case string(path) == "/": fmt.Fprintf(ctx, "Root directory requested") default: fmt.Fprintf(ctx, "Requested path is %q", path) } } if err := fasthttp.ListenAndServe(":80", requestHandler); err != nil { log.Fatalf("error in ListenAndServe: %v", err) } }
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.
func (*RequestCtx) IsBodyStream ¶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.
package main import ( "fmt" "log" "github.com/valyala/fasthttp" ) func main() { requestHandler := func(ctx *fasthttp.RequestCtx) { if string(ctx.Path()) == "/top-secret" { ctx.Logger().Printf("Alarm! Alien intrusion detected!") ctx.Error("Access denied!", fasthttp.StatusForbidden) return } // Logger may be cached in local variables. logger := ctx.Logger() logger.Printf("Good request from User-Agent %q", ctx.Request.Header.UserAgent()) fmt.Fprintf(ctx, "Good request to %q", ctx.Path()) logger.Printf("Multiple log messages may be written during a single request") } if err := fasthttp.ListenAndServe(":80", requestHandler); err != nil { log.Fatalf("error in ListenAndServe: %v", err) } }
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.
func (*RequestCtx) PostBody ¶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:
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:
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 Request.
RemoveUserValueBytes removes the given key and the value under it in Request.
RequestURI returns RequestURI.
The returned bytes are valid until your request handler returns.
func (*RequestCtx) ResetBody ¶ResetBody resets response body contents.
ResetUserValues allows to reset user values from Request.
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.
func (*RequestCtx) SetBody ¶SetBody sets response body to the given value.
It is safe re-using body argument after the function returns.
func (*RequestCtx) SetBodyStream ¶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.
func (*RequestCtx) 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:
package main import ( "bufio" "fmt" "log" "time" "github.com/valyala/fasthttp" ) func main() { // Start fasthttp server for streaming responses. if err := fasthttp.ListenAndServe(":8080", responseStreamHandler); err != nil { log.Fatalf("unexpected error in server: %v", err) } } func responseStreamHandler(ctx *fasthttp.RequestCtx) { // Send the response in chunks and wait for a second between each chunk. ctx.SetBodyStreamWriter(func(w *bufio.Writer) { for i := 0; i < 10; i++ { fmt.Fprintf(w, "this is a message number %d", i) // Do not forget flushing streamed data to the client. if err := w.Flush(); err != nil { return } time.Sleep(time.Second) } }) }func (*RequestCtx) SetBodyString ¶
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 Request.
The value stored in Request 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 Request after returning from the top RequestHandler. Additionally, Close method is called on each value implementing io.Closer before removing the value from Request.
SetUserValueBytes stores the given value (arbitrary object) under the given key in Request.
The value stored in Request 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 Request 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.
package main import ( "fmt" "log" "math/rand" "time" "github.com/valyala/fasthttp" ) func main() { requestHandler := func(ctx *fasthttp.RequestCtx) { // Emulate long-running task, which touches ctx. doneCh := make(chan struct{}) go func() { workDuration := time.Millisecond * time.Duration(rand.Intn(2000)) time.Sleep(workDuration) fmt.Fprintf(ctx, "ctx has been accessed by long-running task\n") fmt.Fprintf(ctx, "The requestHandler may be finished by this time.\n") close(doneCh) }() select { case <-doneCh: fmt.Fprintf(ctx, "The task has been finished in less than a second") case <-time.After(time.Second): // Since the long-running task is still running and may access ctx, // we must call TimeoutError before returning from requestHandler. // // Otherwise the program will suffer from data races. ctx.TimeoutError("Timeout!") } } if err := fasthttp.ListenAndServe(":80", requestHandler); err != nil { log.Fatalf("error in ListenAndServe: %v", err) } }
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.
type RequestHandler ¶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 ¶CompressHandler returns RequestHandler that transparently compresses response body generated by h if the request contains 'gzip' or 'deflate' 'Accept-Encoding' header.
func CompressHandlerBrotliLevel ¶ added in v1.13.0CompressHandlerBrotliLevel 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.
otherLevel is the desired compression level for gzip and deflate.
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:
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:
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.
package main import ( "bytes" "log" "github.com/valyala/fasthttp" ) // Setup file handlers (aka 'file server config'). var ( // Handler for serving images from /img/ path, // i.e. /img/foo/bar.jpg will be served from // /var/www/images/foo/bar.jpb . imgPrefix = []byte("/img/") imgHandler = fasthttp.FSHandler("/var/www/images", 1) // Handler for serving css from /static/css/ path, // i.e. /static/css/foo/bar.css will be served from // /home/dev/css/foo/bar.css . cssPrefix = []byte("/static/css/") cssHandler = fasthttp.FSHandler("/home/dev/css", 2) // Handler for serving the rest of requests, // i.e. /foo/bar/baz.html will be served from // /var/www/files/foo/bar/baz.html . filesHandler = fasthttp.FSHandler("/var/www/files", 0) ) // Main request handler. func requestHandler(ctx *fasthttp.RequestCtx) { path := ctx.Path() switch { case bytes.HasPrefix(path, imgPrefix): imgHandler(ctx) case bytes.HasPrefix(path, cssPrefix): cssHandler(ctx) default: filesHandler(ctx) } } func main() { if err := fasthttp.ListenAndServe(":80", requestHandler); err != nil { log.Fatalf("Error in server: %v", err) } }func TimeoutHandler ¶
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.
func TimeoutWithCodeHandler ¶ added in v1.4.0TimeoutWithCodeHandler 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.
type RequestHeader struct { }
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, Transfer-Encoding, Host and User-Agent headers can only be set once and will overwrite the previous value, while the Cookie header will not clear previous cookies.
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.
func (h *RequestHeader) AddTrailer(trailer string) error
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.
func (h *RequestHeader) AddTrailerBytes(trailer []byte) (err error)
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.
All returns an iterator over key-value pairs in h.
The key and value may invalid outside the iteration loop. Copy key and/or value contents for each iteration if you need retaining them.
To get the headers in order they were received use AllInOrder.
AllInOrder returns an iterator over key-value pairs in h in the order they were received.
The key and value may invalid outside the iteration loop. Copy key and/or value contents for each iteration if you need retaining them.
The returned iterator is slightly slower than All because it has to reparse the raw headers to get the order.
AppendBytes appends request header representation to dst and returns the extended dst.
func (h *RequestHeader) ConnectionClose() bool
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 returns cookie for the given key.
CookieBytes returns cookie for the given key.
Cookies returns an iterator over key-value pairs request cookie in h.
The key and value may invalid outside the iteration loop. Copy key and/or value contents for each iteration if you need retaining them.
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.
func (h *RequestHeader) DisableNormalizing()
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:
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.
func (h *RequestHeader) EnableNormalizing()
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:
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.
func (h *RequestHeader) IsHTTP11() bool
IsHTTP11 returns true if the header 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.
func (h *RequestHeader) PeekTrailerKeys() [][]byte
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.
func (h *RequestHeader) Protocol() []byte
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 response 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.
func (h *RequestHeader) ResetConnectionClose()
ResetConnectionClose clears 'Connection: close' header if it exists.
Set sets the given 'key: value' header.
Please note that the Cookie header will not clear previous cookies, delete cookies before calling in order to reset cookies.
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.
SetBytesK sets the given 'key: value' header.
Please note that the Cookie header will not clear previous cookies, delete cookies before calling in order to reset cookies.
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.
Please note that the Cookie header will not clear previous cookies, delete cookies before calling in order to reset cookies.
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.
Please note that the Cookie header will not clear previous cookies, delete cookies before calling in order to reset cookies.
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.
Please note that the Cookie header will not clear previous cookies, delete cookies before calling in order to reset cookies.
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.
func (h *RequestHeader) SetConnectionClose()
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.
func (h *RequestHeader) SetContentType(contentType string)
SetContentType sets Content-Type header value.
func (h *RequestHeader) SetContentTypeBytes(contentType []byte)
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.
func (h *RequestHeader) SetNoDefaultContentType(noDefaultContentType bool)
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.
func (h *RequestHeader) SetTrailer(trailer string) error
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.
func (h *RequestHeader) SetTrailerBytes(trailer []byte) error
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.
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.
Trailers returns an iterator over trailers in h.
The value of trailer may invalid outside the iteration loop.
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.
Deprecated: Use All instead.
VisitAllCookie calls f for each request cookie.
f must not retain references to key and/or value after returning.
Deprecated: Use Cookies instead.
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.
Deprecated: Use AllInOrder instead.
func (h *RequestHeader) VisitAllTrailer(f func(value []byte))
VisitAllTrailer calls f for each response Trailer.
f must not retain references to value after returning.
Deprecated: Use Trailers instead.
Write writes request header to w.
WriteTo writes request header to w.
WriteTo implements io.WriterTo interface.
Resolver represents interface of the tcp 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.
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.
func (*Response) AppendBody ¶AppendBody appends p to response body.
It is safe re-using p after the function returns.
func (*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.
func (*Response) BodyGunzip ¶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.
func (*Response) BodyInflate ¶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.
func (*Response) BodyStream ¶ added in v1.46.0BodyStream returns io.Reader.
You must CloseBodyStream or ReleaseResponse after you use it.
func (*Response) BodyUnbrotli ¶ added in v1.13.0BodyUnbrotli 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.
func (*Response) BodyUncompressed ¶ added in v1.38.0BodyUncompressed 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.
func (*Response) BodyWriteTo ¶BodyWriteTo writes response body to w.
func (*Response) BodyWriter ¶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.
ConnectionClose returns true if 'Connection: close' header is set.
CopyTo copies resp contents to dst except of body stream.
func (*Response) IsBodyStream ¶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.
func (*Response) ReadBody ¶ added in v1.32.0ReadBody reads response body from the given r, limiting the body size.
If maxBodySize > 0 and the body size exceeds maxBodySize, then ErrBodyTooLarge is returned.
func (*Response) ReadLimitBody ¶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.
func (*Response) ReleaseBody ¶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.
func (*Response) ResetBody ¶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.
func (*Response) SetBody ¶SetBody sets response body.
It is safe re-using body argument after the function returns.
func (*Response) SetBodyRaw ¶ added in v1.3.0SetBodyRaw sets response body, but without copying it.
From this point onward the body argument must not be changed.
func (*Response) SetBodyStream ¶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.
func (*Response) SetBodyStreamWriter ¶SetBodyStreamWriter registers the given sw for populating response body.
This function may be used in the following cases:
See also SetBodyStream.
func (resp *Response) SetConnectionClose()
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.
func (*Response) SwapBody ¶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:
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:
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.
type ResponseHeader struct { }
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, Transfer-Encoding and Date headers can only be set once and will overwrite the previous value, while Set-Cookie will not clear previous cookies.
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, Transfer-Encoding and Date headers can only be set once and will overwrite the previous value, while Set-Cookie will not clear previous cookies.
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, Transfer-Encoding and Date headers can only be set once and will overwrite the previous value, while the Set-Cookie header will not clear previous cookies.
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, Transfer-Encoding and Date headers can only be set once and will overwrite the previous value, while Set-Cookie will not clear previous cookies.
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.
func (h *ResponseHeader) AddTrailer(trailer string) error
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.
func (h *ResponseHeader) AddTrailerBytes(trailer []byte) (err error)
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.
All returns an iterator over key-value pairs in h.
The key and value may invalid outside the iteration loop. Copy key and/or value contents for each iteration if you need retaining them.
AppendBytes appends response header representation to dst and returns the extended dst.
func (h *ResponseHeader) ConnectionClose() bool
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.
Cookies returns an iterator over key-value paired response cookie in h.
Cookie name is passed in key and the whole Set-Cookie header value is passed in value for each iteration. Value may be parsed with Cookie.ParseBytes().
The key and value may invalid outside the iteration loop. Copy key and/or value contents for each iteration if you need retaining them.
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.
func (h *ResponseHeader) DisableNormalizing()
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:
Disable header names' normalization only if know what are you doing.
func (h *ResponseHeader) EnableNormalizing()
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:
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.
func (h *ResponseHeader) IsHTTP11() bool
IsHTTP11 returns true if the header 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 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.
func (h *ResponseHeader) PeekTrailerKeys() [][]byte
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.
func (h *ResponseHeader) Protocol() []byte
Protocol returns HTTP protocol.
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.
func (h *ResponseHeader) ResetConnectionClose()
ResetConnectionClose clears 'Connection: close' header if it exists.
Server returns Server header value.
Set sets the given 'key: value' header.
Please note that the Set-Cookie header will not clear previous cookies, use SetCookie instead to reset cookies.
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.
Please note that the Set-Cookie header will not clear previous cookies, use SetCookie instead to reset cookies.
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.
Please note that the Set-Cookie header will not clear previous cookies, use SetCookie instead to reset cookies.
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.
Please note that the Set-Cookie header will not clear previous cookies, use SetCookie instead to reset cookies.
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.
Please note that the Set-Cookie header will not clear previous cookies, use SetCookie instead to reset cookies.
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.
func (h *ResponseHeader) SetConnectionClose()
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.
func (h *ResponseHeader) SetContentType(contentType string)
SetContentType sets Content-Type header value.
func (h *ResponseHeader) SetContentTypeBytes(contentType []byte)
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.
func (h *ResponseHeader) SetNoDefaultContentType(noDefaultContentType bool)
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.
func (h *ResponseHeader) SetTrailer(trailer string) error
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.
func (h *ResponseHeader) SetTrailerBytes(trailer []byte) error
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.
Trailers returns an iterator over trailers in h.
The value of trailer may invalid outside the iteration loop.
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.
Deprecated: Use All instead.
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.
Deprecated: Use Cookies instead.
func (h *ResponseHeader) VisitAllTrailer(f func(value []byte))
VisitAllTrailer calls f for each response Trailer.
f must not retain references to value after returning.
Deprecated: Use Trailers instead.
Write writes response header to w.
WriteTo writes response header to w.
WriteTo implements io.WriterTo interface.
RetryIfErrFunc defines an interface used for implementing the following functionality: When the client encounters an error during a request, the behavior—whether to retry and whether to reset the request timeout—should be determined based on the return value of this interface.
attempt indicates which attempt the current retry is due to a failure of. The first request counts as the first attempt.
err represents the error encountered while attempting the `attempts`-th request.
resetTimeout indicates whether to reuse the `Request`'s timeout as the timeout interval, rather than using the timeout after subtracting the time spent on previous failed requests. This return value is meaningful only when you use `Request.SetTimeout`, `DoTimeout`, or `DoDeadline`.
retry indicates whether to retry the current request. If it is false, the request function will immediately return with the `err`.
RetryIfFunc defines the signature of the retry if function. Request argument passed to RetryIfFunc, if there are any request errors.
RoundTripper wraps every request/response.
type ServeHandler ¶ added in v1.1.0ServeHandler must process tls.Config.NextProto negotiated requests.
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.
package main import ( "fmt" "log" "github.com/valyala/fasthttp" ) func main() { // This function will be called by the server for each incoming request. // // RequestCtx provides a lot of functionality related to http request // processing. See RequestCtx docs for details. requestHandler := func(ctx *fasthttp.RequestCtx) { fmt.Fprintf(ctx, "Hello, world! Requested path is %q", ctx.Path()) } // Create custom server. s := &fasthttp.Server{ Handler: requestHandler, // Every response will contain 'Server: My super server' header. Name: "My super server", // Other Server settings may be set here. } // Start the server listening for incoming requests on the given address. // // ListenAndServe returns only on error, so usually it blocks forever. if err := s.ListenAndServe("127.0.0.1:80"); err != nil { log.Fatalf("error in ListenAndServe: %v", err) } }
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.
GetRejectedConnectionsCount returns a number of rejected connections.
This function is intended be used by monitoring systems.
func (*Server) ListenAndServe ¶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.
func (*Server) ListenAndServeTLS ¶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.
func (*Server) ListenAndServeTLSEmbed ¶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.
func (*Server) ListenAndServeUNIX ¶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.
When ShutdownWithContext returns errors, any operation to the Server is unavailable.
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.
TCPDialer contains options to control a group of Dial calls.
Dial dials the given TCP addr using tcp4.
This function has the following additional features comparing to net.Dial:
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:
DialDualStack dials the given TCP addr using both tcp4 and tcp6.
This function has the following additional features comparing to net.Dial:
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:
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:
This dialer is intended for custom code wrapping before passing to Client.DialTimeout or HostClient.DialTimeout.
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:
DialTimeout dials the given TCP addr using tcp4 using the given timeout.
This function has the following additional features comparing to net.Dial:
This dialer is intended for custom code wrapping before passing to Client.DialTimeout or HostClient.DialTimeout.
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:
type URI struct { DisablePathNormalizing bool }
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.
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.
AppendBytes appends full uri to dst and returns the extended dst.
func (u *URI) CopyTo(dst *URI)
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.
func (u *URI) LastPathSegment() []byte
LastPathSegment returns the last part of uri path after '/'.
Examples:
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.
func (u *URI) PathOriginal() []byte
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.
RequestURI returns RequestURI - i.e. URI without Scheme and Host.
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.
func (u *URI) SetHashBytes(hash []byte)
SetHashBytes sets URI hash.
SetHost sets host for the uri.
func (u *URI) SetHostBytes(host []byte)
SetHostBytes sets host for the uri.
SetPassword sets URI password.
func (u *URI) SetPasswordBytes(password []byte)
SetPasswordBytes sets URI password.
func (u *URI) SetPathBytes(path []byte)
SetPathBytes sets URI path.
func (u *URI) SetQueryString(queryString string)
SetQueryString sets URI query string.
func (u *URI) SetQueryStringBytes(queryString []byte)
SetQueryStringBytes sets URI query string.
SetScheme sets URI scheme, i.e. http, https, ftp, etc.
func (u *URI) SetSchemeBytes(scheme []byte)
SetSchemeBytes sets URI scheme, i.e. http, https, ftp, etc.
SetUsername sets URI username.
func (u *URI) SetUsernameBytes(username []byte)
SetUsernameBytes sets URI username.
Update updates uri.
The following newURI types are accepted:
func (u *URI) UpdateBytes(newURI []byte)
UpdateBytes updates uri.
The following newURI types are accepted:
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.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4