client
import "github.com/gofiber/fiber/v3/client"
Package client exposes Fiber's HTTP client built on top of fasthttp.
It allows constructing new clients or wrapping existing fasthttp transports so applications can share pools, dialers, and TLS settings between Fiber and lower-level fasthttp integrations.
The code was originally taken from https://github.com/valyala/fasthttp/pull/526.
Core pipeline scaffolds request execution for Fiber's HTTP client, including hook invocation, retry orchestration, and timeout management around fasthttp transports.
Transport adapters unify fasthttp clients behind a shared interface so the Fiber client can coordinate behavior like redirects, TLS overrides, and dial customizations regardless of the underlying transport type.
Variables
var (
ErrTimeoutOrCancel = errors.New("timeout or cancel")
ErrURLFormat = errors.New("the URL is incorrect")
ErrPathParamInHost = errors.New("the path parameter value is not valid in a host")
ErrPathParamInPath = errors.New("the path parameter value is not a single path segment")
ErrNotSupportSchema = errors.New("protocol not supported; only http or https are allowed")
ErrFileNoName = errors.New("the file should have a name")
ErrBodyType = errors.New("the body type should be []byte")
ErrNotSupportSaveMethod = errors.New("only file paths and io.Writer are supported")
ErrBodyTypeNotSupported = errors.New("the body type is not supported")
)var (
// ErrRedirectDowngrade is returned when a redirect leads from an HTTPS origin
// to plaintext HTTP, on every transport. Set MaxRedirects to 0 to take such a
// hop yourself instead.
ErrRedirectDowngrade = errors.New("client: HTTPS to HTTP redirect blocked")
// ErrRedirectTrailers is returned when a redirect that drops the request body finds
// its trailer section announcing more than fieldname.MaxTrailers names, which the
// section goes with. Set MaxRedirects to 0 to take such a hop yourself instead.
ErrRedirectTrailers = errors.New("client: too many trailer names to follow a redirect")
)var ErrClientNil = errors.New("client cannot be nil")var ErrFailedToAppendCert = errors.New("failed to append certificate")Functions
func AcquireCookieJar() *CookieJar
Source: client/cookiejar.go:71
AcquireCookieJar returns an empty CookieJar object from the pool.
func AcquireFile(setter ...SetFileFunc) *File
Source: client/request.go:1141
AcquireFile returns a (pooled) File object and applies the provided SetFileFunc functions to it.
func AcquireRequest() *Request
Source: client/request.go:1092
AcquireRequest returns a new (pooled) Request object.
func AcquireResponse() *Response
Source: client/response.go:336
AcquireResponse returns a new (pooled) Response object. When done, release it with ReleaseResponse to reduce GC load.
func C() *Client
C returns the default client.
func Delete(url string, cfg ...Config) (*Response, error)
Delete sends a DELETE request using the default client.
func Get(url string, cfg ...Config) (*Response, error)
Get sends a GET request using the default client.
func Head(url string, cfg ...Config) (*Response, error)
Head sends a HEAD request using the default client.
func New() *Client
New creates and returns a new Client object.
func NewWithClient(c *fasthttp.Client) *Client
NewWithClient creates and returns a new Client object from an existing fasthttp.Client.
Fiber cannot tell whether that client has served a host already, and a fasthttp.Client gives each host the path normalizing setting it had when it first served that host. So unless the client was created with DisablePathNormalizing set, SetDisablePathNormalizing changes what is sent to hosts not yet served, but the check that keeps a path parameter value inside its segment stays on.
func NewWithHostClient(c *fasthttp.HostClient) *Client
NewWithHostClient creates and returns a new Client object from an existing fasthttp.HostClient.
func NewWithLBClient(c *fasthttp.LBClient) *Client
NewWithLBClient creates and returns a new Client object from an existing fasthttp.LBClient.
func Options(url string, cfg ...Config) (*Response, error)
Options sends an OPTIONS request using the default client.
func Patch(url string, cfg ...Config) (*Response, error)
Patch sends a PATCH request using the default client.
func Post(url string, cfg ...Config) (*Response, error)
Post sends a POST request using the default client.
func Put(url string, cfg ...Config) (*Response, error)
Put sends a PUT request using the default client.
func Query(url string, cfg ...Config) (*Response, error)
Query sends a QUERY request using the default client.
func ReleaseCookieJar(c *CookieJar)
Source: client/cookiejar.go:81
ReleaseCookieJar returns a CookieJar object to the pool.
func ReleaseFile(f *File)
Source: client/request.go:1162
ReleaseFile returns the File object to the pool. Do not use the released File afterward to avoid data races.
func ReleaseRequest(req *Request)
Source: client/request.go:1102
ReleaseRequest returns the Request object to the pool. Do not use the released Request afterward to avoid data races.
func ReleaseResponse(resp *Response)
Source: client/response.go:346
ReleaseResponse returns the Response object to the pool. Do not use the released Response afterward to avoid data races.
func Replace(c *Client) func()
Replace replaces the defaultClient with a new one, returning a function to restore the old client.
func SetFileFieldName(p string) SetFileFunc
Source: client/request.go:1120
SetFileFieldName sets the file's field name.
func SetFileName(n string) SetFileFunc
Source: client/request.go:1113
SetFileName sets the file name.
func SetFilePath(p string) SetFileFunc
Source: client/request.go:1127
SetFilePath sets the file path.
func SetFileReader(r io.ReadCloser) SetFileFunc
Source: client/request.go:1134
SetFileReader sets the file's reader.
func SetValWithStruct(p WithStruct, tagName string, v any)
Source: client/request.go:1175
SetValWithStruct sets values using a struct. The struct's fields are examined via reflection. p is a type that implements WithStruct. tagName defines the struct tag to look for. v is the struct containing data.
Fields in v should be string, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64, complex64, complex128 or bool. Arrays or slices are inserted sequentially with the same key. Other types are ignored.
Types
type Client
Client provides Fiber's high-level HTTP API while delegating transport work to fasthttp.Client, fasthttp.HostClient, or fasthttp.LBClient implementations.
Settings configured on the client are shared across every request and may be overridden per request when needed. Client is safe for concurrent request execution after configuration is complete. Concurrent configuration changes require external synchronization.
type Client struct {
// contains filtered or unexported fields
}func (c *Client) AddFinalRequestHook(h ...RequestHook) *Client
AddFinalRequestHook registers hooks for the point after request serialization and immediately before transport execution.
func (c *Client) AddHeader(key, val string) *Client
AddHeader adds a single header field and its value to the client. These headers apply to all requests.
func (c *Client) AddHeaders(h map[string][]string) *Client
AddHeaders adds multiple header fields and their values to the client.
func (c *Client) AddParam(key, val string) *Client
AddParam adds a single query parameter and its value to the client. These params will be applied to all requests created from this client instance.
func (c *Client) AddParams(m map[string][]string) *Client
AddParams adds multiple query parameters and their values to the client.
func (c *Client) AddRequestHook(h ...RequestHook) *Client
AddRequestHook adds user-defined request hooks.
func (c *Client) AddResponseHook(h ...ResponseHook) *Client
AddResponseHook adds user-defined response hooks.
func (c *Client) BaseURL() string
BaseURL returns the client's base URL.
func (c *Client) CBORMarshal() utils.CBORMarshal
CBORMarshal returns the CBOR marshal function used by the client.
func (c *Client) CBORUnmarshal() utils.CBORUnmarshal
CBORUnmarshal returns the CBOR unmarshal function used by the client.
func (c *Client) CloseIdleConnections()
CloseIdleConnections closes idle connections on the underlying fasthttp transport when supported.
func (c *Client) Cookie(key string) string
Cookie returns the value of the specified cookie. Returns an empty string if it does not exist.
func (c *Client) Custom(url, method string, cfg ...Config) (*Response, error)
Custom sends a request with a custom method to the specified URL, similar to axios.
func (c *Client) Debug() *Client
Debug enables debug-level logging output: after each response, the raw request and response, headers and bodies included, are logged through the client's logger.
func (c *Client) DelCookies(key ...string) *Client
DelCookies deletes one or more cookies and their values from the client.
func (c *Client) DelParams(key ...string) *Client
DelParams deletes one or more query parameters and their values from the client.
func (c *Client) DelPathParams(key ...string) *Client
DelPathParams deletes one or more path parameters and their values from the client.
func (c *Client) Delete(url string, cfg ...Config) (*Response, error)
Delete sends a DELETE request to the specified URL, similar to axios.
func (c *Client) DisableDebug() *Client
DisableDebug disables debug-level logging output.
func (c *Client) DisablePathNormalizing() bool
DisablePathNormalizing reports whether path normalizing is disabled for the client.
func (c *Client) Do(req *fasthttp.Request, resp *fasthttp.Response) error
Do executes the request using the underlying fasthttp transport.
It mirrors fasthttp.Client.Do, fasthttp.HostClient.Do, or fasthttp.LBClient.Do depending on how the Fiber client was constructed.
func (c *Client) DoDeadline(req *fasthttp.Request, resp *fasthttp.Response, deadline time.Time) error
DoDeadline executes the request and waits for a response until the provided deadline. It mirrors the behavior of the respective fasthttp client's DoDeadline implementation.
func (c *Client) DoRedirects(req *fasthttp.Request, resp *fasthttp.Response, maxRedirects int) error
DoRedirects executes the request following redirects up to maxRedirects. It honors SetRedirectSensitiveHeaders.
func (c *Client) DoTimeout(req *fasthttp.Request, resp *fasthttp.Response, timeout time.Duration) error
DoTimeout executes the request and waits for a response up to the provided timeout. It mirrors the behavior of the respective fasthttp client's DoTimeout implementation.
func (c *Client) FasthttpClient() *fasthttp.Client
FasthttpClient returns the underlying *fasthttp.Client if the client was created with one.
A client created by New bounds dials and TLS handshakes through this client's ConfigureClient hook, which has one slot: a hook of your own, set before the first request, applies its settings and then calls the hook that was there.
func (c *Client) FinalRequestHook() []RequestHook
FinalRequestHook returns a copy of the user-defined final request hooks.
func (c *Client) Get(url string, cfg ...Config) (*Response, error)
Get sends a GET request to the specified URL, similar to axios.
func (c *Client) Head(url string, cfg ...Config) (*Response, error)
Head sends a HEAD request to the specified URL, similar to axios.
func (c *Client) Header(key string) []string
Header returns all header values associated with the provided key.
func (c *Client) HostClient() *fasthttp.HostClient
HostClient returns the underlying fasthttp.HostClient if the client was created with one.
func (c *Client) JSONMarshal() utils.JSONMarshal
JSONMarshal returns the JSON marshal function used by the client.
func (c *Client) JSONUnmarshal() utils.JSONUnmarshal
JSONUnmarshal returns the JSON unmarshal function used by the client.
func (c *Client) LBClient() *fasthttp.LBClient
LBClient returns the underlying fasthttp.LBClient if the client was created with one.
func (c *Client) Logger() log.CommonLogger
Logger returns the logger instance used by the client.
func (c *Client) MaxResponseBodySize() int
MaxResponseBodySize returns the largest response body the client buffers, in bytes. Zero or less means no limit.
func (c *Client) Options(url string, cfg ...Config) (*Response, error)
Options sends an OPTIONS request to the specified URL, similar to axios.
func (c *Client) Param(key string) []string
Param returns all values of the specified query parameter.
func (c *Client) Patch(url string, cfg ...Config) (*Response, error)
Patch sends a PATCH request to the specified URL, similar to axios.
func (c *Client) PathParam(key string) string
PathParam returns the value of the specified path parameter. Returns an empty string if it does not exist.
func (c *Client) Post(url string, cfg ...Config) (*Response, error)
Post sends a POST request to the specified URL, similar to axios.
func (c *Client) Put(url string, cfg ...Config) (*Response, error)
Put sends a PUT request to the specified URL, similar to axios.
func (c *Client) Query(url string, cfg ...Config) (*Response, error)
Query sends a QUERY request to the specified URL, similar to axios.
func (c *Client) R() *Request
R creates a new Request associated with the client.
func (c *Client) RedirectSensitiveHeaders() []string
RedirectSensitiveHeaders returns a copy of the names set with SetRedirectSensitiveHeaders.
func (c *Client) RequestHook() []RequestHook
RequestHook returns a copy of the user-defined request hooks.
func (c *Client) Reset()
Reset resets the client to its default state, clearing most configurations and replacing the underlying transport with a new fasthttp.Client so future requests resume with Fiber's standard transport settings.
func (c *Client) ResponseHook() []ResponseHook
ResponseHook returns a copy of the user-defined response hooks.
func (c *Client) RetryConfig() *RetryConfig
RetryConfig returns a copy of the current retry configuration.
func (c *Client) SetBaseURL(url string) *Client
SetBaseURL sets the base URL prefix for all requests made by the client.
func (c *Client) SetCBORMarshal(f utils.CBORMarshal) *Client
SetCBORMarshal sets the CBOR marshal function to use.
func (c *Client) SetCBORUnmarshal(f utils.CBORUnmarshal) *Client
SetCBORUnmarshal sets the CBOR unmarshal function to use.
func (c *Client) SetCertificates(certs ...tls.Certificate) *Client
SetCertificates adds certificates to the client's TLS configuration.
func (c *Client) SetCookie(key, val string) *Client
SetCookie sets a single cookie and its value in the client.
func (c *Client) SetCookieJar(cookieJar *CookieJar) *Client
SetCookieJar sets the cookie jar for the client.
func (c *Client) SetCookies(m map[string]string) *Client
SetCookies sets multiple cookies and their values in the client.
func (c *Client) SetCookiesWithStruct(v any) *Client
SetCookiesWithStruct sets multiple cookies and their values using a struct.
func (c *Client) SetDial(dial fasthttp.DialFunc) *Client
SetDial sets the custom dial function for the client. It also removes a DialTimeout function, the one SetProxyURL installs included, which fasthttp would call instead.
func (c *Client) SetDisablePathNormalizing(disable bool) *Client
SetDisablePathNormalizing configures the client to disable or enable path normalizing.
fasthttp normalizes the path of a request when it writes it, according to the client that sends it, so the setting is applied to the wrapped fasthttp client (every host client behind a load balancer): a client created with NewWithClient, NewWithHostClient or NewWithLBClient changes the one it wraps, for everyone who shares it. Call it before the first request, because a fasthttp.Client copies the setting into the host clients it has already created only when it creates them.
The check that keeps a path parameter value inside its segment is lifted only when the wrapped client is known to send the path as built: a client from New, a fasthttp.Client handed to NewWithClient with the setting already on, or a host client or balancer whose host clients all have it on. Once a request has gone out through a fasthttp.Client that normalized, it stays on.
func (c *Client) SetHeader(key, val string) *Client
SetHeader sets a single header field and its value in the client, overriding any previously set value.
func (c *Client) SetHeaders(h map[string]string) *Client
SetHeaders method sets multiple headers field and its values at one go in the client instance. These headers will be applied to all requests created from this client instance. Also it can be overridden at request level headers options.
func (c *Client) SetJSONMarshal(f utils.JSONMarshal) *Client
SetJSONMarshal sets the JSON marshal function to use.
func (c *Client) SetJSONUnmarshal(f utils.JSONUnmarshal) *Client
SetJSONUnmarshal sets the JSON unmarshal function to use.
func (c *Client) SetLogger(logger log.CommonLogger) *Client
SetLogger sets the logger instance used by the client.
func (c *Client) SetMaxResponseBodySize(size int) *Client
SetMaxResponseBodySize sets the largest response body the client buffers, in bytes; a larger one fails with fasthttp.ErrBodyTooLarge. A client from New starts at 100 MiB, a wrapped fasthttp client keeps its own setting, and zero or less removes the limit. A streamed body is not limited. Call it before the first request: a fasthttp.Client gives each host the limit it has when it first serves that host.
func (c *Client) SetParam(key, val string) *Client
SetParam sets a single query parameter and its value in the client.
func (c *Client) SetParams(m map[string]string) *Client
SetParams sets multiple query parameters and their values in the client.
func (c *Client) SetParamsWithStruct(v any) *Client
SetParamsWithStruct sets multiple query parameters and their values using a struct.
func (c *Client) SetPathParam(key, val string) *Client
SetPathParam sets a single path parameter and its value in the client.
func (c *Client) SetPathParams(m map[string]string) *Client
SetPathParams sets multiple path parameters and their values in the client.
func (c *Client) SetPathParamsWithStruct(v any) *Client
SetPathParamsWithStruct sets multiple path parameters and their values using a struct.
func (c *Client) SetProxyURL(proxyURL string) error
SetProxyURL sets the proxy URL for the client. This affects all subsequent requests. The timeout of a request bounds its dial through the proxy as well; without one, the dial and the proxy handshake each get fasthttp.DefaultDialTimeout.
func (c *Client) SetRedirectSensitiveHeaders(names ...string) *Client
SetRedirectSensitiveHeaders names request headers, such as an X-Api-Key of your own, to drop with the built-in set when a redirect leaves the host a request started on. Names match case-insensitively; no names clears the list. Request.SetRedirectSensitiveHeaders adds names for one request.
func (c *Client) SetReferer(r string) *Client
SetReferer sets the Referer header for the client.
func (c *Client) SetRetryConfig(config *RetryConfig) *Client
SetRetryConfig sets the retry configuration for the client.
func (c *Client) SetRootCertificate(path string) *Client
SetRootCertificate adds one or more root certificates to the client's TLS configuration. It panics when the file cannot be read or holds no valid PEM certificate.
func (c *Client) SetRootCertificateFromString(pem string) *Client
SetRootCertificateFromString adds one or more root certificates from a string to the client's TLS configuration. It panics when the string holds no valid PEM certificate.
func (c *Client) SetStreamResponseBody(enable bool) *Client
SetStreamResponseBody enables or disables response body streaming. When enabled, the response body can be read as a stream using BodyStream() instead of being fully loaded into memory. This is useful for large responses or server-sent events.
func (c *Client) SetTLSConfig(config *tls.Config) *Client
SetTLSConfig sets the TLS configuration for the client.
func (c *Client) SetTimeout(t time.Duration) *Client
SetTimeout sets the timeout value for the client. This applies to all requests unless overridden at the request level.
func (c *Client) SetUserAgent(ua string) *Client
SetUserAgent sets the User-Agent header for the client.
func (c *Client) SetXMLMarshal(f utils.XMLMarshal) *Client
SetXMLMarshal sets the XML marshal function to use.
func (c *Client) SetXMLUnmarshal(f utils.XMLUnmarshal) *Client
SetXMLUnmarshal sets the XML unmarshal function to use.
func (c *Client) StreamResponseBody() bool
StreamResponseBody returns the current StreamResponseBody setting.
func (c *Client) TLSConfig() *tls.Config
TLSConfig returns the client's TLS configuration. If none is set, it initializes a new one.
func (c *Client) XMLMarshal() utils.XMLMarshal
XMLMarshal returns the XML marshal function used by the client.
func (c *Client) XMLUnmarshal() utils.XMLUnmarshal
XMLUnmarshal returns the XML unmarshal function used by the client.
type Config
Config is used to easily set request parameters. Note that when setting a request body, JSON is used as the default serialization mechanism. The priority is: Body > FormData > File.
RedirectSensitiveHeaders is passed to Request.SetRedirectSensitiveHeaders; an empty list changes nothing.
type Config struct {
Ctx context.Context //nolint:containedctx // It's needed to be stored in the config.
Body any
Header map[string]string
Param map[string]string
Cookie map[string]string
PathParam map[string]string
FormData map[string]string
UserAgent string
Referer string
File []*File
RedirectSensitiveHeaders []string
Timeout time.Duration
MaxRedirects int
DisablePathNormalizing bool
}Fields
Ctx context.ContextBody anyHeader map[string]stringParam map[string]stringCookie map[string]stringPathParam map[string]stringFormData map[string]stringUserAgent stringReferer stringFile []*FileRedirectSensitiveHeaders []stringTimeout time.DurationMaxRedirects intDisablePathNormalizing bool
type Cookie
Cookie is a map used to store cookies.
type Cookie map[string]stringfunc (c Cookie) Add(key, val string)
Add adds a cookie key-value pair.
func (c Cookie) All() iter.Seq2[string, string]
All returns an iterator over cookie key-value pairs.
The returned key and value should not be retained after the iteration loop.
func (c Cookie) Del(key string)
Del deletes a cookie by key.
func (c Cookie) DelCookies(key ...string)
DelCookies deletes multiple cookies by keys.
func (c Cookie) Reset()
Reset clears the Cookie map.
func (c Cookie) SetCookie(key, val string)
SetCookie sets a single cookie value.
func (c Cookie) SetCookies(m map[string]string)
SetCookies sets multiple cookies from a map.
func (c Cookie) SetCookiesWithStruct(v any)
SetCookiesWithStruct sets cookies from a struct. Nested structs are not currently supported.
type CookieJar
Source: client/cookiejar.go:89
CookieJar manages cookie storage for the client. CookieJar is safe for concurrent use, except Release. Release must not run concurrently with other methods, and the jar must not be used after Release.
type CookieJar struct {
// contains filtered or unexported fields
}func (cj *CookieJar) Get(uri *fasthttp.URI) []*fasthttp.Cookie
Source: client/cookiejar.go:173
Get returns all cookies stored for a given URI. If there are no cookies for the provided host, the returned slice will be nil.
A host-only cookie is returned without a Domain attribute, so it stays host-only when it is passed back to Set or SetByHost.
The CookieJar keeps its own copies of cookies, so it is safe to release the returned cookies after use.
func (cj *CookieJar) Release()
Source: client/cookiejar.go:806
Release releases all stored cookies. After this, the CookieJar is empty and must not be used again.
func (cj *CookieJar) Set(uri *fasthttp.URI, cookies ...*fasthttp.Cookie)
Source: client/cookiejar.go:341
Set stores the given cookies for the specified URI host. A stored cookie is replaced only when it matches on both key and normalized path within the same storage scope; cookies sharing a key at different paths coexist, and the most specific one is sent first (RFC 6265 Section 5.4).
A cookie with no usable Path attribute is scoped to the URI's default-path (RFC 6265 Section 5.1.4), the same rule applied to a Set-Cookie received for that URI: cookies set against "/a/b" are scoped to "/a", not to the whole host. Set an explicit Path on the cookie to widen it.
CookieJar stores copies of the provided cookies, so they may be safely released after use.
func (cj *CookieJar) SetByHost(host []byte, cookies ...*fasthttp.Cookie)
Source: client/cookiejar.go:357
SetByHost stores the given cookies for the specified host. A stored cookie is replaced only when it matches on both key and normalized path within the same storage scope; cookies sharing a key at different paths coexist.
There is no request path to derive a default-path from, so a cookie with no usable Path attribute is scoped to "/". Use Set when a URI is available and the RFC 6265 Section 5.1.4 scoping is wanted.
CookieJar stores copies of the provided cookies, so they may be safely released after use.
func (cj *CookieJar) SetKeyValue(host, key, value string)
Source: client/cookiejar.go:477
SetKeyValue sets a cookie for the specified host with the given key and value.
This function helps prevent extra allocations by avoiding duplication of repeated cookies.
func (cj *CookieJar) SetKeyValueBytes(host string, key, value []byte)
Source: client/cookiejar.go:489
SetKeyValueBytes sets a cookie for the specified host using byte slices for the key and value.
This function helps prevent extra allocations by avoiding duplication of repeated cookies.
type File
Source: client/request.go:1021
File represents a file to be sent with the request.
type File struct {
// contains filtered or unexported fields
}func (f *File) Reset()
Source: client/request.go:1067
Reset clears the File object and closes a reader no request body was built from.
func (f *File) SetFieldName(n string)
Source: client/request.go:1036
SetFieldName sets the key associated with the file in the body.
func (f *File) SetName(n string)
Source: client/request.go:1031
SetName sets the file's name.
func (f *File) SetPath(p string)
Source: client/request.go:1041
SetPath sets the file's path.
func (f *File) SetReader(r io.ReadCloser)
Source: client/request.go:1047
SetReader sets the file's reader, which the file owns from here on: it is closed once, when the request body is built, when the file is reset or released, or when it is replaced.
type FormData
FormData wraps fasthttp.Args for URL-encoded bodies and form data.
type FormData struct {
*fasthttp.Args
}Fields
*fasthttp.Args
func (f *FormData) Add(key, val string)
Add adds a single form field.
func (f *FormData) AddWithMap(m map[string][]string)
AddWithMap adds multiple form fields from a map.
func (f *FormData) DelData(key ...string)
Source: client/request.go:1009
DelData deletes multiple form fields.
func (f *FormData) Keys() []string
Keys returns all keys from the form data.
func (f *FormData) Reset()
Source: client/request.go:1016
Reset clears the FormData object.
func (f *FormData) Set(key, val string)
Set sets a single form field, overriding previously set values.
func (f *FormData) SetWithMap(m map[string]string)
SetWithMap sets multiple form fields from a map, overriding previously set values.
func (f *FormData) SetWithStruct(v any)
Source: client/request.go:1004
SetWithStruct sets multiple form fields from a struct. Nested structs are not currently supported.
type Header
Header wraps fasthttp.RequestHeader, storing headers for both client and request.
type Header struct {
*fasthttp.RequestHeader
}Fields
*fasthttp.RequestHeader
func (h *Header) AddHeaders(r map[string][]string)
AddHeaders adds multiple headers from a map.
func (h *Header) PeekMultiple(key string) []string
PeekMultiple returns multiple values of a header field with the same key.
func (h *Header) SetHeaders(r map[string]string)
SetHeaders sets multiple headers from a map, overriding previously set values.
type PathParam
PathParam is a map used to store path parameters.
type PathParam map[string]stringfunc (p PathParam) Add(key, val string)
Add adds a path parameter key-value pair.
func (p PathParam) All() iter.Seq2[string, string]
All returns an iterator over path parameter key-value pairs.
The returned key and value should not be retained after the iteration loop.
func (p PathParam) Del(key string)
Del deletes a path parameter by key.
func (p PathParam) DelParams(key ...string)
DelParams deletes multiple path parameters.
func (p PathParam) Reset()
Reset clears the PathParam map.
func (p PathParam) SetParam(key, val string)
SetParam sets a single path parameter.
func (p PathParam) SetParams(m map[string]string)
SetParams sets multiple path parameters from a map.
func (p PathParam) SetParamsWithStruct(v any)
SetParamsWithStruct sets multiple path parameters from a struct. Nested structs are not currently supported.
type QueryParam
QueryParam wraps fasthttp.Args for query parameters.
type QueryParam struct {
*fasthttp.Args
}Fields
*fasthttp.Args
func (p *QueryParam) AddParams(r map[string][]string)
AddParams adds multiple parameters from a map.
func (p *QueryParam) Keys() []string
Keys returns all keys from the query parameters.
func (p *QueryParam) Set(key, val string)
Set sets a single parameter, overriding previously set values. It shadows Args.Set, which replaces only the first pair with that key.
func (p *QueryParam) SetParams(r map[string]string)
SetParams sets multiple parameters from a map, overriding previously set values.
func (p *QueryParam) SetParamsWithStruct(v any)
SetParamsWithStruct sets multiple parameters from a struct. Nested structs are not currently supported.
type Request
Request contains all data related to an HTTP request.
type Request struct {
RawRequest *fasthttp.Request
// contains filtered or unexported fields
}Fields
RawRequest *fasthttp.Request
func (r *Request) AddFile(path string) *Request
AddFile adds a single file by its path.
func (r *Request) AddFileWithReader(name string, reader io.ReadCloser) *Request
AddFileWithReader adds a file using an io.ReadCloser. The request takes over the reader and closes it, see File.SetReader.
func (r *Request) AddFiles(files ...*File) *Request
AddFiles adds multiple files at once.
func (r *Request) AddFormData(key, val string) *Request
AddFormData adds a single form field and value to the Request.
func (r *Request) AddFormDataWithMap(m map[string][]string) *Request
AddFormDataWithMap adds multiple form fields and values to the Request.
func (r *Request) AddHeader(key, val string) *Request
AddHeader adds a single header field and value to the Request.
func (r *Request) AddHeaders(h map[string][]string) *Request
AddHeaders adds multiple header fields and values at once.
func (r *Request) AddParam(key, val string) *Request
AddParam adds a single query parameter and value to the Request.
func (r *Request) AddParams(m map[string][]string) *Request
AddParams adds multiple query parameters and their values at once.
func (r *Request) AllFormData() iter.Seq2[string, []string]
AllFormData returns an iterator over all form fields. Use maps.Collect() to gather them into a map if needed.
The returned values are only valid until the request object is released. Do not store references to returned values; make copies instead.
func (r *Request) Boundary() string
Boundary returns the multipart boundary used by the Request.
func (r *Request) Client() *Client
Client returns the Client instance associated with this Request.
func (r *Request) Context() context.Context
Context returns the context associated with the Request. If not set, a background context is returned.
func (r *Request) Cookie(key string) string
Cookie returns the value of a named cookie. If the cookie does not exist, an empty string is returned.
func (r *Request) Cookies() iter.Seq2[string, string]
Cookies returns an iterator over all cookies. Use maps.Collect() to gather them into a map if needed.
func (r *Request) Custom(url, method string) (*Response, error)
Custom sends a request with a custom HTTP method to the given URL.
func (r *Request) DelCookies(key ...string) *Request
DelCookies deletes one or more cookies.
func (r *Request) DelFormData(key ...string) *Request
DelFormData deletes one or more form fields.
func (r *Request) DelParams(key ...string) *Request
DelParams deletes one or more query parameters.
func (r *Request) DelPathParams(key ...string) *Request
DelPathParams deletes one or more path parameters.
func (r *Request) Delete(url string) (*Response, error)
Delete sends a DELETE request to the given URL.
func (r *Request) DisablePathNormalizing() bool
DisablePathNormalizing reports whether path normalizing is disabled for the Request.
func (r *Request) File(name string) *File
File returns the file associated with the given name. If no name was provided during addition, it attempts to match by the file's base name.
func (r *Request) FileByPath(path string) *File
FileByPath returns the file associated with the given file path.
func (r *Request) Files() []*File
Files returns all files added to the Request.
The returned values are only valid until the request object is released. Do not store references to returned values; make copies instead.
func (r *Request) FormData(key string) []string
FormData returns all values associated with a form field.
func (r *Request) Get(url string) (*Response, error)
Get sends a GET request to the given URL.
func (r *Request) Head(url string) (*Response, error)
Head sends a HEAD request to the given URL.
func (r *Request) Header(key string) []string
Header returns all values associated with the given header key.
func (r *Request) Headers() iter.Seq2[string, []string]
Headers returns an iterator over all headers in the Request. Use maps.Collect() to gather them into a map if needed.
The returned values are only valid until the request object is released. Do not store references to returned values; make copies instead.
func (r *Request) MaxRedirects() int
MaxRedirects returns the maximum number of redirects configured for the Request.
func (r *Request) Method() string
Method returns the HTTP method set in the Request.
func (r *Request) Options(url string) (*Response, error)
Options sends an OPTIONS request to the given URL.
func (r *Request) Param(key string) []string
Param returns all values associated with the given query parameter.
func (r *Request) Params() iter.Seq2[string, []string]
Params returns an iterator over all query parameters in the Request. Use maps.Collect() to gather them into a map if needed.
The returned values are only valid until the request object is released. Do not store references to returned values; make copies instead.
func (r *Request) Patch(url string) (*Response, error)
Patch sends a PATCH request to the given URL.
func (r *Request) PathParam(key string) string
PathParam returns the value of a named path parameter. If the parameter does not exist, an empty string is returned.
func (r *Request) PathParams() iter.Seq2[string, string]
PathParams returns an iterator over all path parameters. Use maps.Collect() to gather them into a map if needed.
func (r *Request) Post(url string) (*Response, error)
Post sends a POST request to the given URL.
func (r *Request) Put(url string) (*Response, error)
Put sends a PUT request to the given URL.
func (r *Request) Query(url string) (*Response, error)
Query sends a QUERY request to the given URL.
func (r *Request) RedirectSensitiveHeaders() []string
RedirectSensitiveHeaders returns a copy of this Request's names.
func (r *Request) Referer() string
Referer returns the Referer header set in the Request.
func (r *Request) Reset()
Reset clears the Request object, returning it to its default state. Used by ReleaseRequest to recycle the object.
func (r *Request) ResetPathParams() *Request
ResetPathParams deletes all path parameters.
func (r *Request) Send() (*Response, error)
Send executes the Request.
func (r *Request) SetBoundary(b string) *Request
SetBoundary sets the multipart boundary.
func (r *Request) SetCBOR(v any) *Request
SetCBOR sets the request body to a CBOR-encoded value.
func (r *Request) SetClient(c *Client) *Request
SetClient sets the Client instance for the Request.
func (r *Request) SetContext(ctx context.Context) *Request
SetContext sets the context for the Request. Its deadline bounds the exchange at the transport, and its cancellation ends the exchange of a client made by New as well, which closes the connection it was using once the connection is open; a dial still in progress runs to its end first, and a response read with SetStreamResponseBody is not reached. A wrapped fasthttp client returns the caller at once while its exchange ends on its own, when the server answers or its timeouts pass. See https://blog.golang.org/context article and the "context" package documentation.
func (r *Request) SetCookie(key, val string) *Request
SetCookie sets a single cookie, overriding any previously set value.
func (r *Request) SetCookies(m map[string]string) *Request
SetCookies sets multiple cookies at once, overriding previously set values.
func (r *Request) SetCookiesWithStruct(v any) *Request
SetCookiesWithStruct sets multiple cookies from a struct, overriding previously set values.
func (r *Request) SetDisablePathNormalizing(disable bool) *Request
SetDisablePathNormalizing configures the Request to disable or enable path normalizing.
func (r *Request) SetFormData(key, val string) *Request
SetFormData sets a single form field and value, overriding any previously set value.
func (r *Request) SetFormDataWithMap(m map[string]string) *Request
SetFormDataWithMap sets multiple form fields and values at once, overriding previously set values.
func (r *Request) SetFormDataWithStruct(v any) *Request
SetFormDataWithStruct sets multiple form fields from a struct, overriding previously set values.
func (r *Request) SetHeader(key, val string) *Request
SetHeader sets a single header field and value in the Request, overriding any previously set value.
func (r *Request) SetHeaders(h map[string]string) *Request
SetHeaders sets multiple header fields and values at once, overriding previously set values.
func (r *Request) SetJSON(v any) *Request
SetJSON sets the request body to a JSON-encoded value.
func (r *Request) SetMaxRedirects(count int) *Request
SetMaxRedirects sets the maximum number of redirects, overriding any previously set value.
func (r *Request) SetMethod(method string) *Request
SetMethod sets the HTTP method for the Request. It is recommended to use the specialized methods (e.g., Get, Post) instead.
func (r *Request) SetParam(key, val string) *Request
SetParam sets a single query parameter and value in the Request, overriding any previously set value.
func (r *Request) SetParams(m map[string]string) *Request
SetParams sets multiple query parameters and their values at once, overriding previously set values.
func (r *Request) SetParamsWithStruct(v any) *Request
SetParamsWithStruct sets multiple query parameters from a struct, overriding previously set values.
func (r *Request) SetPathParam(key, val string) *Request
SetPathParam sets a single path parameter and value, overriding any previously set value.
func (r *Request) SetPathParams(m map[string]string) *Request
SetPathParams sets multiple path parameters and values at once, overriding previously set values.
func (r *Request) SetPathParamsWithStruct(v any) *Request
SetPathParamsWithStruct sets multiple path parameters from a struct, overriding previously set values.
func (r *Request) SetRawBody(v []byte) *Request
SetRawBody sets the request body to raw bytes.
func (r *Request) SetRedirectSensitiveHeaders(names ...string) *Request
SetRedirectSensitiveHeaders names headers to drop when a redirect leaves the host, in addition to the client's list and the built-in set. It replaces this Request's previous names.
func (r *Request) SetReferer(referer string) *Request
SetReferer sets the Referer header, overriding any previously set value.
func (r *Request) SetTimeout(t time.Duration) *Request
SetTimeout sets the timeout for the Request, overriding any previously set value.
func (r *Request) SetURL(url string) *Request
SetURL sets the URL for the Request.
func (r *Request) SetUserAgent(ua string) *Request
SetUserAgent sets the User-Agent header, overriding any previously set value.
func (r *Request) SetXML(v any) *Request
SetXML sets the request body to an XML-encoded value.
func (r *Request) Timeout() time.Duration
Timeout returns the timeout duration set in the Request.
func (r *Request) URL() string
URL returns the URL set in the Request.
func (r *Request) UserAgent() string
UserAgent returns the User-Agent header set in the Request.
type RequestHook
RequestHook is a function invoked before the request is sent. It receives a Client and a Request. Mutate the Request, not the shared Client config: the Client is read concurrently by in-flight requests (see the Client type's concurrency contract), so per-request changes belong on the Request.
type RequestHook func(*Client, *Request) errortype Response
Response represents the result of a request. It provides access to the response data.
type Response struct {
RawResponse *fasthttp.Response
// contains filtered or unexported fields
}Fields
RawResponse *fasthttp.Response
func (r *Response) Body() []byte
Source: client/response.go:189
Body returns the HTTP response body as a byte slice.
func (r *Response) BodyStream() io.Reader
Source: client/response.go:196
BodyStream returns the response body as a stream reader. Note: When using BodyStream(), the response body is not copied to memory, so calling Body() afterwards may return an empty slice.
func (r *Response) CBOR(v any) error
Source: client/response.go:224
CBOR unmarshal the response body into the given any using CBOR.
func (r *Response) Close()
Source: client/response.go:313
Close releases the Response back to its pool, along with the Request when a client helper created it. A Request from AcquireRequest stays the caller's. After calling Close, do not use these objects.
func (r *Response) Cookies() []*fasthttp.Cookie
Source: client/response.go:184
Cookies returns all cookies set by the response.
The returned values are valid only until the response object is released. Do not store references to returned values; make copies instead.
func (r *Response) Header(key string) string
Source: client/response.go:106
Header returns the value of the specified response header field.
Only the header section is read: a trailer field is no header (RFC 9110 Section 6.5.1) and is left to RawResponse.Header.PeekTrailer.
func (r *Response) Headers() iter.Seq2[string, []string]
Source: client/response.go:137
Headers returns all headers in the response using an iterator. Use maps.Collect() to gather them into a map if needed. Like Header, it leaves out the fields of the trailer section.
The returned values are valid only until the response object is released. Do not store references to returned values; make copies instead.
func (r *Response) IsStreaming() bool
Source: client/response.go:205
IsStreaming returns true if the response body is being streamed.
func (r *Response) JSON(v any) error
Source: client/response.go:215
JSON unmarshal the response body into the given any using JSON.
func (r *Response) Protocol() string
Protocol returns the HTTP protocol used for the request.
func (r *Response) Reset()
Source: client/response.go:294
Reset clears the Response object, making it ready for reuse.
func (r *Response) Save(v any) error
Source: client/response.go:245
Save writes the response body to a file or io.Writer. If a string path is provided, it creates directories if needed, then writes to a file. If an io.Writer is provided, it writes directly to it. When streaming is enabled, the body is read directly from the stream.
func (r *Response) Status() string
Status returns the HTTP status message of the executed request.
func (r *Response) StatusCode() int
StatusCode returns the HTTP status code of the executed request.
func (r *Response) String() string
Source: client/response.go:210
String returns the response body as a trimmed string.
func (r *Response) XML(v any) error
Source: client/response.go:233
XML unmarshal the response body into the given any using XML.
type ResponseHook
ResponseHook is a function invoked after a response is received. It receives a Client, Response, and Request. Mutate the Response or act on it; do not mutate the shared Client config, which is read concurrently by other in-flight requests (see the Client type's concurrency contract).
type ResponseHook func(*Client, *Response, *Request) errortype RetryConfig
RetryConfig is an alias for the retry.Config type from the addon/retry package.
type RetryConfig = retry.Configtype SetFileFunc
Source: client/request.go:1110
SetFileFunc defines a function that modifies a File object.
type SetFileFunc func(f *File)type WithStruct
WithStruct is implemented by types that allow data to be stored from a struct via reflection.
type WithStruct interface {
Add(name, obj string)
Del(name string)
}Methods
Add func(name, obj string)Del func(name string)