mirror of https://github.com/gofiber/fiber.git
docs: add docs for new client (#2991)
* docs: add docs for new client * Add docs for client hooks * Add docs for client examples * Some fixes. * docs: add docs for new client * docs: add docs for new client * Add more examples for methods * Update docs/client/examples.md Co-authored-by: Jason McNeil <sixcolors@mac.com> * Add one more example for cookiejar * apply review * apply review * apply review * docs: add docs for new client * docs: add docs for new client --------- Co-authored-by: René <rene@gofiber.io> Co-authored-by: Jason McNeil <sixcolors@mac.com>pull/3000/head
parent
109ccdd4ad
commit
3ba90c0fb0
|
@ -117,7 +117,7 @@ func (c *Client) JSONMarshal() utils.JSONMarshal {
|
|||
return c.jsonMarshal
|
||||
}
|
||||
|
||||
// SetJSONMarshal Set json encoder.
|
||||
// SetJSONMarshal sets the JSON encoder.
|
||||
func (c *Client) SetJSONMarshal(f utils.JSONMarshal) *Client {
|
||||
c.jsonMarshal = f
|
||||
return c
|
||||
|
@ -475,7 +475,7 @@ func (c *Client) Debug() *Client {
|
|||
return c
|
||||
}
|
||||
|
||||
// DisableDebug disenable log debug level output.
|
||||
// DisableDebug disables log debug level output.
|
||||
func (c *Client) DisableDebug() *Client {
|
||||
c.debug = false
|
||||
return c
|
||||
|
@ -574,7 +574,7 @@ func (c *Client) Logger() log.CommonLogger {
|
|||
return c.logger
|
||||
}
|
||||
|
||||
// Reset clear Client object
|
||||
// Reset clears the Client object
|
||||
func (c *Client) Reset() {
|
||||
c.fasthttp = &fasthttp.Client{}
|
||||
c.baseURL = ""
|
||||
|
|
|
@ -121,21 +121,19 @@ func (r *Request) SetContext(ctx context.Context) *Request {
|
|||
}
|
||||
|
||||
// Header method returns header value via key,
|
||||
// this method will visit all field in the header,
|
||||
// then sort them.
|
||||
// this method will visit all field in the header.
|
||||
func (r *Request) Header(key string) []string {
|
||||
return r.header.PeekMultiple(key)
|
||||
}
|
||||
|
||||
// AddHeader method adds a single header field and its value in the request instance.
|
||||
// It will override header which set in client instance.
|
||||
func (r *Request) AddHeader(key, val string) *Request {
|
||||
r.header.Add(key, val)
|
||||
return r
|
||||
}
|
||||
|
||||
// SetHeader method sets a single header field and its value in the request instance.
|
||||
// It will override header which set in client instance.
|
||||
// It will override header which has been set in client instance.
|
||||
func (r *Request) SetHeader(key, val string) *Request {
|
||||
r.header.Del(key)
|
||||
r.header.Set(key, val)
|
||||
|
@ -143,14 +141,13 @@ func (r *Request) SetHeader(key, val string) *Request {
|
|||
}
|
||||
|
||||
// AddHeaders method adds multiple header fields and its values at one go in the request instance.
|
||||
// It will override header which set in client instance.
|
||||
func (r *Request) AddHeaders(h map[string][]string) *Request {
|
||||
r.header.AddHeaders(h)
|
||||
return r
|
||||
}
|
||||
|
||||
// SetHeaders method sets multiple header fields and its values at one go in the request instance.
|
||||
// It will override header which set in client instance.
|
||||
// It will override header which has been set in client instance.
|
||||
func (r *Request) SetHeaders(h map[string]string) *Request {
|
||||
r.header.SetHeaders(h)
|
||||
return r
|
||||
|
@ -169,35 +166,33 @@ func (r *Request) Param(key string) []string {
|
|||
}
|
||||
|
||||
// AddParam method adds a single param field and its value in the request instance.
|
||||
// It will override param which set in client instance.
|
||||
func (r *Request) AddParam(key, val string) *Request {
|
||||
r.params.Add(key, val)
|
||||
return r
|
||||
}
|
||||
|
||||
// SetParam method sets a single param field and its value in the request instance.
|
||||
// It will override param which set in client instance.
|
||||
// It will override param which has been set in client instance.
|
||||
func (r *Request) SetParam(key, val string) *Request {
|
||||
r.params.Set(key, val)
|
||||
return r
|
||||
}
|
||||
|
||||
// AddParams method adds multiple param fields and its values at one go in the request instance.
|
||||
// It will override param which set in client instance.
|
||||
func (r *Request) AddParams(m map[string][]string) *Request {
|
||||
r.params.AddParams(m)
|
||||
return r
|
||||
}
|
||||
|
||||
// SetParams method sets multiple param fields and its values at one go in the request instance.
|
||||
// It will override param which set in client instance.
|
||||
// It will override param which has been set in client instance.
|
||||
func (r *Request) SetParams(m map[string]string) *Request {
|
||||
r.params.SetParams(m)
|
||||
return r
|
||||
}
|
||||
|
||||
// SetParamsWithStruct method sets multiple param fields and its values at one go in the request instance.
|
||||
// It will override param which set in client instance.
|
||||
// It will override param which has been set in client instance.
|
||||
func (r *Request) SetParamsWithStruct(v any) *Request {
|
||||
r.params.SetParamsWithStruct(v)
|
||||
return r
|
||||
|
@ -217,7 +212,7 @@ func (r *Request) UserAgent() string {
|
|||
}
|
||||
|
||||
// SetUserAgent method sets user agent in request.
|
||||
// It will override user agent which set in client instance.
|
||||
// It will override user agent which has been set in client instance.
|
||||
func (r *Request) SetUserAgent(ua string) *Request {
|
||||
r.userAgent = ua
|
||||
return r
|
||||
|
@ -326,14 +321,14 @@ func (r *Request) ResetPathParams() *Request {
|
|||
return r
|
||||
}
|
||||
|
||||
// SetJSON method sets json body in request.
|
||||
// SetJSON method sets JSON body in request.
|
||||
func (r *Request) SetJSON(v any) *Request {
|
||||
r.body = v
|
||||
r.bodyType = jsonBody
|
||||
return r
|
||||
}
|
||||
|
||||
// SetXML method sets xml body in request.
|
||||
// SetXML method sets XML body in request.
|
||||
func (r *Request) SetXML(v any) *Request {
|
||||
r.body = v
|
||||
r.bodyType = xmlBody
|
||||
|
@ -589,7 +584,7 @@ func (h *Header) PeekMultiple(key string) []string {
|
|||
return res
|
||||
}
|
||||
|
||||
// AddHeaders receive a map and add each value to header.
|
||||
// AddHeaders receives a map and add each value to header.
|
||||
func (h *Header) AddHeaders(r map[string][]string) {
|
||||
for k, v := range r {
|
||||
for _, vv := range v {
|
||||
|
@ -678,14 +673,14 @@ func (c Cookie) VisitAll(f func(key, val string)) {
|
|||
}
|
||||
}
|
||||
|
||||
// Reset clear the Cookie object.
|
||||
// Reset clears the Cookie object.
|
||||
func (c Cookie) Reset() {
|
||||
for k := range c {
|
||||
delete(c, k)
|
||||
}
|
||||
}
|
||||
|
||||
// PathParam is a map which to store the cookies.
|
||||
// PathParam is a map which to store path params.
|
||||
type PathParam map[string]string
|
||||
|
||||
// Add method impl the method in WithStruct interface.
|
||||
|
@ -729,7 +724,7 @@ func (p PathParam) VisitAll(f func(key, val string)) {
|
|||
}
|
||||
}
|
||||
|
||||
// Reset clear the PathParams object.
|
||||
// Reset clear the PathParam object.
|
||||
func (p PathParam) Reset() {
|
||||
for k := range p {
|
||||
delete(p, k)
|
||||
|
@ -737,7 +732,7 @@ func (p PathParam) Reset() {
|
|||
}
|
||||
|
||||
// FormData is a wrapper of fasthttp.Args,
|
||||
// and it be used for url encode body and file body.
|
||||
// and it is used for url encode body and file body.
|
||||
type FormData struct {
|
||||
*fasthttp.Args
|
||||
}
|
||||
|
|
|
@ -129,7 +129,7 @@ func (r *Response) Save(v any) error {
|
|||
}
|
||||
}
|
||||
|
||||
// Reset clear Response object.
|
||||
// Reset clears the Response object.
|
||||
func (r *Response) Reset() {
|
||||
r.client = nil
|
||||
r.request = nil
|
||||
|
|
|
@ -1,663 +0,0 @@
|
|||
---
|
||||
id: client
|
||||
title: 🌎 Client
|
||||
description: The Client struct represents the Fiber HTTP Client.
|
||||
sidebar_position: 6
|
||||
---
|
||||
|
||||
## Start request
|
||||
|
||||
Start a http request with http method and url.
|
||||
|
||||
```go title="Signatures"
|
||||
// Client http methods
|
||||
func (c *Client) Get(url string) *Agent
|
||||
func (c *Client) Head(url string) *Agent
|
||||
func (c *Client) Post(url string) *Agent
|
||||
func (c *Client) Put(url string) *Agent
|
||||
func (c *Client) Patch(url string) *Agent
|
||||
func (c *Client) Delete(url string) *Agent
|
||||
```
|
||||
|
||||
Here we present a brief example demonstrating the simulation of a proxy using our `*fiber.Agent` methods.
|
||||
```go
|
||||
// Get something
|
||||
func getSomething(c fiber.Ctx) (err error) {
|
||||
agent := fiber.Get("<URL>")
|
||||
statusCode, body, errs := agent.Bytes()
|
||||
if len(errs) > 0 {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"errs": errs,
|
||||
})
|
||||
}
|
||||
|
||||
var something fiber.Map
|
||||
err = json.Unmarshal(body, &something)
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"err": err,
|
||||
})
|
||||
}
|
||||
|
||||
return c.Status(statusCode).JSON(something)
|
||||
}
|
||||
|
||||
// Post something
|
||||
func createSomething(c fiber.Ctx) (err error) {
|
||||
agent := fiber.Post("<URL>")
|
||||
agent.Body(c.Body()) // set body received by request
|
||||
statusCode, body, errs := agent.Bytes()
|
||||
if len(errs) > 0 {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"errs": errs,
|
||||
})
|
||||
}
|
||||
|
||||
// pass status code and body received by the proxy
|
||||
return c.Status(statusCode).Send(body)
|
||||
}
|
||||
```
|
||||
Based on this short example, we can perceive that using the `*fiber.Client` is very straightforward and intuitive.
|
||||
|
||||
|
||||
## ✨ Agent
|
||||
`Agent` is built on top of FastHTTP's [`HostClient`](https://github.com/valyala/fasthttp/blob/master/client.go#L603) which has lots of convenient helper methods such as dedicated methods for request methods.
|
||||
|
||||
### Parse
|
||||
|
||||
Parse initializes a HostClient.
|
||||
|
||||
```go title="Parse"
|
||||
a := AcquireAgent()
|
||||
req := a.Request()
|
||||
req.Header.SetMethod(MethodGet)
|
||||
req.SetRequestURI("http://example.com")
|
||||
|
||||
if err := a.Parse(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
code, body, errs := a.Bytes() // ...
|
||||
```
|
||||
|
||||
### Set
|
||||
|
||||
Set sets the given `key: value` header.
|
||||
|
||||
```go title="Signature"
|
||||
func (a *Agent) Set(k, v string) *Agent
|
||||
func (a *Agent) SetBytesK(k []byte, v string) *Agent
|
||||
func (a *Agent) SetBytesV(k string, v []byte) *Agent
|
||||
func (a *Agent) SetBytesKV(k []byte, v []byte) *Agent
|
||||
```
|
||||
|
||||
```go title="Example"
|
||||
agent.Set("k1", "v1").
|
||||
SetBytesK([]byte("k1"), "v1").
|
||||
SetBytesV("k1", []byte("v1")).
|
||||
SetBytesKV([]byte("k2"), []byte("v2"))
|
||||
// ...
|
||||
```
|
||||
|
||||
### Add
|
||||
|
||||
Add adds the given `key: value` header. Multiple headers with the same key may be added with this function.
|
||||
|
||||
```go title="Signature"
|
||||
func (a *Agent) Add(k, v string) *Agent
|
||||
func (a *Agent) AddBytesK(k []byte, v string) *Agent
|
||||
func (a *Agent) AddBytesV(k string, v []byte) *Agent
|
||||
func (a *Agent) AddBytesKV(k []byte, v []byte) *Agent
|
||||
```
|
||||
|
||||
```go title="Example"
|
||||
agent.Add("k1", "v1").
|
||||
AddBytesK([]byte("k1"), "v1").
|
||||
AddBytesV("k1", []byte("v1")).
|
||||
AddBytesKV([]byte("k2"), []byte("v2"))
|
||||
// Headers:
|
||||
// K1: v1
|
||||
// K1: v1
|
||||
// K1: v1
|
||||
// K2: v2
|
||||
```
|
||||
|
||||
### ConnectionClose
|
||||
|
||||
ConnectionClose adds the `Connection: close` header.
|
||||
|
||||
```go title="Signature"
|
||||
func (a *Agent) ConnectionClose() *Agent
|
||||
```
|
||||
|
||||
```go title="Example"
|
||||
agent.ConnectionClose()
|
||||
// ...
|
||||
```
|
||||
|
||||
### UserAgent
|
||||
|
||||
UserAgent sets `User-Agent` header value.
|
||||
|
||||
```go title="Signature"
|
||||
func (a *Agent) UserAgent(userAgent string) *Agent
|
||||
func (a *Agent) UserAgentBytes(userAgent []byte) *Agent
|
||||
```
|
||||
|
||||
```go title="Example"
|
||||
agent.UserAgent("fiber")
|
||||
// ...
|
||||
```
|
||||
|
||||
### Cookie
|
||||
|
||||
Cookie sets a cookie in `key: value` form. `Cookies` can be used to set multiple cookies.
|
||||
|
||||
```go title="Signature"
|
||||
func (a *Agent) Cookie(key, value string) *Agent
|
||||
func (a *Agent) CookieBytesK(key []byte, value string) *Agent
|
||||
func (a *Agent) CookieBytesKV(key, value []byte) *Agent
|
||||
func (a *Agent) Cookies(kv ...string) *Agent
|
||||
func (a *Agent) CookiesBytesKV(kv ...[]byte) *Agent
|
||||
```
|
||||
|
||||
```go title="Example"
|
||||
agent.Cookie("k", "v")
|
||||
agent.Cookies("k1", "v1", "k2", "v2")
|
||||
// ...
|
||||
```
|
||||
|
||||
### Referer
|
||||
|
||||
Referer sets the Referer header value.
|
||||
|
||||
```go title="Signature"
|
||||
func (a *Agent) Referer(referer string) *Agent
|
||||
func (a *Agent) RefererBytes(referer []byte) *Agent
|
||||
```
|
||||
|
||||
```go title="Example"
|
||||
agent.Referer("https://docs.gofiber.io")
|
||||
// ...
|
||||
```
|
||||
|
||||
### ContentType
|
||||
|
||||
ContentType sets Content-Type header value.
|
||||
|
||||
```go title="Signature"
|
||||
func (a *Agent) ContentType(contentType string) *Agent
|
||||
func (a *Agent) ContentTypeBytes(contentType []byte) *Agent
|
||||
```
|
||||
|
||||
```go title="Example"
|
||||
agent.ContentType("custom-type")
|
||||
// ...
|
||||
```
|
||||
|
||||
### Host
|
||||
|
||||
Host sets the Host header.
|
||||
|
||||
```go title="Signature"
|
||||
func (a *Agent) Host(host string) *Agent
|
||||
func (a *Agent) HostBytes(host []byte) *Agent
|
||||
```
|
||||
|
||||
```go title="Example"
|
||||
agent.Host("example.com")
|
||||
// ...
|
||||
```
|
||||
|
||||
### QueryString
|
||||
|
||||
QueryString sets the URI query string.
|
||||
|
||||
```go title="Signature"
|
||||
func (a *Agent) QueryString(queryString string) *Agent
|
||||
func (a *Agent) QueryStringBytes(queryString []byte) *Agent
|
||||
```
|
||||
|
||||
```go title="Example"
|
||||
agent.QueryString("foo=bar")
|
||||
// ...
|
||||
```
|
||||
|
||||
### BasicAuth
|
||||
|
||||
BasicAuth sets the URI username and password using HTTP Basic Auth.
|
||||
|
||||
```go title="Signature"
|
||||
func (a *Agent) BasicAuth(username, password string) *Agent
|
||||
func (a *Agent) BasicAuthBytes(username, password []byte) *Agent
|
||||
```
|
||||
|
||||
```go title="Example"
|
||||
agent.BasicAuth("foo", "bar")
|
||||
// ...
|
||||
```
|
||||
|
||||
### Body
|
||||
|
||||
There are several ways to set request body.
|
||||
|
||||
```go title="Signature"
|
||||
func (a *Agent) BodyString(bodyString string) *Agent
|
||||
func (a *Agent) Body(body []byte) *Agent
|
||||
|
||||
// BodyStream sets request body stream and, optionally body size.
|
||||
//
|
||||
// If bodySize is >= 0, then the bodyStream must provide exactly bodySize bytes
|
||||
// before returning io.EOF.
|
||||
//
|
||||
// If bodySize < 0, then bodyStream is read until io.EOF.
|
||||
//
|
||||
// bodyStream.Close() is called after finishing reading all body data
|
||||
// if it implements io.Closer.
|
||||
//
|
||||
// Note that GET and HEAD requests cannot have body.
|
||||
func (a *Agent) BodyStream(bodyStream io.Reader, bodySize int) *Agent
|
||||
```
|
||||
|
||||
```go title="Example"
|
||||
agent.BodyString("foo=bar")
|
||||
agent.Body([]byte("bar=baz"))
|
||||
agent.BodyStream(strings.NewReader("body=stream"), -1)
|
||||
// ...
|
||||
```
|
||||
|
||||
### JSON
|
||||
|
||||
JSON sends a JSON request by setting the Content-Type header to the `ctype` parameter. If no `ctype` is passed in, the header is set to `application/json`.
|
||||
|
||||
```go title="Signature"
|
||||
func (a *Agent) JSON(v any, ctype ...string) *Agent
|
||||
```
|
||||
|
||||
```go title="Example"
|
||||
agent.JSON(fiber.Map{"success": true})
|
||||
// ...
|
||||
```
|
||||
|
||||
### XML
|
||||
|
||||
XML sends an XML request by setting the Content-Type header to `application/xml`.
|
||||
|
||||
```go title="Signature"
|
||||
func (a *Agent) XML(v any) *Agent
|
||||
```
|
||||
|
||||
```go title="Example"
|
||||
agent.XML(fiber.Map{"success": true})
|
||||
// ...
|
||||
```
|
||||
|
||||
### Form
|
||||
|
||||
Form sends a form request by setting the Content-Type header to `application/x-www-form-urlencoded`.
|
||||
|
||||
```go title="Signature"
|
||||
// Form sends form request with body if args is non-nil.
|
||||
//
|
||||
// It is recommended obtaining args via AcquireArgs and release it
|
||||
// manually in performance-critical code.
|
||||
func (a *Agent) Form(args *Args) *Agent
|
||||
```
|
||||
|
||||
```go title="Example"
|
||||
args := AcquireArgs()
|
||||
args.Set("foo", "bar")
|
||||
|
||||
agent.Form(args)
|
||||
// ...
|
||||
ReleaseArgs(args)
|
||||
```
|
||||
|
||||
### MultipartForm
|
||||
|
||||
MultipartForm sends multipart form request by setting the Content-Type header to `multipart/form-data`. These requests can include key-value's and files.
|
||||
|
||||
```go title="Signature"
|
||||
// MultipartForm sends multipart form request with k-v and files.
|
||||
//
|
||||
// It is recommended to obtain args via AcquireArgs and release it
|
||||
// manually in performance-critical code.
|
||||
func (a *Agent) MultipartForm(args *Args) *Agent
|
||||
```
|
||||
|
||||
```go title="Example"
|
||||
args := AcquireArgs()
|
||||
args.Set("foo", "bar")
|
||||
|
||||
agent.MultipartForm(args)
|
||||
// ...
|
||||
ReleaseArgs(args)
|
||||
```
|
||||
|
||||
Fiber provides several methods for sending files. Note that they must be called before `MultipartForm`.
|
||||
|
||||
#### Boundary
|
||||
|
||||
Boundary sets boundary for multipart form request.
|
||||
|
||||
```go title="Signature"
|
||||
func (a *Agent) Boundary(boundary string) *Agent
|
||||
```
|
||||
|
||||
```go title="Example"
|
||||
agent.Boundary("myBoundary")
|
||||
.MultipartForm(nil)
|
||||
// ...
|
||||
```
|
||||
|
||||
#### SendFile\(s\)
|
||||
|
||||
SendFile read a file and appends it to a multipart form request. Sendfiles can be used to append multiple files.
|
||||
|
||||
```go title="Signature"
|
||||
func (a *Agent) SendFile(filename string, fieldname ...string) *Agent
|
||||
func (a *Agent) SendFiles(filenamesAndFieldnames ...string) *Agent
|
||||
```
|
||||
|
||||
```go title="Example"
|
||||
agent.SendFile("f", "field name")
|
||||
.SendFiles("f1", "field name1", "f2").
|
||||
.MultipartForm(nil)
|
||||
// ...
|
||||
```
|
||||
|
||||
#### FileData
|
||||
|
||||
FileData appends file data for multipart form request.
|
||||
|
||||
```go
|
||||
// FormFile represents multipart form file
|
||||
type FormFile struct {
|
||||
// Fieldname is form file's field name
|
||||
Fieldname string
|
||||
// Name is form file's name
|
||||
Name string
|
||||
// Content is form file's content
|
||||
Content []byte
|
||||
}
|
||||
```
|
||||
|
||||
```go title="Signature"
|
||||
// FileData appends files for multipart form request.
|
||||
//
|
||||
// It is recommended obtaining formFile via AcquireFormFile and release it
|
||||
// manually in performance-critical code.
|
||||
func (a *Agent) FileData(formFiles ...*FormFile) *Agent
|
||||
```
|
||||
|
||||
```go title="Example"
|
||||
ff1 := &FormFile{"filename1", "field name1", []byte("content")}
|
||||
ff2 := &FormFile{"filename2", "field name2", []byte("content")}
|
||||
agent.FileData(ff1, ff2).
|
||||
MultipartForm(nil)
|
||||
// ...
|
||||
```
|
||||
|
||||
### Debug
|
||||
|
||||
Debug mode enables logging request and response detail to `io.writer`\(default is `os.Stdout`\).
|
||||
|
||||
```go title="Signature"
|
||||
func (a *Agent) Debug(w ...io.Writer) *Agent
|
||||
```
|
||||
|
||||
```go title="Example"
|
||||
agent.Debug()
|
||||
// ...
|
||||
```
|
||||
|
||||
### Timeout
|
||||
|
||||
Timeout sets request timeout duration.
|
||||
|
||||
```go title="Signature"
|
||||
func (a *Agent) Timeout(timeout time.Duration) *Agent
|
||||
```
|
||||
|
||||
```go title="Example"
|
||||
agent.Timeout(time.Second)
|
||||
// ...
|
||||
```
|
||||
|
||||
### Reuse
|
||||
|
||||
Reuse enables the Agent instance to be used again after one request. If agent is reusable, then it should be released manually when it is no longer used.
|
||||
|
||||
```go title="Signature"
|
||||
func (a *Agent) Reuse() *Agent
|
||||
```
|
||||
|
||||
```go title="Example"
|
||||
agent.Reuse()
|
||||
// ...
|
||||
```
|
||||
|
||||
### InsecureSkipVerify
|
||||
|
||||
InsecureSkipVerify controls whether the Agent verifies the server certificate chain and host name.
|
||||
|
||||
```go title="Signature"
|
||||
func (a *Agent) InsecureSkipVerify() *Agent
|
||||
```
|
||||
|
||||
```go title="Example"
|
||||
agent.InsecureSkipVerify()
|
||||
// ...
|
||||
```
|
||||
|
||||
### TLSConfig
|
||||
|
||||
TLSConfig sets tls config.
|
||||
|
||||
```go title="Signature"
|
||||
func (a *Agent) TLSConfig(config *tls.Config) *Agent
|
||||
```
|
||||
|
||||
```go title="Example"
|
||||
// Create tls certificate
|
||||
cer, _ := tls.LoadX509KeyPair("pem", "key")
|
||||
|
||||
config := &tls.Config{
|
||||
Certificates: []tls.Certificate{cer},
|
||||
}
|
||||
|
||||
agent.TLSConfig(config)
|
||||
// ...
|
||||
```
|
||||
|
||||
### MaxRedirectsCount
|
||||
|
||||
MaxRedirectsCount sets max redirect count for GET and HEAD.
|
||||
|
||||
```go title="Signature"
|
||||
func (a *Agent) MaxRedirectsCount(count int) *Agent
|
||||
```
|
||||
|
||||
```go title="Example"
|
||||
agent.MaxRedirectsCount(7)
|
||||
// ...
|
||||
```
|
||||
|
||||
### JSONEncoder
|
||||
|
||||
JSONEncoder sets custom json encoder.
|
||||
|
||||
```go title="Signature"
|
||||
func (a *Agent) JSONEncoder(jsonEncoder utils.JSONMarshal) *Agent
|
||||
```
|
||||
|
||||
```go title="Example"
|
||||
agent.JSONEncoder(json.Marshal)
|
||||
// ...
|
||||
```
|
||||
|
||||
### JSONDecoder
|
||||
|
||||
JSONDecoder sets custom json decoder.
|
||||
|
||||
```go title="Signature"
|
||||
func (a *Agent) JSONDecoder(jsonDecoder utils.JSONUnmarshal) *Agent
|
||||
```
|
||||
|
||||
```go title="Example"
|
||||
agent.JSONDecoder(json.Unmarshal)
|
||||
// ...
|
||||
```
|
||||
|
||||
### Request
|
||||
|
||||
Request returns Agent request instance.
|
||||
|
||||
```go title="Signature"
|
||||
func (a *Agent) Request() *Request
|
||||
```
|
||||
|
||||
```go title="Example"
|
||||
req := agent.Request()
|
||||
// ...
|
||||
```
|
||||
|
||||
### SetResponse
|
||||
|
||||
SetResponse sets custom response for the Agent instance. It is recommended obtaining custom response via AcquireResponse and release it manually in performance-critical code.
|
||||
|
||||
```go title="Signature"
|
||||
func (a *Agent) SetResponse(customResp *Response) *Agent
|
||||
```
|
||||
|
||||
```go title="Example"
|
||||
resp := AcquireResponse()
|
||||
agent.SetResponse(resp)
|
||||
// ...
|
||||
ReleaseResponse(resp)
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Example handling for response values</summary>
|
||||
|
||||
```go title="Example handling response"
|
||||
// Create a Fiber HTTP client agent
|
||||
agent := fiber.Get("https://httpbin.org/get")
|
||||
|
||||
// Acquire a response object to store the result
|
||||
resp := fiber.AcquireResponse()
|
||||
agent.SetResponse(resp)
|
||||
|
||||
// Perform the HTTP GET request
|
||||
code, body, errs := agent.String()
|
||||
if errs != nil {
|
||||
// Handle any errors that occur during the request
|
||||
panic(errs)
|
||||
}
|
||||
|
||||
// Print the HTTP response code and body
|
||||
fmt.Println("Response Code:", code)
|
||||
fmt.Println("Response Body:", body)
|
||||
|
||||
// Visit and print all the headers in the response
|
||||
resp.Header.VisitAll(func(key, value []byte) {
|
||||
fmt.Println("Header", string(key), "value", string(value))
|
||||
})
|
||||
|
||||
// Release the response to free up resources
|
||||
fiber.ReleaseResponse(resp)
|
||||
```
|
||||
|
||||
Output:
|
||||
```txt title="Output"
|
||||
Response Code: 200
|
||||
Response Body: {
|
||||
"args": {},
|
||||
"headers": {
|
||||
"Host": "httpbin.org",
|
||||
"User-Agent": "fiber",
|
||||
"X-Amzn-Trace-Id": "Root=1-653763d0-2555d5ba3838f1e9092f9f72"
|
||||
},
|
||||
"origin": "83.137.191.1",
|
||||
"url": "https://httpbin.org/get"
|
||||
}
|
||||
|
||||
Header Content-Length value 226
|
||||
Header Content-Type value application/json
|
||||
Header Server value gunicorn/19.9.0
|
||||
Header Date value Tue, 24 Oct 2023 06:27:28 GMT
|
||||
Header Connection value keep-alive
|
||||
Header Access-Control-Allow-Origin value *
|
||||
Header Access-Control-Allow-Credentials value true
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
### Dest
|
||||
|
||||
Dest sets custom dest. The contents of dest will be replaced by the response body, if the dest is too small a new slice will be allocated.
|
||||
|
||||
```go title="Signature"
|
||||
func (a *Agent) Dest(dest []byte) *Agent {
|
||||
```
|
||||
|
||||
```go title="Example"
|
||||
agent.Dest(nil)
|
||||
// ...
|
||||
```
|
||||
|
||||
### Bytes
|
||||
|
||||
Bytes returns the status code, bytes body and errors of url.
|
||||
|
||||
```go title="Signature"
|
||||
func (a *Agent) Bytes() (code int, body []byte, errs []error)
|
||||
```
|
||||
|
||||
```go title="Example"
|
||||
code, body, errs := agent.Bytes()
|
||||
// ...
|
||||
```
|
||||
|
||||
### String
|
||||
|
||||
String returns the status code, string body and errors of url.
|
||||
|
||||
```go title="Signature"
|
||||
func (a *Agent) String() (int, string, []error)
|
||||
```
|
||||
|
||||
```go title="Example"
|
||||
code, body, errs := agent.String()
|
||||
// ...
|
||||
```
|
||||
|
||||
### Struct
|
||||
|
||||
Struct returns the status code, bytes body and errors of url. And bytes body will be unmarshalled to given v.
|
||||
|
||||
```go title="Signature"
|
||||
func (a *Agent) Struct(v any) (code int, body []byte, errs []error)
|
||||
```
|
||||
|
||||
```go title="Example"
|
||||
var d data
|
||||
code, body, errs := agent.Struct(&d)
|
||||
// ...
|
||||
```
|
||||
|
||||
### RetryIf
|
||||
|
||||
RetryIf controls whether a retry should be attempted after an error.
|
||||
By default, will use isIdempotent function from fasthttp
|
||||
|
||||
```go title="Signature"
|
||||
func (a *Agent) RetryIf(retryIf RetryIfFunc) *Agent
|
||||
```
|
||||
|
||||
```go title="Example"
|
||||
agent.Get("https://example.com").RetryIf(func (req *fiber.Request) bool {
|
||||
return req.URI() == "https://example.com"
|
||||
})
|
||||
// ...
|
||||
```
|
|
@ -2,7 +2,7 @@
|
|||
id: constants
|
||||
title: 📋 Constants
|
||||
description: Some constants for Fiber.
|
||||
sidebar_position: 9
|
||||
sidebar_position: 8
|
||||
---
|
||||
|
||||
### HTTP methods were copied from net/http.
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
---
|
||||
id: hooks
|
||||
title: 🎣 Hooks
|
||||
sidebar_position: 8
|
||||
sidebar_position: 7
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
|
|
|
@ -2,7 +2,7 @@
|
|||
id: log
|
||||
title: 📃 Log
|
||||
description: Fiber's built-in log package
|
||||
sidebar_position: 7
|
||||
sidebar_position: 6
|
||||
---
|
||||
|
||||
We can use logs to observe program behavior, diagnose problems, or configure corresponding alarms.
|
||||
|
|
|
@ -0,0 +1,8 @@
|
|||
{
|
||||
"label": "\uD83C\uDF0E Client",
|
||||
"position": 5,
|
||||
"link": {
|
||||
"type": "generated-index",
|
||||
"description": "HTTP client for Fiber."
|
||||
}
|
||||
}
|
|
@ -0,0 +1,250 @@
|
|||
---
|
||||
id: examples
|
||||
title: 🍳 Examples
|
||||
description: >-
|
||||
Client usage examples.
|
||||
sidebar_position: 5
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
## Basic Auth
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="client" label="Client">
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
|
||||
"github.com/gofiber/fiber/v3/client"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cc := client.New()
|
||||
|
||||
out := base64.StdEncoding.EncodeToString([]byte("john:doe"))
|
||||
resp, err := cc.Get("http://localhost:3000", client.Config{
|
||||
Header: map[string]string{
|
||||
"Authorization": "Basic " + out,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
fmt.Print(string(resp.Body()))
|
||||
}
|
||||
```
|
||||
</TabItem>
|
||||
<TabItem value="server" label="Server">
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/gofiber/fiber/v3/middleware/basicauth"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := fiber.New()
|
||||
app.Use(
|
||||
basicauth.New(basicauth.Config{
|
||||
Users: map[string]string{
|
||||
"john": "doe",
|
||||
},
|
||||
}),
|
||||
)
|
||||
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
return c.SendString("Hello, World!")
|
||||
})
|
||||
|
||||
app.Listen(":3000")
|
||||
}
|
||||
```
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## TLS
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="client" label="Client">
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/gofiber/fiber/v3/client"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cc := client.New()
|
||||
|
||||
certPool, err := x509.SystemCertPool()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
cert, err := os.ReadFile("ssl.cert")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
certPool.AppendCertsFromPEM(cert)
|
||||
cc.SetTLSConfig(&tls.Config{
|
||||
RootCAs: certPool,
|
||||
})
|
||||
|
||||
resp, err := cc.Get("https://localhost:3000")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
fmt.Print(string(resp.Body()))
|
||||
}
|
||||
```
|
||||
</TabItem>
|
||||
<TabItem value="server" label="Server">
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/gofiber/fiber/v3"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := fiber.New()
|
||||
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
return c.SendString("Hello, World!")
|
||||
})
|
||||
|
||||
err := app.Listen(":3000", fiber.ListenConfig{
|
||||
CertFile: "ssl.cert",
|
||||
CertKeyFile: "ssl.key",
|
||||
})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
```
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## Cookiejar
|
||||
|
||||
### Request
|
||||
|
||||
```go
|
||||
func main() {
|
||||
jar := client.AcquireCookieJar()
|
||||
defer client.ReleaseCookieJar(jar)
|
||||
|
||||
cc := client.New()
|
||||
cc.SetCookieJar(jar)
|
||||
|
||||
jar.SetKeyValueBytes("httpbin.org", []byte("john"), []byte("doe"))
|
||||
|
||||
resp, err := cc.Get("https://httpbin.org/cookies")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
fmt.Println(string(resp.Body()))
|
||||
}
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Click here to see the result</summary>
|
||||
|
||||
```json
|
||||
{
|
||||
"cookies": {
|
||||
"john": "doe"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
### Response
|
||||
|
||||
```go
|
||||
func main() {
|
||||
jar := client.AcquireCookieJar()
|
||||
defer client.ReleaseCookieJar(jar)
|
||||
|
||||
cc := client.New()
|
||||
cc.SetCookieJar(jar)
|
||||
|
||||
_, err := cc.Get("https://httpbin.org/cookies/set/john/doe")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
uri := fasthttp.AcquireURI()
|
||||
defer fasthttp.ReleaseURI(uri)
|
||||
|
||||
uri.SetHost("httpbin.org")
|
||||
uri.SetPath("/cookies")
|
||||
fmt.Println(jar.Get(uri))
|
||||
}
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Click here to see the result</summary>
|
||||
|
||||
```plaintext
|
||||
[john=doe; path=/]
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
### Response 2
|
||||
|
||||
```go
|
||||
func main() {
|
||||
jar := client.AcquireCookieJar()
|
||||
defer client.ReleaseCookieJar(jar)
|
||||
|
||||
cc := client.New()
|
||||
cc.SetCookieJar(jar)
|
||||
|
||||
_, err := cc.Get("https://httpbin.org/cookies/set/john/doe")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
resp, err := cc.Get("https://httpbin.org/cookies")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
fmt.Println(resp.String())
|
||||
}
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Click here to see the result</summary>
|
||||
|
||||
```json
|
||||
{
|
||||
"cookies": {
|
||||
"john": "doe"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
|
@ -0,0 +1,261 @@
|
|||
---
|
||||
id: hooks
|
||||
title: 🎣 Hooks
|
||||
description: >-
|
||||
Hooks are used to manipulate request/response proccess of Fiber client.
|
||||
sidebar_position: 4
|
||||
---
|
||||
|
||||
With hooks, you can manipulate the client on before request/after response stages or more complex logging/tracing cases.
|
||||
|
||||
There are 2 kinds of hooks:
|
||||
|
||||
## Request Hooks
|
||||
|
||||
They are called before the HTTP request has been sent. You can use them make changes on Request object.
|
||||
|
||||
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:
|
||||
|
||||
```go
|
||||
type Repository struct {
|
||||
Name string `json:"name"`
|
||||
FullName string `json:"full_name"`
|
||||
Description string `json:"description"`
|
||||
Homepage string `json:"homepage"`
|
||||
|
||||
Owner struct {
|
||||
Login string `json:"login"`
|
||||
} `json:"owner"`
|
||||
}
|
||||
|
||||
func main() {
|
||||
cc := client.New()
|
||||
|
||||
cc.AddRequestHook(func(c *client.Client, r *client.Request) error {
|
||||
r.SetURL("https://api.github.com/" + r.URL())
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
resp, err := cc.Get("repos/gofiber/fiber")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
var repo Repository
|
||||
if err := resp.JSON(&repo); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
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)
|
||||
fmt.Printf("Owner: %s\n", repo.Owner.Login)
|
||||
fmt.Printf("Name: %s\n", repo.Name)
|
||||
fmt.Printf("Full Name: %s\n", repo.FullName)
|
||||
}
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Click here to see the result</summary>
|
||||
|
||||
```plaintext
|
||||
Status code: 200
|
||||
Repository: gofiber/fiber
|
||||
Description: ⚡️ Express inspired web framework written in Go
|
||||
Homepage: https://gofiber.io
|
||||
Owner: gofiber
|
||||
Name: fiber
|
||||
Full Name: gofiber/fiber
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
There are also some builtin request hooks provide some functionalities for Fiber client. Here is a list of them:
|
||||
|
||||
- [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.
|
||||
|
||||
- [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 proeprties. It's necessary to make request header and cookiejar methods functional.
|
||||
|
||||
- [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.
|
||||
|
||||
:::info
|
||||
If any error returns from request hook execution, it will interrupt the request and return the error.
|
||||
:::
|
||||
|
||||
```go
|
||||
func main() {
|
||||
cc := client.New()
|
||||
|
||||
cc.AddRequestHook(func(c *client.Client, r *client.Request) error {
|
||||
fmt.Println("Hook 1")
|
||||
return errors.New("error")
|
||||
})
|
||||
|
||||
cc.AddRequestHook(func(c *client.Client, r *client.Request) error {
|
||||
fmt.Println("Hook 2")
|
||||
return nil
|
||||
})
|
||||
|
||||
_, err := cc.Get("https://example.com/")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Click here to see the result</summary>
|
||||
|
||||
```shell
|
||||
Hook 1.
|
||||
panic: error
|
||||
|
||||
goroutine 1 [running]:
|
||||
main.main()
|
||||
main.go:25 +0xaa
|
||||
exit status 2
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
## Response Hooks
|
||||
|
||||
They are called after the HTTP response has been completed. You can use them to get some information about response and request.
|
||||
|
||||
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
|
||||
func main() {
|
||||
cc := client.New()
|
||||
|
||||
cc.AddResponseHook(func(c *client.Client, resp *client.Response, req *client.Request) error {
|
||||
fmt.Printf("Response Status Code: %d\n", resp.StatusCode())
|
||||
fmt.Printf("HTTP protocol: %s\n\n", resp.Protocol())
|
||||
|
||||
fmt.Println("Response Headers:")
|
||||
resp.RawResponse.Header.VisitAll(func(key, value []byte) {
|
||||
fmt.Printf("%s: %s\n", key, value)
|
||||
})
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
_, err := cc.Get("https://example.com/")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Click here to see the result</summary>
|
||||
|
||||
```plaintext
|
||||
Response Status Code: 200
|
||||
HTTP protocol: HTTP/1.1
|
||||
|
||||
Response Headers:
|
||||
Content-Length: 1256
|
||||
Content-Type: text/html; charset=UTF-8
|
||||
Server: ECAcc (dcd/7D5A)
|
||||
Age: 216114
|
||||
Cache-Control: max-age=604800
|
||||
Date: Fri, 10 May 2024 10:49:10 GMT
|
||||
Etag: "3147526947+gzip+ident"
|
||||
Expires: Fri, 17 May 2024 10:49:10 GMT
|
||||
Last-Modified: Thu, 17 Oct 2019 07:18:26 GMT
|
||||
Vary: Accept-Encoding
|
||||
X-Cache: HIT
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
There are also some builtin request hooks provide some functionalities for Fiber client. Here is a list of them:
|
||||
|
||||
- [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.
|
||||
|
||||
- [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.
|
||||
|
||||
:::info
|
||||
If any error is returned from executing the response hook, it will return the error without executing other response hooks.
|
||||
:::
|
||||
|
||||
```go
|
||||
func main() {
|
||||
cc := client.New()
|
||||
|
||||
cc.AddResponseHook(func(c *client.Client, r1 *client.Response, r2 *client.Request) error {
|
||||
fmt.Println("Hook 1")
|
||||
return nil
|
||||
})
|
||||
|
||||
cc.AddResponseHook(func(c *client.Client, r1 *client.Response, r2 *client.Request) error {
|
||||
fmt.Println("Hook 2")
|
||||
return errors.New("error")
|
||||
})
|
||||
|
||||
cc.AddResponseHook(func(c *client.Client, r1 *client.Response, r2 *client.Request) error {
|
||||
fmt.Println("Hook 3")
|
||||
return nil
|
||||
})
|
||||
|
||||
_, err := cc.Get("https://example.com/")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Click here to see the result</summary>
|
||||
|
||||
```shell
|
||||
Hook 1
|
||||
Hook 2
|
||||
panic: error
|
||||
|
||||
goroutine 1 [running]:
|
||||
main.main()
|
||||
main.go:30 +0xd6
|
||||
exit status 2
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
:::info
|
||||
Hooks work as FIFO (first-in-first-out). You need to check the order while adding the hooks.
|
||||
:::
|
||||
|
||||
```go
|
||||
func main() {
|
||||
cc := client.New()
|
||||
|
||||
cc.AddRequestHook(func(c *client.Client, r *client.Request) error {
|
||||
fmt.Println("Hook 1")
|
||||
return nil
|
||||
})
|
||||
|
||||
cc.AddRequestHook(func(c *client.Client, r *client.Request) error {
|
||||
fmt.Println("Hook 2")
|
||||
return nil
|
||||
})
|
||||
|
||||
_, err := cc.Get("https://example.com/")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Click here to see the result</summary>
|
||||
|
||||
```plaintext
|
||||
Hook 1
|
||||
Hook 2
|
||||
```
|
||||
|
||||
</details>
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,212 @@
|
|||
---
|
||||
id: response
|
||||
title: 📥 Response
|
||||
description: >-
|
||||
Response methods of Gofiber HTTP client.
|
||||
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:
|
||||
|
||||
- **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.
|
||||
|
||||
This structure allows users to easily access and manage the data returned by the server, facilitating efficient handling of HTTP responses.
|
||||
|
||||
```go
|
||||
type Response struct {
|
||||
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.
|
||||
|
||||
```go title="Signature"
|
||||
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.
|
||||
|
||||
```go title="Signature"
|
||||
func ReleaseResponse(resp *Response)
|
||||
```
|
||||
|
||||
## Status
|
||||
|
||||
Status method returns the HTTP status string for the executed request.
|
||||
|
||||
```go title="Signature"
|
||||
func (r *Response) Status() string
|
||||
```
|
||||
|
||||
## StatusCode
|
||||
|
||||
StatusCode method returns the HTTP status code for the executed request.
|
||||
|
||||
```go title="Signature"
|
||||
func (r *Response) StatusCode() int
|
||||
```
|
||||
|
||||
## Protocol
|
||||
|
||||
Protocol method returns the HTTP response protocol used for the request.
|
||||
|
||||
```go title="Signature"
|
||||
func (r *Response) Protocol() string
|
||||
```
|
||||
|
||||
```go title="Example"
|
||||
resp, err := client.Get("https://httpbin.org/get")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
fmt.Println(resp.Protocol())
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Click here to see the result</summary>
|
||||
|
||||
```
|
||||
HTTP/1.1
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
## Header
|
||||
|
||||
Header method returns the response headers.
|
||||
|
||||
```go title="Signature"
|
||||
func (r *Response) Header(key string) string
|
||||
```
|
||||
|
||||
## Cookies
|
||||
|
||||
Cookies method to access all the response cookies.
|
||||
|
||||
```go title="Signature"
|
||||
func (r *Response) Cookies() []*fasthttp.Cookie
|
||||
```
|
||||
|
||||
```go title="Example"
|
||||
resp, err := client.Get("https://httpbin.org/cookies/set/go/fiber")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
cookies := resp.Cookies()
|
||||
for _, cookie := range cookies {
|
||||
fmt.Printf("%s => %s\n", string(cookie.Key()), string(cookie.Value()))
|
||||
}
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Click here to see the result</summary>
|
||||
|
||||
```
|
||||
go => fiber
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
## Body
|
||||
|
||||
Body method returns HTTP response as []byte array for the executed request.
|
||||
|
||||
```go title="Signature"
|
||||
func (r *Response) Body() []byte
|
||||
```
|
||||
|
||||
## String
|
||||
|
||||
String method returns the body of the server response as String.
|
||||
|
||||
```go title="Signature"
|
||||
func (r *Response) String() string
|
||||
```
|
||||
|
||||
## JSON
|
||||
|
||||
JSON method will unmarshal body to json.
|
||||
|
||||
```go title="Signature"
|
||||
func (r *Response) JSON(v any) error
|
||||
```
|
||||
|
||||
```go title="Example"
|
||||
type Body struct {
|
||||
Slideshow struct {
|
||||
Author string `json:"author"`
|
||||
Date string `json:"date"`
|
||||
Title string `json:"title"`
|
||||
} `json:"slideshow"`
|
||||
}
|
||||
var out Body
|
||||
|
||||
resp, err := client.Get("https://httpbin.org/json")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
err = resp.JSON(&out)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
fmt.Printf("%+v\n", out)
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Click here to see the result</summary>
|
||||
|
||||
```
|
||||
{Slideshow:{Author:Yours Truly Date:date of publication Title:Sample Slide Show}}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
## XML
|
||||
|
||||
XML method will unmarshal body to xml.
|
||||
|
||||
```go title="Signature"
|
||||
func (r *Response) XML(v any) error
|
||||
```
|
||||
|
||||
## Save
|
||||
|
||||
Save method will save the body to a file or io.Writer.
|
||||
|
||||
```go title="Signature"
|
||||
func (r *Response) Save(v any) error
|
||||
```
|
||||
|
||||
## Reset
|
||||
|
||||
Reset clears the Response object.
|
||||
|
||||
```go title="Signature"
|
||||
func (r *Response) Reset()
|
||||
```
|
||||
|
||||
## Close
|
||||
|
||||
Close method will release the Request and Response objects; after calling Close, please do not use these objects.
|
||||
|
||||
```go title="Signature"
|
||||
func (r *Response) Close()
|
||||
```
|
|
@ -0,0 +1,810 @@
|
|||
---
|
||||
id: rest
|
||||
title: 🖥️ REST
|
||||
description: >-
|
||||
HTTP client for Gofiber.
|
||||
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.
|
||||
|
||||
## 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.
|
||||
|
||||
## Usage
|
||||
To use the Fiber Client, instantiate it with the desired configuration. Here's a simple example:
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v3/client"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cc := client.New()
|
||||
cc.SetTimeout(10 * time.Second)
|
||||
|
||||
// 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()))
|
||||
}
|
||||
```
|
||||
|
||||
You can check out [examples](examples.md) for more examples!
|
||||
|
||||
```go
|
||||
type Client struct {
|
||||
mu sync.RWMutex
|
||||
|
||||
fasthttp *fasthttp.Client
|
||||
|
||||
baseURL string
|
||||
userAgent string
|
||||
referer string
|
||||
header *Header
|
||||
params *QueryParam
|
||||
cookies *Cookie
|
||||
path *PathParam
|
||||
|
||||
debug bool
|
||||
|
||||
timeout time.Duration
|
||||
|
||||
// user defined request hooks
|
||||
userRequestHooks []RequestHook
|
||||
|
||||
// client package defined request hooks
|
||||
builtinRequestHooks []RequestHook
|
||||
|
||||
// user defined response hooks
|
||||
userResponseHooks []ResponseHook
|
||||
|
||||
// client package defined response hooks
|
||||
builtinResponseHooks []ResponseHook
|
||||
|
||||
jsonMarshal utils.JSONMarshal
|
||||
jsonUnmarshal utils.JSONUnmarshal
|
||||
xmlMarshal utils.XMLMarshal
|
||||
xmlUnmarshal utils.XMLUnmarshal
|
||||
|
||||
cookieJar *CookieJar
|
||||
|
||||
// proxy
|
||||
proxyURL string
|
||||
|
||||
// retry
|
||||
retryConfig *RetryConfig
|
||||
|
||||
// logger
|
||||
logger log.CommonLogger
|
||||
}
|
||||
```
|
||||
|
||||
New
|
||||
|
||||
New creates and returns a new Client object.
|
||||
|
||||
```go title="Signature"
|
||||
func New() *Client
|
||||
```
|
||||
|
||||
## REST Methods
|
||||
|
||||
### Get
|
||||
|
||||
Get provides an API like axios which sends a get request.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) Get(url string, cfg ...Config) (*Response, error)
|
||||
```
|
||||
|
||||
### Post
|
||||
|
||||
Post provides an API like axios which send post request.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) Post(url string, cfg ...Config) (*Response, error)
|
||||
```
|
||||
|
||||
### Put
|
||||
|
||||
Put provides an API like axios which send put request.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) Put(url string, cfg ...Config) (*Response, error)
|
||||
```
|
||||
|
||||
### Patch
|
||||
|
||||
Patch provides an API like axios which send patch request.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) Patch(url string, cfg ...Config) (*Response, error)
|
||||
```
|
||||
|
||||
### Delete
|
||||
|
||||
Delete provides an API like axios which send delete request.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) Delete(url string, cfg ...Config) (*Response, error)
|
||||
```
|
||||
|
||||
### Head
|
||||
|
||||
Head provides an API like axios which send head request.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) Head(url string, cfg ...Config) (*Response, error)
|
||||
```
|
||||
|
||||
### Options
|
||||
|
||||
Options provides an API like axios which send options request.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) Options(url string, cfg ...Config) (*Response, error)
|
||||
```
|
||||
|
||||
### Custom
|
||||
|
||||
Custom provides an API like axios which send custom request.
|
||||
|
||||
```go title="Signature"
|
||||
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.
|
||||
|
||||
It can be used to configure request data while sending requests using Get, Post, etc.
|
||||
|
||||
```go
|
||||
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 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.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) R() *Request
|
||||
```
|
||||
|
||||
### Hooks
|
||||
|
||||
#### RequestHook
|
||||
|
||||
RequestHook Request returns user-defined request hooks.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) RequestHook() []RequestHook
|
||||
```
|
||||
|
||||
#### ResponseHook
|
||||
|
||||
ResponseHook return user-define response hooks.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) ResponseHook() []ResponseHook
|
||||
```
|
||||
|
||||
#### AddRequestHook
|
||||
|
||||
AddRequestHook Add user-defined request hooks.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) AddRequestHook(h ...RequestHook) *Client
|
||||
```
|
||||
|
||||
#### AddResponseHook
|
||||
|
||||
AddResponseHook Add user-defined response hooks.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) AddResponseHook(h ...ResponseHook) *Client
|
||||
```
|
||||
|
||||
### JSON
|
||||
|
||||
#### JSONMarshal
|
||||
|
||||
JSONMarshal returns json marshal function in Core.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) JSONMarshal() utils.JSONMarshal
|
||||
```
|
||||
|
||||
#### JSONUnmarshal
|
||||
|
||||
JSONUnmarshal returns json unmarshal function in Core.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) JSONUnmarshal() utils.JSONUnmarshal
|
||||
```
|
||||
|
||||
#### SetJSONMarshal
|
||||
|
||||
SetJSONMarshal sets the JSON encoder.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) SetJSONMarshal(f utils.JSONMarshal) *Client
|
||||
```
|
||||
|
||||
#### SetJSONUnmarshal
|
||||
|
||||
Set the JSON decoder.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) SetJSONUnmarshal(f utils.JSONUnmarshal) *Client
|
||||
```
|
||||
|
||||
### XML
|
||||
|
||||
#### XMLMarshal
|
||||
|
||||
XMLMarshal returns xml marshal function in Core.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) XMLMarshal() utils.XMLMarshal
|
||||
```
|
||||
|
||||
#### XMLUnmarshal
|
||||
|
||||
XMLUnmarshal returns xml unmarshal function in Core.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) XMLUnmarshal() utils.XMLUnmarshal
|
||||
```
|
||||
|
||||
#### SetXMLMarshal
|
||||
|
||||
SetXMLMarshal sets the XML encoder.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) SetXMLMarshal(f utils.XMLMarshal) *Client
|
||||
```
|
||||
|
||||
#### SetXMLUnmarshal
|
||||
|
||||
SetXMLUnmarshal sets the XML decoder.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) SetXMLUnmarshal(f utils.XMLUnmarshal) *Client
|
||||
```
|
||||
|
||||
### TLS
|
||||
|
||||
#### TLSConfig
|
||||
|
||||
TLSConfig returns tlsConfig in client.
|
||||
If the client doesn't have a tlsConfig, this function will initialize it.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) TLSConfig() *tls.Config
|
||||
```
|
||||
|
||||
#### SetTLSConfig
|
||||
|
||||
SetTLSConfig sets tlsConfig in client.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) SetTLSConfig(config *tls.Config) *Client
|
||||
```
|
||||
|
||||
#### SetCertificates
|
||||
|
||||
SetCertificates method sets client certificates into client.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) SetCertificates(certs ...tls.Certificate) *Client
|
||||
```
|
||||
|
||||
#### SetRootCertificate
|
||||
|
||||
SetRootCertificate adds one or more root certificates into client.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) SetRootCertificate(path string) *Client
|
||||
```
|
||||
|
||||
#### SetRootCertificateFromString
|
||||
|
||||
SetRootCertificateFromString method adds one or more root certificates into the client.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) SetRootCertificateFromString(pem string) *Client
|
||||
```
|
||||
|
||||
### SetProxyURL
|
||||
|
||||
SetProxyURL sets proxy url in client. It will apply via core to hostclient.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) SetProxyURL(proxyURL string) error
|
||||
```
|
||||
|
||||
### RetryConfig
|
||||
|
||||
RetryConfig returns retry config in client.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) RetryConfig() *RetryConfig
|
||||
```
|
||||
|
||||
### SetRetryConfig
|
||||
|
||||
SetRetryConfig sets retry config in client, which is impl by addon/retry package.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) SetRetryConfig(config *RetryConfig) *Client
|
||||
```
|
||||
|
||||
### BaseURL
|
||||
|
||||
BaseURL returns baseurl in Client instance.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) BaseURL() string
|
||||
```
|
||||
|
||||
### SetBaseURL
|
||||
|
||||
SetBaseURL Set baseUrl which is prefix of real url.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) SetBaseURL(url string) *Client
|
||||
```
|
||||
|
||||
```go title="Example"
|
||||
cc := client.New()
|
||||
cc.SetBaseURL("https://httpbin.org/")
|
||||
|
||||
resp, err := cc.Get("/get")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
fmt.Println(string(resp.Body()))
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Click here to see the result</summary>
|
||||
|
||||
```
|
||||
{
|
||||
"args": {},
|
||||
...
|
||||
}
|
||||
```
|
||||
</details>
|
||||
|
||||
### Header
|
||||
|
||||
Header method returns header value via key, this method will visit all field in the header
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) Header(key string) []string
|
||||
```
|
||||
|
||||
#### 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.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) AddHeader(key, val string) *Client
|
||||
```
|
||||
|
||||
#### 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.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) SetHeader(key, val string) *Client
|
||||
```
|
||||
|
||||
#### 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.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) AddHeaders(h map[string][]string) *Client
|
||||
```
|
||||
|
||||
#### 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.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) SetHeaders(h map[string]string) *Client
|
||||
```
|
||||
|
||||
### Param
|
||||
|
||||
Param method returns params value via key, this method will visit all field in the query param.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) Param(key string) []string
|
||||
```
|
||||
|
||||
#### 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.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) AddParam(key, val string) *Client
|
||||
```
|
||||
|
||||
#### 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.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) SetParam(key, val string) *Client
|
||||
```
|
||||
|
||||
#### 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.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) AddParams(m map[string][]string) *Client
|
||||
```
|
||||
|
||||
#### 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.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) SetParams(m map[string]string) *Client
|
||||
```
|
||||
|
||||
#### 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.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) SetParamsWithStruct(v any) *Client
|
||||
```
|
||||
|
||||
#### DelParams
|
||||
|
||||
DelParams method deletes single or multiple params field and its values in client.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) DelParams(key ...string) *Client
|
||||
```
|
||||
|
||||
### 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.
|
||||
|
||||
```go title="Signature"
|
||||
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.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) SetReferer(r string) *Client
|
||||
```
|
||||
|
||||
### PathParam
|
||||
|
||||
PathParam returns the path param be set in request instance.
|
||||
If the path param doesn't exist, return empty string.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) PathParam(key string) string
|
||||
```
|
||||
|
||||
#### 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.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) SetPathParam(key, val string) *Client
|
||||
```
|
||||
|
||||
#### 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.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) SetPathParams(m map[string]string) *Client
|
||||
```
|
||||
|
||||
#### 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.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) SetPathParamsWithStruct(v any) *Client
|
||||
```
|
||||
|
||||
#### DelPathParams
|
||||
|
||||
DelPathParams method deletes single or multiple path params field and its values in client.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) DelPathParams(key ...string) *Client
|
||||
```
|
||||
|
||||
### Cookie
|
||||
|
||||
Cookie returns the cookie be set in request instance.
|
||||
If cookie doesn't exist, return empty string.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) Cookie(key string) string
|
||||
```
|
||||
|
||||
#### 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.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) SetCookie(key, val string) *Client
|
||||
```
|
||||
|
||||
```go title="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()))
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Click here to see the result</summary>
|
||||
|
||||
```
|
||||
{
|
||||
"cookies": {
|
||||
"john": "doe"
|
||||
}
|
||||
}
|
||||
```
|
||||
</details>
|
||||
|
||||
#### 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.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) SetCookies(m map[string]string) *Client
|
||||
```
|
||||
|
||||
#### 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.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) SetCookiesWithStruct(v any) *Client
|
||||
```
|
||||
|
||||
#### DelCookies
|
||||
|
||||
DelCookies method deletes single or multiple cookies field and its values in client.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) DelCookies(key ...string) *Client
|
||||
```
|
||||
|
||||
### 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.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) SetTimeout(t time.Duration) *Client
|
||||
```
|
||||
|
||||
### Debug
|
||||
|
||||
Debug enable log debug level output.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) Debug() *Client
|
||||
```
|
||||
|
||||
#### DisableDebug
|
||||
|
||||
DisableDebug disables log debug level output.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) DisableDebug() *Client
|
||||
```
|
||||
|
||||
### SetCookieJar
|
||||
|
||||
SetCookieJar sets cookie jar in client instance.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) SetCookieJar(cookieJar *CookieJar) *Client
|
||||
```
|
||||
|
||||
### SetDial
|
||||
|
||||
SetDial sets dial function in client.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) SetDial(dial fasthttp.DialFunc) *Client
|
||||
```
|
||||
|
||||
### SetLogger
|
||||
|
||||
SetLogger sets logger instance in client.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) SetLogger(logger log.CommonLogger) *Client
|
||||
```
|
||||
|
||||
### Logger
|
||||
|
||||
Logger returns logger instance of client.
|
||||
|
||||
```go title="Signature"
|
||||
func (c *Client) Logger() log.CommonLogger
|
||||
```
|
||||
|
||||
### Reset
|
||||
|
||||
Reset clears the Client object
|
||||
|
||||
```go title="Signature"
|
||||
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.
|
||||
|
||||
### C
|
||||
|
||||
C gets default client.
|
||||
|
||||
```go title="Signature"
|
||||
func C() *Client
|
||||
```
|
||||
|
||||
### Get
|
||||
|
||||
Get is a convenience method that sends a GET request using the `defaultClient`.
|
||||
|
||||
```go title="Signature"
|
||||
func Get(url string, cfg ...Config) (*Response, error)
|
||||
```
|
||||
|
||||
### Post
|
||||
|
||||
Post is a convenience method that sends a POST request using the `defaultClient`.
|
||||
|
||||
```go title="Signature"
|
||||
func Post(url string, cfg ...Config) (*Response, error)
|
||||
```
|
||||
|
||||
### Put
|
||||
|
||||
Put is a convenience method that sends a PUT request using the `defaultClient`.
|
||||
|
||||
```go title="Signature"
|
||||
func Put(url string, cfg ...Config) (*Response, error)
|
||||
```
|
||||
|
||||
### Patch
|
||||
|
||||
Patch is a convenience method that sends a PATCH request using the `defaultClient`.
|
||||
|
||||
```go title="Signature"
|
||||
func Patch(url string, cfg ...Config) (*Response, error)
|
||||
```
|
||||
|
||||
### Delete
|
||||
|
||||
Delete is a convenience method that sends a DELETE request using the `defaultClient`.
|
||||
|
||||
```go title="Signature"
|
||||
func Delete(url string, cfg ...Config) (*Response, error)
|
||||
```
|
||||
|
||||
### Head
|
||||
|
||||
Head sends a HEAD request using the `defaultClient`, a convenience method.
|
||||
|
||||
```go title="Signature"
|
||||
func Head(url string, cfg ...Config) (*Response, error)
|
||||
```
|
||||
|
||||
### Options
|
||||
|
||||
Options is a convenience method that sends an OPTIONS request using the `defaultClient`.
|
||||
|
||||
```go title="Signature"
|
||||
func Options(url string, cfg ...Config) (*Response, error)
|
||||
```
|
||||
|
||||
### Replace
|
||||
|
||||
Replace the defaultClient, the returned function can undo.
|
||||
|
||||
:::caution
|
||||
The default client should not be changed concurrently.
|
||||
:::
|
||||
|
||||
```go title="Signature"
|
||||
func Replace(c *Client) func()
|
||||
```
|
|
@ -223,9 +223,8 @@ DRAFT section
|
|||
|
||||
## 🌎 Client package
|
||||
|
||||
:::caution
|
||||
DRAFT section
|
||||
:::
|
||||
The Gofiber client has been completely rebuilt. It includes numerous new features such as Cookiejar, request/response hooks, and more.
|
||||
You can take a look to [client docs](./client/client.md) to see what's new with the client.
|
||||
|
||||
## 📎 Binding
|
||||
|
||||
|
|
Loading…
Reference in New Issue