diff --git a/docs/client/hooks.md b/docs/client/hooks.md index ccbc7d408e..d8b7965b80 100644 --- a/docs/client/hooks.md +++ b/docs/client/hooks.md @@ -2,19 +2,35 @@ id: hooks title: 🎣 Hooks description: >- - Hooks are used to manipulate request/response process of Fiber client. + Hooks are used to manipulate the request/response process of the Fiber client. sidebar_position: 4 --- -With hooks, you can manipulate the client on before request/after response stages or more complex logging/tracing cases. +Hooks allow you to intercept and modify the request or response flow of the Fiber client. They are particularly useful for: -There are 2 kinds of hooks: +- Changing request parameters (e.g., URL, headers) before sending the request. +- Logging request and response details. +- Integrating complex tracing or monitoring tools. +- Handling authentication, retries, or other custom logic. + +There are two kinds of hooks: ## Request Hooks -They are called before the HTTP request has been sent. You can use them make changes on Request object. +**Request hooks** are functions executed before the HTTP request is sent. They follow the signature: + +```go +type RequestHook func(*Client, *Request) error +``` + +A request hook receives both the `Client` and the `Request` objects, allowing you to modify the request before it leaves your application. For example, you could: -You need to use `RequestHook func(*Client, *Request) error` function signature while creating the hooks. You can use request hooks to change host URL, log request properties etc. Here is an example about how to create request hooks: +- Change the host URL. +- Log request details (method, URL, headers). +- Add or modify headers or query parameters. +- Intercept and apply custom authentication logic. + +**Example:** ```go type Repository struct { @@ -31,9 +47,9 @@ type Repository struct { func main() { cc := client.New() + // Add a request hook that modifies the request URL before sending. cc.AddRequestHook(func(c *client.Client, r *client.Request) error { r.SetURL("https://api.github.com/" + r.URL()) - return nil }) @@ -48,7 +64,6 @@ func main() { } fmt.Printf("Status code: %d\n", resp.StatusCode()) - fmt.Printf("Repository: %s\n", repo.FullName) fmt.Printf("Description: %s\n", repo.Description) fmt.Printf("Homepage: %s\n", repo.Homepage) @@ -73,17 +88,17 @@ Full Name: gofiber/fiber -There are also some builtin request hooks provide some functionalities for Fiber client. Here is a list of them: +### Built-in Request Hooks -- [parserRequestURL](https://github.com/gofiber/fiber/blob/main/client/hooks.go#L62): parserRequestURL customizes the URL according to the path params and query params. It's necessary for `PathParam` and `QueryParam` methods. +Fiber provides some built-in request hooks: -- [parserRequestHeader](https://github.com/gofiber/fiber/blob/main/client/hooks.go#L113): parserRequestHeader sets request headers, cookies, body type, referer, user agent according to client and request properties. It's necessary to make request header and cookiejar methods functional. +- **parserRequestURL**: Normalizes and customizes the URL based on path and query parameters. Required for `PathParam` and `QueryParam` methods. +- **parserRequestHeader**: Sets request headers, cookies, content type, referer, and user agent based on client and request properties. +- **parserRequestBody**: Automatically serializes the request body (JSON, XML, form, file uploads, etc.). -- [parserRequestBody](https://github.com/gofiber/fiber/blob/main/client/hooks.go#L178): parserRequestBody serializes the body automatically. It is useful for XML, JSON, form, file bodies. +If any request hook returns an error, the request is interrupted and the error is returned immediately. -:::info -If any error returns from request hook execution, it will interrupt the request and return the error. -::: +**Example with Multiple Hooks:** ```go func main() { @@ -123,9 +138,15 @@ exit status 2 ## Response Hooks -They are called after the HTTP response has been completed. You can use them to get some information about response and request. +**Response hooks** are functions executed after the HTTP response is received. They follow the signature: -You need to use `ResponseHook func(*Client, *Response, *Request) error` function signature while creating the hooks. You can use response hook for logging, tracing etc. Here is an example about how to create response hooks: +```go +type ResponseHook func(*Client, *Response, *Request) error +``` + +A response hook receives the `Client`, `Response`, and `Request` objects, allowing you to inspect and modify the response or perform additional actions such as logging, tracing, or processing response data. + +**Example:** ```go func main() { @@ -173,16 +194,19 @@ X-Cache: HIT -There are also some builtin request hooks provide some functionalities for Fiber client. Here is a list of them: +### Built-in Response Hooks -- [parserResponseCookie](https://github.com/gofiber/fiber/blob/main/client/hooks.go#L293): parserResponseCookie parses cookies and saves into the response objects and cookiejar if it's exists. +Fiber provides built-in response hooks: -- [logger](https://github.com/gofiber/fiber/blob/main/client/hooks.go#L319): logger prints some RawRequest and RawResponse information. It uses [log.CommonLogger](https://github.com/gofiber/fiber/blob/main/log/log.go#L49) interface for logging. +- **parserResponseCookie**: Parses cookies from the response and stores them in the response object and cookie jar if available. +- **logger**: Logs information about the raw request and response. It uses the `log.CommonLogger` interface. :::info -If any error is returned from executing the response hook, it will return the error without executing other response hooks. +If a response hook returns an error, it stops executing any further hooks and returns the error. ::: +**Example with Multiple Response Hooks:** + ```go func main() { cc := client.New() @@ -225,9 +249,11 @@ exit status 2 -:::info -Hooks work as FIFO (first-in-first-out). You need to check the order while adding the hooks. -::: +## Hook Execution Order + +Hooks run in FIFO order (First-In-First-Out). That means hooks are executed in the order they were added. Keep this in mind when adding multiple hooks, as the order can affect the outcome. + +**Example:** ```go func main() { diff --git a/docs/client/response.md b/docs/client/response.md index 135970069c..caee98e5e4 100644 --- a/docs/client/response.md +++ b/docs/client/response.md @@ -6,30 +6,27 @@ description: >- sidebar_position: 3 --- -The `Response` structure in Gofiber's HTTP client represents the server's response to an HTTP request. It contains all the necessary information received from the server. This includes: +The `Response` structure in Gofiber's HTTP client represents the server's response to an HTTP request. It includes: -- **Status Code**: The HTTP status code returned by the server (e.g., 200 OK, 404 Not Found). -- **Headers**: HTTP headers received from the server that provide additional information about the response. -- **Body**: The data received from the server, typically in the form of a JSON, XML, or plain text format. -- **Cookies**: Any cookies sent by the server along with the response. +- **Status Code**: The HTTP status code returned by the server (e.g., `200 OK`, `404 Not Found`). +- **Headers**: All HTTP headers returned by the server, providing additional response-related information. +- **Body**: The response body content, which can be JSON, XML, plain text, or other formats. +- **Cookies**: Any cookies the server sent along with the response. -This structure allows users to easily access and manage the data returned by the server, facilitating efficient handling of HTTP responses. +This structure makes it easy to inspect and handle the data sent back by the server. ```go type Response struct { - client *Client - request *Request - cookie []*fasthttp.Cookie - + client *Client + request *Request + cookie []*fasthttp.Cookie RawResponse *fasthttp.Response } ``` ## AcquireResponse -AcquireResponse returns an empty response object from the pool. -The returned response may be returned to the pool with ReleaseResponse when no longer needed. -This allows reducing GC load. +**AcquireResponse** returns a new (pooled) `Response` object. When finished, release it using `ReleaseResponse` to reduce GC overhead. ```go title="Signature" func AcquireResponse() *Response @@ -37,8 +34,7 @@ func AcquireResponse() *Response ## ReleaseResponse -ReleaseResponse returns the object acquired via AcquireResponse to the pool. -Do not access the released Response object; otherwise, data races may occur. +**ReleaseResponse** returns the `Response` object to the pool. Avoid using the response after releasing it to prevent data races. ```go title="Signature" func ReleaseResponse(resp *Response) @@ -46,7 +42,7 @@ func ReleaseResponse(resp *Response) ## Status -Status method returns the HTTP status string for the executed request. +**Status** returns the HTTP status message (e.g., `OK`, `Not Found`) associated with the response. ```go title="Signature" func (r *Response) Status() string @@ -54,7 +50,7 @@ func (r *Response) Status() string ## StatusCode -StatusCode method returns the HTTP status code for the executed request. +**StatusCode** returns the numeric HTTP status code of the response. ```go title="Signature" func (r *Response) StatusCode() int @@ -62,7 +58,7 @@ func (r *Response) StatusCode() int ## Protocol -Protocol method returns the HTTP response protocol used for the request. +**Protocol** returns the HTTP protocol used (e.g., `HTTP/1.1`, `HTTP/2`) for the response. ```go title="Signature" func (r *Response) Protocol() string @@ -80,6 +76,8 @@ if err != nil { fmt.Println(resp.Protocol()) ``` +**Output:** + ```text HTTP/1.1 ``` @@ -88,7 +86,7 @@ HTTP/1.1 ## Header -Header method returns the response headers. +**Header** retrieves the value of a specific response header by key. If multiple values exist for the same header, this returns the first one. ```go title="Signature" func (r *Response) Header(key string) string @@ -96,8 +94,7 @@ func (r *Response) Header(key string) string ## Headers -Headers returns all headers in the response using an iterator. You can use `maps.Collect()` to collect all headers into a map. -The returned value is valid until the response object is released. Any future calls to Headers method will return the modified value. Do not store references to returned value. Make copies instead. +**Headers** returns an iterator over all response headers. Use `maps.Collect()` to convert them into a map if desired. The returned values are only valid until the response is released, so make copies if needed. ```go title="Signature" func (r *Response) Headers() iter.Seq2[string, []string] @@ -117,6 +114,8 @@ for key, values := range resp.Headers() { } ``` +**Output:** + ```text Date => Wed, 04 Dec 2024 15:28:29 GMT Connection => keep-alive @@ -135,12 +134,14 @@ if err != nil { panic(err) } -headers := maps.Collect(resp.Headers()) // Collect all headers into a map +headers := maps.Collect(resp.Headers()) for key, values := range headers { fmt.Printf("%s => %s\n", key, strings.Join(values, ", ")) } ``` +**Output:** + ```text Date => Wed, 04 Dec 2024 15:28:29 GMT Connection => keep-alive @@ -152,8 +153,7 @@ Access-Control-Allow-Credentials => true ## Cookies -Cookies method to access all the response cookies. -The returned value is valid until the response object is released. Any future calls to Cookies method will return the modified value. Do not store references to returned value. Make copies instead. +**Cookies** returns a slice of all cookies set by the server in this response. The slice is only valid until the response is released. ```go title="Signature" func (r *Response) Cookies() []*fasthttp.Cookie @@ -174,6 +174,8 @@ for _, cookie := range cookies { } ``` +**Output:** + ```text go => fiber ``` @@ -182,7 +184,7 @@ go => fiber ## Body -Body method returns HTTP response as []byte array for the executed request. +**Body** returns the raw response body as a byte slice. ```go title="Signature" func (r *Response) Body() []byte @@ -190,7 +192,7 @@ func (r *Response) Body() []byte ## String -String method returns the body of the server response as String. +**String** returns the response body as a trimmed string. ```go title="Signature" func (r *Response) String() string @@ -198,7 +200,7 @@ func (r *Response) String() string ## JSON -JSON method will unmarshal body to json. +**JSON** unmarshals the response body into the provided variable `v` using JSON. `v` should be a pointer to a struct or a type compatible with JSON unmarshalling. ```go title="Signature" func (r *Response) JSON(v any) error @@ -222,14 +224,15 @@ if err != nil { panic(err) } -err = resp.JSON(&out) -if err != nil { +if err = resp.JSON(&out); err != nil { panic(err) } fmt.Printf("%+v\n", out) ``` +**Output:** + ```text {Slideshow:{Author:Yours Truly Date:date of publication Title:Sample Slide Show}} ``` @@ -238,7 +241,7 @@ fmt.Printf("%+v\n", out) ## XML -XML method will unmarshal body to xml. +**XML** unmarshals the response body into the provided variable `v` using XML decoding. ```go title="Signature" func (r *Response) XML(v any) error @@ -246,7 +249,7 @@ func (r *Response) XML(v any) error ## CBOR -CBOR method will unmarshal body to CBOR. +**CBOR** unmarshals the response body into `v` using CBOR decoding. ```go title="Signature" func (r *Response) CBOR(v any) error @@ -254,7 +257,7 @@ func (r *Response) CBOR(v any) error ## Save -Save method will save the body to a file or io.Writer. +**Save** writes the response body to a file or an `io.Writer`. If `v` is a string, it interprets it as a file path, creates the file (and directories if needed), and writes the response to it. If `v` is an `io.Writer`, it writes directly to it. ```go title="Signature" func (r *Response) Save(v any) error @@ -262,15 +265,15 @@ func (r *Response) Save(v any) error ## Reset -Reset clears the Response object. +**Reset** clears the `Response` object, making it ready for reuse by `ReleaseResponse`. ```go title="Signature" -func (r *Response) Reset() +func (r *Response) Reset() ``` ## Close -Close method will release the Request and Response objects; after calling Close, please do not use these objects. +**Close** releases both the associated `Request` and `Response` objects back to their pools. After calling `Close`, do not use the request or response. ```go title="Signature" func (r *Response) Close() diff --git a/docs/client/rest.md b/docs/client/rest.md index 04c7a5c44c..c66e110361 100644 --- a/docs/client/rest.md +++ b/docs/client/rest.md @@ -7,18 +7,18 @@ sidebar_position: 1 toc_max_heading_level: 5 --- -The Fiber Client for Fiber v3 is a powerful HTTP client optimized for high performance and ease of use in server-side applications. Built on top of the robust FastHTTP library, it inherits FastHTTP's high-speed HTTP protocol implementation. The client is designed to make HTTP requests both internally within services or externally to other web services. +The Fiber Client for Fiber v3 is a powerful HTTP client optimized for high performance and ease of use in server-side applications. Built atop the FastHTTP library, it inherits FastHTTP's high-speed HTTP protocol implementation. The client is designed for making both internal requests (within a microservices architecture) and external requests to other web services. ## Features -- **Lightweight & Fast**: Leveraging the minimalistic design of FastHTTP, the Fiber Client is lightweight and extremely fast. -- **Flexible Configuration**: Configure client-level settings such as timeouts, headers, and more, which apply to all requests. Specific requests can further override or merge these settings. -- **Connection Pooling**: Manages a pool of persistent connections that reduce the overhead of repeatedly establishing connections. -- **Timeouts & Retries**: Supports setting request timeouts and retry mechanisms to handle transient failures. +- **Lightweight & Fast**: Due to its FastHTTP foundation, the Fiber Client is both lightweight and extremely performant. +- **Flexible Configuration**: Set client-level configurations (e.g., timeouts, headers) that apply to all requests, while still allowing overrides at the individual request level. +- **Connection Pooling**: Maintains a pool of persistent connections, minimizing the overhead of establishing new connections for each request. +- **Timeouts & Retries**: Supports request-level timeouts and configurable retries to handle transient errors gracefully. ## Usage -To use the Fiber Client, instantiate it with the desired configuration. Here's a simple example: +Instantiate the Fiber Client with your desired configurations, then send requests: ```go package main @@ -34,7 +34,7 @@ func main() { cc := client.New() cc.SetTimeout(10 * time.Second) - // Get request + // Send a GET request resp, err := cc.Get("https://httpbin.org/get") if err != nil { panic(err) @@ -45,7 +45,7 @@ func main() { } ``` -You can check out [examples](examples.md) for more examples! +Check out [examples](examples.md) for more detailed usage examples. ```go type Client struct { @@ -65,16 +65,16 @@ type Client struct { timeout time.Duration - // user defined request hooks + // user-defined request hooks userRequestHooks []RequestHook - // client package defined request hooks + // client package-defined request hooks builtinRequestHooks []RequestHook - // user defined response hooks + // user-defined response hooks userResponseHooks []ResponseHook - // client package defined response hooks + // client package-defined response hooks builtinResponseHooks []ResponseHook jsonMarshal utils.JSONMarshal @@ -99,7 +99,7 @@ type Client struct { ### New -New creates and returns a new Client object. +**New** creates and returns a new Client object. ```go title="Signature" func New() *Client @@ -107,7 +107,7 @@ func New() *Client ### NewWithClient -NewWithClient creates and returns a new Client object from an existing client object. +**NewWithClient** creates and returns a new Client object from an existing `fasthttp.Client`. ```go title="Signature" func NewWithClient(c *fasthttp.Client) *Client @@ -115,9 +115,11 @@ func NewWithClient(c *fasthttp.Client) *Client ## REST Methods +The following methods send HTTP requests using the configured client: + ### Get -Get provides an API like axios which sends a get request. +Sends a GET request, similar to axios. ```go title="Signature" func (c *Client) Get(url string, cfg ...Config) (*Response, error) @@ -125,7 +127,7 @@ func (c *Client) Get(url string, cfg ...Config) (*Response, error) ### Post -Post provides an API like axios which send post request. +Sends a POST request, similar to axios. ```go title="Signature" func (c *Client) Post(url string, cfg ...Config) (*Response, error) @@ -133,7 +135,7 @@ func (c *Client) Post(url string, cfg ...Config) (*Response, error) ### Put -Put provides an API like axios which send put request. +Sends a PUT request, similar to axios. ```go title="Signature" func (c *Client) Put(url string, cfg ...Config) (*Response, error) @@ -141,7 +143,7 @@ func (c *Client) Put(url string, cfg ...Config) (*Response, error) ### Patch -Patch provides an API like axios which send patch request. +Sends a PATCH request, similar to axios. ```go title="Signature" func (c *Client) Patch(url string, cfg ...Config) (*Response, error) @@ -149,7 +151,7 @@ func (c *Client) Patch(url string, cfg ...Config) (*Response, error) ### Delete -Delete provides an API like axios which send delete request. +Sends a DELETE request, similar to axios. ```go title="Signature" func (c *Client) Delete(url string, cfg ...Config) (*Response, error) @@ -157,7 +159,7 @@ func (c *Client) Delete(url string, cfg ...Config) (*Response, error) ### Head -Head provides an API like axios which send head request. +Sends a HEAD request, similar to axios. ```go title="Signature" func (c *Client) Head(url string, cfg ...Config) (*Response, error) @@ -165,7 +167,7 @@ func (c *Client) Head(url string, cfg ...Config) (*Response, error) ### Options -Options provides an API like axios which send options request. +Sends an OPTIONS request, similar to axios. ```go title="Signature" func (c *Client) Options(url string, cfg ...Config) (*Response, error) @@ -173,7 +175,7 @@ func (c *Client) Options(url string, cfg ...Config) (*Response, error) ### Custom -Custom provides an API like axios which send custom request. +Sends a custom HTTP request, similar to axios, allowing you to specify any method. ```go title="Signature" func (c *Client) Custom(url, method string, cfg ...Config) (*Response, error) @@ -181,9 +183,11 @@ func (c *Client) Custom(url, method string, cfg ...Config) (*Response, error) ## Request Configuration -Config for easy to set the request parameters, it should be noted that when setting the request body will use JSON as the default serialization mechanism, while the priority of Body is higher than FormData, and the priority of FormData is higher than File. +The `Config` type helps configure request parameters. When setting the request body, JSON is used as the default serialization. The priority of the body sources is: -It can be used to configure request data while sending requests using Get, Post, etc. +1. Body +2. FormData +3. File ```go type Config struct { @@ -205,221 +209,223 @@ type Config struct { } ``` -### R +## R -R raise a request from the client. -It acquires a request from the pool. You have to release it using `ReleaseRequest()` when it's no longer needed. +**R** creates a new `Request` object from the client's request pool. Use `ReleaseRequest()` to return it to the pool when done. ```go title="Signature" func (c *Client) R() *Request ``` -### Hooks +## Hooks + +Hooks allow you to add custom logic before a request is sent or after a response is received. -#### RequestHook +### RequestHook -RequestHook Request returns user-defined request hooks. +**RequestHook** returns user-defined request hooks. ```go title="Signature" func (c *Client) RequestHook() []RequestHook ``` -#### ResponseHook +### ResponseHook -ResponseHook return user-define response hooks. +**ResponseHook** returns user-defined response hooks. ```go title="Signature" func (c *Client) ResponseHook() []ResponseHook ``` -#### AddRequestHook +### AddRequestHook -AddRequestHook Add user-defined request hooks. +Adds one or more user-defined request hooks. ```go title="Signature" func (c *Client) AddRequestHook(h ...RequestHook) *Client ``` -#### AddResponseHook +### AddResponseHook -AddResponseHook Add user-defined response hooks. +Adds one or more user-defined response hooks. ```go title="Signature" func (c *Client) AddResponseHook(h ...ResponseHook) *Client ``` -### JSON +## JSON -#### JSONMarshal +### JSONMarshal -JSONMarshal returns json marshal function in Core. +Returns the JSON marshaler function used by the client. ```go title="Signature" func (c *Client) JSONMarshal() utils.JSONMarshal ``` -#### JSONUnmarshal +### JSONUnmarshal -JSONUnmarshal returns json unmarshal function in Core. +Returns the JSON unmarshaller function used by the client. ```go title="Signature" func (c *Client) JSONUnmarshal() utils.JSONUnmarshal ``` -#### SetJSONMarshal +### SetJSONMarshal -SetJSONMarshal sets the JSON encoder. +Sets a custom JSON marshaler. ```go title="Signature" func (c *Client) SetJSONMarshal(f utils.JSONMarshal) *Client ``` -#### SetJSONUnmarshal +### SetJSONUnmarshal -Set the JSON decoder. +Sets a custom JSON unmarshaller. ```go title="Signature" func (c *Client) SetJSONUnmarshal(f utils.JSONUnmarshal) *Client ``` -### XML +## XML -#### XMLMarshal +### XMLMarshal -XMLMarshal returns xml marshal function in Core. +Returns the XML marshaler function used by the client. ```go title="Signature" func (c *Client) XMLMarshal() utils.XMLMarshal ``` -#### XMLUnmarshal +### XMLUnmarshal -XMLUnmarshal returns xml unmarshal function in Core. +Returns the XML unmarshaller function used by the client. ```go title="Signature" func (c *Client) XMLUnmarshal() utils.XMLUnmarshal ``` -#### SetXMLMarshal +### SetXMLMarshal -SetXMLMarshal sets the XML encoder. +Sets a custom XML marshaler. ```go title="Signature" func (c *Client) SetXMLMarshal(f utils.XMLMarshal) *Client ``` -#### SetXMLUnmarshal +### SetXMLUnmarshal -SetXMLUnmarshal sets the XML decoder. +Sets a custom XML unmarshaller. ```go title="Signature" func (c *Client) SetXMLUnmarshal(f utils.XMLUnmarshal) *Client ``` -### CBOR +## CBOR -#### CBORMarshal +### CBORMarshal -CBORMarshal returns CBOR marshal function in Core. +Returns the CBOR marshaler function used by the client. ```go title="Signature" func (c *Client) CBORMarshal() utils.CBORMarshal ``` -#### CBORUnmarshal +### CBORUnmarshal -CBORUnmarshal returns CBOR unmarshal function in Core. +Returns the CBOR unmarshaller function used by the client. ```go title="Signature" func (c *Client) CBORUnmarshal() utils.CBORUnmarshal ``` -#### SetCBORMarshal +### SetCBORMarshal -SetCBORMarshal sets CBOR encoder. +Sets a custom CBOR marshaler. ```go title="Signature" func (c *Client) SetCBORMarshal(f utils.CBORMarshal) *Client ``` -#### SetCBORUnmarshal +### SetCBORUnmarshal -SetCBORUnmarshal sets CBOR decoder. +Sets a custom CBOR unmarshaller. ```go title="Signature" func (c *Client) SetCBORUnmarshal(f utils.CBORUnmarshal) *Client ``` -### TLS +## TLS -#### TLSConfig +### TLSConfig -TLSConfig returns tlsConfig in client. -If the client doesn't have a tlsConfig, this function will initialize it. +Returns the client's TLS configuration. If none is set, it initializes a new one. ```go title="Signature" func (c *Client) TLSConfig() *tls.Config ``` -#### SetTLSConfig +### SetTLSConfig -SetTLSConfig sets tlsConfig in client. +Sets the TLS configuration for the client. ```go title="Signature" func (c *Client) SetTLSConfig(config *tls.Config) *Client ``` -#### SetCertificates +### SetCertificates -SetCertificates method sets client certificates into client. +Adds client certificates to the TLS configuration. ```go title="Signature" func (c *Client) SetCertificates(certs ...tls.Certificate) *Client ``` -#### SetRootCertificate +### SetRootCertificate -SetRootCertificate adds one or more root certificates into client. +Adds one or more root certificates to the client's trust store. ```go title="Signature" func (c *Client) SetRootCertificate(path string) *Client ``` -#### SetRootCertificateFromString +### SetRootCertificateFromString -SetRootCertificateFromString method adds one or more root certificates into the client. +Adds one or more root certificates from a string. ```go title="Signature" func (c *Client) SetRootCertificateFromString(pem string) *Client ``` -### SetProxyURL +## SetProxyURL -SetProxyURL sets proxy url in client. It will apply via core to hostclient. +Sets a proxy URL for the client. All subsequent requests will use this proxy. ```go title="Signature" func (c *Client) SetProxyURL(proxyURL string) error ``` -### RetryConfig +## RetryConfig -RetryConfig returns retry config in client. +Returns the retry configuration of the client. ```go title="Signature" func (c *Client) RetryConfig() *RetryConfig ``` -### SetRetryConfig +## SetRetryConfig -SetRetryConfig sets retry config in client, which is impl by addon/retry package. +Sets the retry configuration for the client. ```go title="Signature" func (c *Client) SetRetryConfig(config *RetryConfig) *Client ``` +## BaseURL + ### BaseURL -BaseURL returns baseurl in Client instance. +**BaseURL** returns the base URL currently set in the client. ```go title="Signature" func (c *Client) BaseURL() string @@ -427,12 +433,14 @@ func (c *Client) BaseURL() string ### SetBaseURL -SetBaseURL Set baseUrl which is prefix of real url. +Sets a base URL prefix for all requests made by the client. ```go title="Signature" func (c *Client) SetBaseURL(url string) *Client ``` +**Example:** + ```go title="Example" cc := client.New() cc.SetBaseURL("https://httpbin.org/") @@ -450,132 +458,118 @@ fmt.Println(string(resp.Body())) ```json { - "args": {}, + "args": {}, ... } ``` +## Headers + ### Header -Header method returns header value via key, this method will visit all field in the header +Retrieves all values of a header key at the client level. The returned values apply to all requests. ```go title="Signature" func (c *Client) Header(key string) []string ``` -#### AddHeader +### AddHeader -AddHeader method adds a single header field and its value in the client instance. -These headers will be applied to all requests raised from this client instance. -Also, it can be overridden at request level header options. +Adds a single header to all requests initiated by this client. ```go title="Signature" func (c *Client) AddHeader(key, val string) *Client ``` -#### SetHeader +### SetHeader -SetHeader method sets a single header field and its value in the client instance. -These headers will be applied to all requests raised from this client instance. -Also, it can be overridden at request level header options. +Sets a single header, overriding any existing headers with the same key. ```go title="Signature" func (c *Client) SetHeader(key, val string) *Client ``` -#### AddHeaders +### AddHeaders -AddHeaders method adds multiple headers field and its values at one go in the client instance. -These headers will be applied to all requests raised from this client instance. -Also it can be overridden at request level headers options. +Adds multiple headers at once, all applying to all future requests from this client. ```go title="Signature" func (c *Client) AddHeaders(h map[string][]string) *Client ``` -#### SetHeaders +### SetHeaders -SetHeaders method sets multiple headers field and its values at one go in the client instance. -These headers will be applied to all requests raised from this client instance. -Also it can be overridden at request level headers options. +Sets multiple headers at once, overriding previously set headers. ```go title="Signature" func (c *Client) SetHeaders(h map[string]string) *Client ``` +## Query Parameters + ### Param -Param method returns params value via key, this method will visit all field in the query param. +Returns the values for a given query parameter key. ```go title="Signature" func (c *Client) Param(key string) []string ``` -#### AddParam +### AddParam -AddParam method adds a single query param field and its value in the client instance. -These params will be applied to all requests raised from this client instance. -Also, it can be overridden at request level param options. +Adds a single query parameter for all requests. ```go title="Signature" func (c *Client) AddParam(key, val string) *Client ``` -#### SetParam +### SetParam -SetParam method sets a single query param field and its value in the client instance. -These params will be applied to all requests raised from this client instance. -Also, it can be overridden at request level param options. +Sets a single query parameter, overriding previously set values. ```go title="Signature" func (c *Client) SetParam(key, val string) *Client ``` -#### AddParams +### AddParams -AddParams method adds multiple query params field and its values at one go in the client instance. -These params will be applied to all requests raised from this client instance. -Also it can be overridden at request level params options. +Adds multiple query parameters from a map of string slices. ```go title="Signature" func (c *Client) AddParams(m map[string][]string) *Client ``` -#### SetParams +### SetParams -SetParams method sets multiple params field and its values at one go in the client instance. -These params will be applied to all requests raised from this client instance. -Also it can be overridden at request level params options. +Sets multiple query parameters from a map, overriding previously set values. ```go title="Signature" func (c *Client) SetParams(m map[string]string) *Client ``` -#### SetParamsWithStruct +### SetParamsWithStruct -SetParamsWithStruct method sets multiple params field and its values at one go in the client instance. -These params will be applied to all requests raised from this client instance. -Also it can be overridden at request level params options. +Sets multiple query parameters from a struct. Nested structs are not currently supported. ```go title="Signature" func (c *Client) SetParamsWithStruct(v any) *Client ``` -#### DelParams +### DelParams -DelParams method deletes single or multiple params field and its values in client. +Deletes one or more query parameters. ```go title="Signature" func (c *Client) DelParams(key ...string) *Client ``` +## UserAgent & Referer + ### SetUserAgent -SetUserAgent method sets the userAgent field and its value in the client instance. -This ua will be applied to all requests raised from this client instance. -Also it can be overridden at request level ua options. +Sets the user agent header for all requests. ```go title="Signature" func (c *Client) SetUserAgent(ua string) *Client @@ -583,80 +577,74 @@ func (c *Client) SetUserAgent(ua string) *Client ### SetReferer -SetReferer method sets referer field and its value in the client instance. -This referer will be applied to all requests raised from this client instance. -Also it can be overridden at request level referer options. +Sets the referer header for all requests. ```go title="Signature" func (c *Client) SetReferer(r string) *Client ``` +## Path Parameters + ### PathParam -PathParam returns the path param be set in request instance. -If the path param doesn't exist, return empty string. +Returns the value of a named path parameter, if set. ```go title="Signature" func (c *Client) PathParam(key string) string ``` -#### SetPathParam +### SetPathParam -SetPathParam method sets a single path param field and its value in the client instance. -These path params will be applied to all requests raised from this client instance. -Also it can be overridden at request level path params options. +Sets a single path parameter. ```go title="Signature" func (c *Client) SetPathParam(key, val string) *Client ``` -#### SetPathParams +### SetPathParams -SetPathParams method sets multiple path params field and its values at one go in the client instance. -These path params will be applied to all requests raised from this client instance. -Also it can be overridden at request level path params options. +Sets multiple path parameters at once. ```go title="Signature" func (c *Client) SetPathParams(m map[string]string) *Client ``` -#### SetPathParamsWithStruct +### SetPathParamsWithStruct -SetPathParamsWithStruct method sets multiple path params field and its values at one go in the client instance. -These path params will be applied to all requests raised from this client instance. -Also it can be overridden at request level path params options. +Sets multiple path parameters from a struct. ```go title="Signature" func (c *Client) SetPathParamsWithStruct(v any) *Client ``` -#### DelPathParams +### DelPathParams -DelPathParams method deletes single or multiple path params field and its values in client. +Deletes one or more path parameters. ```go title="Signature" func (c *Client) DelPathParams(key ...string) *Client ``` +## Cookies + ### Cookie -Cookie returns the cookie be set in request instance. -If cookie doesn't exist, return empty string. +Returns the value of a named cookie if set at the client level. ```go title="Signature" func (c *Client) Cookie(key string) string ``` -#### SetCookie +### SetCookie -SetCookie method sets a single cookie field and its value in the client instance. -These cookies will be applied to all requests raised from this client instance. -Also it can be overridden at request level cookie options. +Sets a single cookie for all requests. ```go title="Signature" func (c *Client) SetCookie(key, val string) *Client ``` +**Example:** + ```go title="Example" cc := client.New() cc.SetCookie("john", "doe") @@ -682,71 +670,73 @@ fmt.Println(string(resp.Body())) -#### SetCookies +### SetCookies -SetCookies method sets multiple cookies field and its values at one go in the client instance. -These cookies will be applied to all requests raised from this client instance. -Also it can be overridden at request level cookie options. +Sets multiple cookies at once. ```go title="Signature" func (c *Client) SetCookies(m map[string]string) *Client ``` -#### SetCookiesWithStruct +### SetCookiesWithStruct -SetCookiesWithStruct method sets multiple cookies field and its values at one go in the client instance. -These cookies will be applied to all requests raised from this client instance. -Also it can be overridden at request level cookies options. +Sets multiple cookies from a struct. ```go title="Signature" func (c *Client) SetCookiesWithStruct(v any) *Client ``` -#### DelCookies +### DelCookies -DelCookies method deletes single or multiple cookies field and its values in client. +Deletes one or more cookies. ```go title="Signature" func (c *Client) DelCookies(key ...string) *Client ``` +## Timeout + ### SetTimeout -SetTimeout method sets timeout val in client instance. -This value will be applied to all requests raised from this client instance. -Also, it can be overridden at request level timeout options. +Sets a default timeout for all requests, which can be overridden per request. ```go title="Signature" func (c *Client) SetTimeout(t time.Duration) *Client ``` +## Debugging + ### Debug -Debug enable log debug level output. +Enables debug-level logging output. ```go title="Signature" func (c *Client) Debug() *Client ``` -#### DisableDebug +### DisableDebug -DisableDebug disables log debug level output. +Disables debug-level logging output. ```go title="Signature" func (c *Client) DisableDebug() *Client ``` +## Cookie Jar + ### SetCookieJar -SetCookieJar sets cookie jar in client instance. +Assigns a cookie jar to the client to store and manage cookies across requests. ```go title="Signature" func (c *Client) SetCookieJar(cookieJar *CookieJar) *Client ``` +## Dial & Logger + ### SetDial -SetDial sets dial function in client. +Sets a custom dial function. ```go title="Signature" func (c *Client) SetDial(dial fasthttp.DialFunc) *Client @@ -754,7 +744,7 @@ func (c *Client) SetDial(dial fasthttp.DialFunc) *Client ### SetLogger -SetLogger sets logger instance in client. +Sets the logger instance used by the client. ```go title="Signature" func (c *Client) SetLogger(logger log.CommonLogger) *Client @@ -762,15 +752,17 @@ func (c *Client) SetLogger(logger log.CommonLogger) *Client ### Logger -Logger returns logger instance of client. +Returns the current logger instance. ```go title="Signature" func (c *Client) Logger() log.CommonLogger ``` +## Reset + ### Reset -Reset clears the Client object +Clears and resets the client to its default state. ```go title="Signature" func (c *Client) Reset() @@ -778,12 +770,11 @@ func (c *Client) Reset() ## Default Client -Default client is default client object of Gofiber and created using `New()`. -You can configurate it as you wish or replace it with another clients. +Fiber provides a default client (created with `New()`). You can configure it or replace it as needed. ### C -C gets default client. +**C** returns the default client. ```go title="Signature" func C() *Client @@ -847,10 +838,10 @@ func Options(url string, cfg ...Config) (*Response, error) ### Replace -Replace the defaultClient, the returned function can undo. +**Replace** replaces the default client with a new one. It returns a function that can restore the old client. :::caution -The default client should not be changed concurrently. +Do not modify the default client concurrently. ::: ```go title="Signature"