π₯οΈ REST
The Fiber Client is a high-performance HTTP client built on FastHTTP. It handles both internal service calls and external requests with minimal overhead.
Use the index to jump straight to any client method; filter by name or by category:
Featuresβ
- Lightweight and fast: built on FastHTTP for minimal overhead.
- Flexible configuration: set global defaults like timeouts or headers and override them per request.
- Connection pooling: reuses persistent connections instead of opening new ones.
- Timeouts and retries: supports per-request deadlines and retry policies for transient errors.
Usageβ
Create a client with any required configuration, then send requests:
package main
import (
"fmt"
"time"
"github.com/gofiber/fiber/v3/client"
)
func main() {
cc := client.New()
cc.SetTimeout(10 * time.Second)
// Send a GET request
resp, err := cc.Get("https://httpbin.org/get")
if err != nil {
panic(err)
}
fmt.Printf("Status: %d\n", resp.StatusCode())
fmt.Printf("Body: %s\n", string(resp.Body()))
}
See examples for more detailed usage.
type Client struct {
logger log.CommonLogger
transport httpClientTransport
header *Header
params *QueryParam
cookies *Cookie
path *PathParam
jsonMarshal utils.JSONMarshal
jsonUnmarshal utils.JSONUnmarshal
xmlMarshal utils.XMLMarshal
xmlUnmarshal utils.XMLUnmarshal
cborMarshal utils.CBORMarshal
cborUnmarshal utils.CBORUnmarshal
cookieJar *CookieJar
retryConfig *RetryConfig
baseURL string
userAgent string
referer string
userRequestHooks []RequestHook
builtinRequestHooks []RequestHook
userResponseHooks []ResponseHook
builtinResponseHooks []ResponseHook
timeout time.Duration
mu sync.RWMutex
isDebug bool
isPathNormalizingDisabled bool
}
Newβ
New creates and returns a new Client object.
func New() *Client
NewWithClientβ
NewWithClient creates and returns a new Client object from an existing fasthttp.Client.
func NewWithClient(c *fasthttp.Client) *Client
REST Methodsβ
These helpers mirror axios-style method names and send HTTP requests using the configured client:
Getβ
Sends a GET request.
func (c *Client) Get(url string, cfg ...Config) (*Response, error)
Postβ
Sends a POST request.
func (c *Client) Post(url string, cfg ...Config) (*Response, error)
Putβ
Sends a PUT request.
func (c *Client) Put(url string, cfg ...Config) (*Response, error)
Patchβ
Sends a PATCH request.
func (c *Client) Patch(url string, cfg ...Config) (*Response, error)
Queryβ
Sends a QUERY request.
func (c *Client) Query(url string, cfg ...Config) (*Response, error)
Deleteβ
Sends a DELETE request.
func (c *Client) Delete(url string, cfg ...Config) (*Response, error)
Headβ
Sends a HEAD request.
func (c *Client) Head(url string, cfg ...Config) (*Response, error)
Optionsβ
Sends an OPTIONS request.
func (c *Client) Options(url string, cfg ...Config) (*Response, error)
Customβ
Sends a request with any HTTP method.
func (c *Client) Custom(url, method string, cfg ...Config) (*Response, error)
Request Configurationβ
The Config type holds per-request parameters. JSON is used to serialize the body by default. If multiple body sources are set, precedence is:
- Body
- FormData
- File
type Config struct {
Ctx context.Context
UserAgent string
Referer string
Header map[string]string
Param map[string]string
Cookie map[string]string
PathParam map[string]string
Timeout time.Duration
MaxRedirects int
Body any
FormData map[string]string
File []*File
}
Rβ
R gets a Request object from the pool. Call ReleaseRequest when finished.
func (c *Client) R() *Request
Hooksβ
Hooks allow you to add custom logic before a request is sent or after a response is received.
RequestHookβ
RequestHook returns user-defined request hooks.
func (c *Client) RequestHook() []RequestHook
ResponseHookβ
ResponseHook returns user-defined response hooks.
func (c *Client) ResponseHook() []ResponseHook
AddRequestHookβ
Adds one or more user-defined request hooks.
func (c *Client) AddRequestHook(h ...RequestHook) *Client
AddResponseHookβ
Adds one or more user-defined response hooks.
func (c *Client) AddResponseHook(h ...ResponseHook) *Client
JSONβ
JSONMarshalβ
Returns the JSON marshaler function used by the client.
func (c *Client) JSONMarshal() utils.JSONMarshal
JSONUnmarshalβ
Returns the JSON unmarshaler function used by the client.
func (c *Client) JSONUnmarshal() utils.JSONUnmarshal
SetJSONMarshalβ
Sets a custom JSON marshaler.
func (c *Client) SetJSONMarshal(f utils.JSONMarshal) *Client
SetJSONUnmarshalβ
Sets a custom JSON unmarshaler.
func (c *Client) SetJSONUnmarshal(f utils.JSONUnmarshal) *Client
XMLβ
XMLMarshalβ
Returns the XML marshaler function used by the client.
func (c *Client) XMLMarshal() utils.XMLMarshal
XMLUnmarshalβ
Returns the XML unmarshaler function used by the client.
func (c *Client) XMLUnmarshal() utils.XMLUnmarshal
SetXMLMarshalβ
Sets a custom XML marshaler.
func (c *Client) SetXMLMarshal(f utils.XMLMarshal) *Client
SetXMLUnmarshalβ
Sets a custom XML unmarshaler.
func (c *Client) SetXMLUnmarshal(f utils.XMLUnmarshal) *Client
CBORβ
CBORMarshalβ
Returns the CBOR marshaler function used by the client.
func (c *Client) CBORMarshal() utils.CBORMarshal
CBORUnmarshalβ
Returns the CBOR unmarshaler function used by the client.
func (c *Client) CBORUnmarshal() utils.CBORUnmarshal
SetCBORMarshalβ
Sets a custom CBOR marshaler.
func (c *Client) SetCBORMarshal(f utils.CBORMarshal) *Client
SetCBORUnmarshalβ
Sets a custom CBOR unmarshaler.
func (c *Client) SetCBORUnmarshal(f utils.CBORUnmarshal) *Client
TLSβ
TLSConfigβ
Returns the client's TLS configuration. If none is set, it initializes a new
configuration with MinVersion defaulting to TLS 1.2.
func (c *Client) TLSConfig() *tls.Config
SetTLSConfigβ
Sets the TLS configuration for the client.
func (c *Client) SetTLSConfig(config *tls.Config) *Client
SetCertificatesβ
Adds client certificates to the TLS configuration.
func (c *Client) SetCertificates(certs ...tls.Certificate) *Client
SetRootCertificateβ
Adds one or more root certificates to the client's trust store.
func (c *Client) SetRootCertificate(path string) *Client
SetRootCertificateFromStringβ
Adds one or more root certificates from a string.
func (c *Client) SetRootCertificateFromString(pem string) *Client
SetProxyURLβ
Sets a proxy URL for the client. All subsequent requests will use this proxy.
func (c *Client) SetProxyURL(proxyURL string) error
Response Streamingβ
StreamResponseBodyβ
Returns whether response body streaming is enabled. When enabled, the response body is not fully loaded into memory and can be read as a stream using Response.BodyStream(). This is useful for handling large responses or server-sent events (SSE).
func (c *Client) StreamResponseBody() bool
SetStreamResponseBodyβ
Enables or disables response body streaming. When enabled, responses can be consumed incrementally without loading the entire body into memory.
func (c *Client) SetStreamResponseBody(enable bool) *Client
Example:
cc := client.New()
cc.SetStreamResponseBody(true)
resp, err := cc.Get("https://example.com/large-file")
if err != nil {
panic(err)
}
defer resp.Close()
// Check if response is streaming
if resp.IsStreaming() {
// Read body incrementally
reader := resp.BodyStream()
buf := make([]byte, 4096)
for {
n, err := reader.Read(buf)
if n > 0 {
// Process chunk...
}
if err == io.EOF {
break
}
if err != nil {
panic(err)
}
}
} else {
// Regular body access
body := resp.Body()
fmt.Println(string(body))
}
Server-Sent Events Example:
cc := client.New()
cc.SetStreamResponseBody(true)
resp, err := cc.Get("https://example.com/events")
if err != nil {
panic(err)
}
defer resp.Close()
reader := bufio.NewReader(resp.BodyStream())
for {
line, err := reader.ReadString('\n')
if err == io.EOF {
break
}
if err != nil {
panic(err)
}
fmt.Print(line) // Process SSE event
}
RetryConfigβ
Returns the retry configuration of the client.
func (c *Client) RetryConfig() *RetryConfig
SetRetryConfigβ
Sets the retry configuration for the client.
func (c *Client) SetRetryConfig(config *RetryConfig) *Client
BaseURLβ
BaseURLβ
BaseURL returns the base URL currently set in the client.
func (c *Client) BaseURL() string
SetBaseURLβ
Sets a base URL prefix for all requests made by the client.
func (c *Client) SetBaseURL(url string) *Client
Example:
cc := client.New()
cc.SetBaseURL("https://httpbin.org/")
resp, err := cc.Get("/get")
if err != nil {
panic(err)
}
fmt.Println(string(resp.Body()))
Click here to see the result
{
"args": {},
...
}
Headersβ
Headerβ
Retrieves all values of a header key at the client level. The returned values apply to all requests.
func (c *Client) Header(key string) []string
AddHeaderβ
Adds a single header to all requests initiated by this client.
func (c *Client) AddHeader(key, val string) *Client
SetHeaderβ
Sets a single header, overriding any existing headers with the same key.
func (c *Client) SetHeader(key, val string) *Client
AddHeadersβ
Adds multiple headers at once, all applying to all future requests from this client.
func (c *Client) AddHeaders(h map[string][]string) *Client
SetHeadersβ
Sets multiple headers at once, overriding previously set headers.
func (c *Client) SetHeaders(h map[string]string) *Client
Query Parametersβ
Paramβ
Returns the values for a given query parameter key.
func (c *Client) Param(key string) []string
AddParamβ
Adds a single query parameter for all requests.
func (c *Client) AddParam(key, val string) *Client
SetParamβ
Sets a single query parameter, overriding previously set values.
func (c *Client) SetParam(key, val string) *Client
AddParamsβ
Adds multiple query parameters from a map of string slices.
func (c *Client) AddParams(m map[string][]string) *Client
SetParamsβ
Sets multiple query parameters from a map, overriding previously set values.
func (c *Client) SetParams(m map[string]string) *Client
SetParamsWithStructβ
Sets multiple query parameters from a struct. Nested structs are not currently supported.
func (c *Client) SetParamsWithStruct(v any) *Client
DelParamsβ
Deletes one or more query parameters.
func (c *Client) DelParams(key ...string) *Client
UserAgent & Refererβ
SetUserAgentβ
Sets the user agent header for all requests.
func (c *Client) SetUserAgent(ua string) *Client
SetRefererβ
Sets the referer header for all requests.
func (c *Client) SetReferer(r string) *Client
Path Parametersβ
PathParamβ
Returns the value of a named path parameter, if set.
func (c *Client) PathParam(key string) string
SetPathParamβ
Sets a single path parameter.
func (c *Client) SetPathParam(key, val string) *Client
SetPathParamsβ
Sets multiple path parameters at once.
func (c *Client) SetPathParams(m map[string]string) *Client
SetPathParamsWithStructβ
Sets multiple path parameters from a struct.
func (c *Client) SetPathParamsWithStruct(v any) *Client
DelPathParamsβ
Deletes one or more path parameters.
func (c *Client) DelPathParams(key ...string) *Client
Cookiesβ
Cookieβ
Returns the value of a named cookie if set at the client level.
func (c *Client) Cookie(key string) string
SetCookieβ
Sets a single cookie for all requests.
func (c *Client) SetCookie(key, val string) *Client
Example:
cc := client.New()
cc.SetCookie("john", "doe")
resp, err := cc.Get("https://httpbin.org/cookies")
if err != nil {
panic(err)
}
fmt.Println(string(resp.Body()))
Click here to see the result
{
"cookies": {
"john": "doe"
}
}
SetCookiesβ
Sets multiple cookies at once.
func (c *Client) SetCookies(m map[string]string) *Client
SetCookiesWithStructβ
Sets multiple cookies from a struct.
func (c *Client) SetCookiesWithStruct(v any) *Client
DelCookiesβ
Deletes one or more cookies.
func (c *Client) DelCookies(key ...string) *Client
Timeoutβ
SetTimeoutβ
Sets a default timeout for all requests, which can be overridden per request.
func (c *Client) SetTimeout(t time.Duration) *Client
Debuggingβ
Debugβ
Enables debug-level logging output.
func (c *Client) Debug() *Client
DisableDebugβ
Disables debug-level logging output.
func (c *Client) DisableDebug() *Client
Cookie Jarβ
SetCookieJarβ
Assigns a cookie jar to the client to store and manage cookies across requests.
func (c *Client) SetCookieJar(cookieJar *CookieJar) *Client
Dial & Loggerβ
SetDialβ
Sets a custom dial function.
func (c *Client) SetDial(dial fasthttp.DialFunc) *Client
SetLoggerβ
Sets the logger instance used by the client.
func (c *Client) SetLogger(logger log.CommonLogger) *Client
Loggerβ
Returns the current logger instance.
func (c *Client) Logger() log.CommonLogger
Resetβ
Resetβ
Clears and resets the client to its default state and reinstates the default
fasthttp.Client transport.
func (c *Client) Reset()
Default Clientβ
Fiber provides a default client (created with New()). You can configure it or replace it as needed.
Cβ
C returns the default client.
func C() *Client
Getβ
Get is a convenience method that sends a GET request using the defaultClient.
func Get(url string, cfg ...Config) (*Response, error)
Postβ
Post is a convenience method that sends a POST request using the defaultClient.
func Post(url string, cfg ...Config) (*Response, error)
Putβ
Put is a convenience method that sends a PUT request using the defaultClient.
func Put(url string, cfg ...Config) (*Response, error)
Patchβ
Patch is a convenience method that sends a PATCH request using the defaultClient.
func Patch(url string, cfg ...Config) (*Response, error)
Queryβ
Query is a convenience method that sends a QUERY request using the defaultClient.
func Query(url string, cfg ...Config) (*Response, error)
Deleteβ
Delete is a convenience method that sends a DELETE request using the defaultClient.
func Delete(url string, cfg ...Config) (*Response, error)
Headβ
Head sends a HEAD request using the defaultClient, a convenience method.
func Head(url string, cfg ...Config) (*Response, error)
Optionsβ
Options is a convenience method that sends an OPTIONS request using the defaultClient.
func Options(url string, cfg ...Config) (*Response, error)
Replaceβ
Replace replaces the default client with a new one. It returns a function that can restore the old client.
Replacing the default client is concurrency-safe, but mutating the same Client instance still requires external synchronization.
func Replace(c *Client) func()