From f4eac18dc205a12f6a1f72c04883036b4a5eed5a Mon Sep 17 00:00:00 2001 From: Muhammed Efe Cetin Date: Sun, 28 Apr 2024 23:23:43 +0300 Subject: [PATCH 01/14] docs: add docs for new client --- client/client.go | 6 +- client/request.go | 33 +- client/response.go | 2 +- docs/api/client.md | 663 ------------------------ docs/api/constants.md | 2 +- docs/api/hooks.md | 2 +- docs/api/log.md | 2 +- docs/client/_category_.json | 8 + docs/client/client.md | 741 +++++++++++++++++++++++++++ docs/client/request.md | 972 ++++++++++++++++++++++++++++++++++++ docs/client/response.md | 136 +++++ docs/whats_new.md | 5 +- 12 files changed, 1880 insertions(+), 692 deletions(-) delete mode 100644 docs/api/client.md create mode 100644 docs/client/_category_.json create mode 100644 docs/client/client.md create mode 100644 docs/client/request.md create mode 100644 docs/client/response.md diff --git a/client/client.go b/client/client.go index 101e534586..e9c65e14d8 100644 --- a/client/client.go +++ b/client/client.go @@ -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 = "" diff --git a/client/request.go b/client/request.go index 0bf2fb321c..ebddb0d0ee 100644 --- a/client/request.go +++ b/client/request.go @@ -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 } diff --git a/client/response.go b/client/response.go index f6ecd6fcd8..adb70ac4c4 100644 --- a/client/response.go +++ b/client/response.go @@ -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 diff --git a/docs/api/client.md b/docs/api/client.md deleted file mode 100644 index 1ffe50f410..0000000000 --- a/docs/api/client.md +++ /dev/null @@ -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("") - 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("") - 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) -``` - -
-Example handling for response values - -```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 -``` - -
- -### 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" -}) -// ... -``` diff --git a/docs/api/constants.md b/docs/api/constants.md index c9fa7904c4..fce36d3694 100644 --- a/docs/api/constants.md +++ b/docs/api/constants.md @@ -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. diff --git a/docs/api/hooks.md b/docs/api/hooks.md index c9852ad505..8717ba5851 100644 --- a/docs/api/hooks.md +++ b/docs/api/hooks.md @@ -1,7 +1,7 @@ --- id: hooks title: 🎣 Hooks -sidebar_position: 8 +sidebar_position: 7 --- import Tabs from '@theme/Tabs'; diff --git a/docs/api/log.md b/docs/api/log.md index d6a14a6df0..e53d6d4b0a 100644 --- a/docs/api/log.md +++ b/docs/api/log.md @@ -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. diff --git a/docs/client/_category_.json b/docs/client/_category_.json new file mode 100644 index 0000000000..35fb941567 --- /dev/null +++ b/docs/client/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "\uD83D\uDCD6 Client", + "position": 5, + "link": { + "type": "generated-index", + "description": "HTTP client for Fiber." + } +} \ No newline at end of file diff --git a/docs/client/client.md b/docs/client/client.md new file mode 100644 index 0000000000..70063c6353 --- /dev/null +++ b/docs/client/client.md @@ -0,0 +1,741 @@ +--- +id: client +title: 🌎 Client +description: >- + HTTP client for Gofiber. +sidebar_position: 1 +--- + +# Client + +The Client is used to create a Fiber Client with client-level settings that apply to all requests raise from the client. +Fiber Client also provides an option to override or merge most of the client settings at the request. + +It is built top on FastHTTP client. + +# TODO: Add more information about gofiber client. + +```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 +``` + +## Request Config + +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 configurate 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 +``` + +## RequestHook + +RequestHook Request returns user-defined request hooks. + +```go title="Signature" +func (c *Client) RequestHook() []RequestHook +``` + +## AddRequestHook + +AddRequestHook Add user-defined request hooks. + +```go title="Signature" +func (c *Client) AddRequestHook(h ...RequestHook) *Client +``` + +## ResponseHook + +ResponseHook return user-define response hooks. + +```go title="Signature" +func (c *Client) ResponseHook() []ResponseHook +``` + +## AddResponseHook + +AddResponseHook Add user-defined response hooks. + +```go title="Signature" +func (c *Client) AddResponseHook(h ...ResponseHook) *Client +``` + +## JSONMarshal + +JSONMarshal returns json marshal function in Core. + +```go title="Signature" +func (c *Client) JSONMarshal() utils.JSONMarshal +``` + +## SetJSONMarshal + +SetJSONMarshal sets the JSON encoder. + +```go title="Signature" +func (c *Client) SetJSONMarshal(f utils.JSONMarshal) *Client +``` + +## JSONUnmarshal + +JSONUnmarshal returns json unmarshal function in Core. + +```go title="Signature" +func (c *Client) JSONUnmarshal() utils.JSONUnmarshal +``` + +## SetJSONUnmarshal + +Set json decoder. + +```go title="Signature" +func (c *Client) SetJSONUnmarshal(f utils.JSONUnmarshal) *Client +``` + +## XMLMarshal + +XMLMarshal returns xml marshal function in Core. + +```go title="Signature" +func (c *Client) XMLMarshal() utils.XMLMarshal +``` + +## SetXMLMarshal + +SetXMLMarshal Set xml encoder. + +```go title="Signature" +func (c *Client) SetXMLMarshal(f utils.XMLMarshal) *Client +``` + +## XMLUnmarshal + +XMLUnmarshal returns xml unmarshal function in Core. + +```go title="Signature" +func (c *Client) XMLUnmarshal() utils.XMLUnmarshal +``` + +## SetXMLUnmarshal + +SetXMLUnmarshal Set xml decoder. + +```go title="Signature" +func (c *Client) SetXMLUnmarshal(f utils.XMLUnmarshal) *Client +``` + +## TLSConfig + +TLSConfig returns tlsConfig in client. +If client don't have tlsConfig, this function will init 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 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 +``` + +## 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 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 +``` + +## 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 +``` + +## 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 + +DisableDebug disables log debug level output. + +```go title="Signature" +func (c *Client) SetCookieJar(cookieJar *CookieJar) *Client +``` + +## SetCookieJar + +SetCookieJar sets cookie jar in client instance. + +```go title="Signature" +func (c *Client) SetCookieJar(cookieJar *CookieJar) *Client +``` + +## Get + +Get provide an API like axios which send get request. + +```go title="Signature" +func (c *Client) Get(url string, cfg ...Config) (*Response, error) +``` + +## Post + +Post provide an API like axios which send post request. + +```go title="Signature" +func (c *Client) Post(url string, cfg ...Config) (*Response, error) +``` + +## Head + +Head provide an API like axios which send head request. + +```go title="Signature" +func (c *Client) Head(url string, cfg ...Config) (*Response, error) +``` + +## Put + +Put provide an API like axios which send put request. + +```go title="Signature" +func (c *Client) Put(url string, cfg ...Config) (*Response, error) +``` + +## Delete + +Delete provide an API like axios which send delete request. + +```go title="Signature" +func (c *Client) Delete(url string, cfg ...Config) (*Response, error) +``` + +## Options + +Options provide an API like axios which send options request. + +```go title="Signature" +func (c *Client) Options(url string, cfg ...Config) (*Response, error) +``` + +## Patch + +Patch provide an API like axios which send patch request. + +```go title="Signature" +func (c *Client) Patch(url string, cfg ...Config) (*Response, error) +``` + +## Custom + +Custom provide an API like axios which send custom request. + +```go title="Signature" +func (c *Client) Custom(url, method string, cfg ...Config) (*Response, error) +``` + +## 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() +``` + +## Replace + +Replace the defaultClient, the returned function can undo. + +:::caution +The default client should not be changed concurrently. +::: + +```go title="Signature" +func Replace() +``` + +## Get + +Get send a get request use defaultClient, a convenient method. + +```go title="Signature" +func Get(url string, cfg ...Config) (*Response, error) +``` + +## Post + +Post send a post request use defaultClient, a convenient method. + +```go title="Signature" +func Post(url string, cfg ...Config) (*Response, error) +``` + +## Head + +Head send a head request use defaultClient, a convenient method. + +```go title="Signature" +func Head(url string, cfg ...Config) (*Response, error) +``` + +## Put + +Put send a put request use defaultClient, a convenient method. + +```go title="Signature" +func Put(url string, cfg ...Config) (*Response, error) +``` + +## Delete + +Delete send a delete request use defaultClient, a convenient method. + +```go title="Signature" +func Delete(url string, cfg ...Config) (*Response, error) +``` + +## Options + +Options send a options request use defaultClient, a convenient method. + +```go title="Signature" +func Options(url string, cfg ...Config) (*Response, error) +``` + +## Patch + +Patch send a patch request use defaultClient, a convenient method. + +```go title="Signature" +func Patch(url string, cfg ...Config) (*Response, error) +``` \ No newline at end of file diff --git a/docs/client/request.md b/docs/client/request.md new file mode 100644 index 0000000000..65251105ce --- /dev/null +++ b/docs/client/request.md @@ -0,0 +1,972 @@ +--- +id: request +title: 🌎 Request +description: >- + Request methods of Gofiber HTTP client. +sidebar_position: 2 +--- + +# Request + +Request is the structure contains request data. + +```go +type Request struct { + url string + method string + userAgent string + boundary string + referer string + ctx context.Context + header *Header + params *QueryParam + cookies *Cookie + path *PathParam + + timeout time.Duration + maxRedirects int + + client *Client + + body any + formData *FormData + files []*File + bodyType bodyType + + RawRequest *fasthttp.Request +} +``` + +## AcquireRequest + +AcquireRequest returns an empty request object from the pool. +The returned request may be returned to the pool with ReleaseRequest when no longer needed. +This allows reducing GC load. + +```go title="Signature" +func AcquireRequest() *Request +``` + +## ReleaseRequest + +ReleaseRequest returns the object acquired via AcquireRequest to the pool. +Do not access the released Request object, otherwise data races may occur. + +```go title="Signature" +func ReleaseRequest(req *Request) +``` + +## Method + +Method returns HTTP method in request. + +```go title="Signature" +func (r *Request) Method() string +``` + +## SetMethod + +SetMethod will set method for Request object. The user should use request method to set method. + +```go title="Signature" +func (r *Request) SetMethod(method string) *Request +``` + +## URL + +URL returns request url in Request instance. + +```go title="Signature" +func (r *Request) URL() string +``` + +## SetURL + +SetURL will set url for Request object. + +```go title="Signature" +func (r *Request) SetURL(url string) *Request +``` + +## Client + +Client gets the Client instance of Request. + +```go title="Signature" +func (r *Request) Client() *Client +``` + +## SetClient + +SetClient method sets client of request instance. +If the client given is null, it will panic. + +```go title="Signature" +func (r *Request) SetClient(c *Client) *Request +``` + +## Context + +Context returns the Context if its already set in request. Otherwise it returns `context.Background()`. + +```go title="Signature" +func (r *Request) Context() context.Context +``` + +## SetContext + +SetContext sets the context.Context for current Request. It allows to interrupt the request execution if ctx.Done() channel is closed. +See https://blog.golang.org/context article and the "context" package documentation. + +```go title="Signature" +func (r *Request) SetContext(ctx context.Context) *Request +``` + +## Header + +Header method returns header value via key, this method will visit all field in the header. +```go title="Signature" +func (r *Request) Header(key string) []string +``` + +## AddHeader + +AddHeader method adds a single header field and its value in the request instance. + +```go title="Signature" +func (r *Request) AddHeader(key, val string) *Request +``` + +## SetHeader + +SetHeader method sets a single header field and its value in the request instance. +It will override header which has been set in client instance. + +```go title="Signature" +func (r *Request) SetHeader(key, val string) *Request +``` + +## AddHeaders + +AddHeaders method adds multiple header fields and its values at one go in the request instance. + +```go title="Signature" +func (r *Request) AddHeaders(h map[string][]string) *Request +``` + +## SetHeaders + +SetHeaders method sets multiple header fields and its values at one go in the request instance. +It will override header which has been set in client instance. + +```go title="Signature" +func (r *Request) SetHeaders(h map[string]string) *Request +``` + +## Param + +Param method returns params value via key, this method will visit all field in the query param. + +```go title="Signature" +func (r *Request) Param(key string) []string +``` + +## AddParam + +AddParam method adds a single param field and its value in the request instance. + +```go title="Signature" +func (r *Request) AddParam(key, val string) *Request +``` + +## SetParam + +SetParam method sets a single param field and its value in the request instance. +It will override param which has been set in client instance. + +```go title="Signature" +func (r *Request) SetParam(key, val string) *Request +``` + +## AddParams + +AddParams method adds multiple param fields and its values at one go in the request instance. + +```go title="Signature" +func (r *Request) AddParams(m map[string][]string) *Request +``` + +## SetParams + +SetParams method sets multiple param fields and its values at one go in the request instance. +It will override param which has been set in client instance. + +```go title="Signature" +func (r *Request) SetParams(m map[string]string) *Request +``` + +## SetParamsWithStruct + +SetParamsWithStruct method sets multiple param fields and its values at one go in the request instance. +It will override param which has been set in client instance. + +```go title="Signature" +func (r *Request) SetParamsWithStruct(v any) *Request +``` + +## DelParams + +DelParams method deletes single or multiple param fields ant its values. + +```go title="Signature" +func (r *Request) DelParams(key ...string) *Request +``` + +## UserAgent + +UserAgent returns user agent in request instance. + +```go title="Signature" +func (r *Request) UserAgent() string +``` + +## SetUserAgent + +SetUserAgent method sets user agent in request. +It will override user agent which has been set in client instance. + +```go title="Signature" +func (r *Request) SetUserAgent(ua string) *Request +``` + +## Boundary + +Boundary returns boundary in multipart boundary. + +```go title="Signature" +func (r *Request) Boundary() string +``` + +## SetBoundary + +SetBoundary method sets multipart boundary. + +```go title="Signature" +func (r *Request) SetBoundary(b string) *Request +``` + +## Referer + +Referer returns referer in request instance. + +```go title="Signature" +func (r *Request) Referer() string +``` + +## SetReferer + +SetReferer method sets referer in request. +It will override referer which set in client instance. + +```go title="Signature" +func (r *Request) SetReferer(referer string) *Request +``` + +## Cookie + +Cookie returns the cookie be set in request instance. If the cookie doesn't exist, returns empty string. + +```go title="Signature" +func (r *Request) Cookie(key string) string +``` + +## SetCookie + +SetCookie method sets a single cookie field and its value in the request instance. +It will override cookie which set in client instance. + +```go title="Signature" +func (r *Request) SetCookie(key, val string) *Request +``` + +## SetCookies + +SetCookies method sets multiple cookie fields and its values at one go in the request instance. +It will override cookie which set in client instance. + +```go title="Signature" +func (r *Request) SetCookies(m map[string]string) *Request +``` + +## SetCookiesWithStruct + +SetCookiesWithStruct method sets multiple cookie fields and its values at one go in the request instance. +It will override cookie which set in client instance. + +```go title="Signature" +func (r *Request) SetCookiesWithStruct(v any) *Request +``` + +## DelCookies + +DelCookies method deletes single or multiple cookie fields ant its values. + +```go title="Signature" +func (r *Request) DelCookies(key ...string) *Request +``` + +## 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 (r *Request) PathParam(key string) string +``` + +## SetPathParam + +SetPathParam method sets a single path param field and its value in the request instance. +It will override path param which set in client instance. + +```go title="Signature" +func (r *Request) SetPathParam(key, val string) *Request +``` + +## SetPathParams + +SetPathParams method sets multiple path param fields and its values at one go in the request instance. +It will override path param which set in client instance. + +```go title="Signature" +func (r *Request) SetPathParams(m map[string]string) *Request +``` + +## SetPathParamsWithStruct + +SetPathParamsWithStruct method sets multiple path param fields and its values at one go in the request instance. +It will override path param which set in client instance. + +```go title="Signature" +func (r *Request) SetPathParamsWithStruct(v any) *Request +``` + +## DelPathParams + +DelPathParams method deletes single or multiple path param fields ant its values. + +```go title="Signature" +func (r *Request) DelPathParams(key ...string) *Request +``` + +## ResetPathParams + +ResetPathParams deletes all path params. + +```go title="Signature" +func (r *Request) ResetPathParams() *Request +``` + +## SetJSON + +SetJSON method sets JSON body in request. + +```go title="Signature" +func (r *Request) SetJSON(v any) *Request +``` + +## SetXML + +SetXML method sets XML body in request. + +```go title="Signature" +func (r *Request) SetXML(v any) *Request +``` + +## SetRawBody + +SetRawBody method sets body with raw data in request. + +```go title="Signature" +func (r *Request) SetRawBody(v []byte) *Request +``` + +## FormData + +FormData method returns form data value via key, this method will visit all field in the form data. + +```go title="Signature" +func (r *Request) FormData(key string) []string +``` + +## AddFormData + +AddFormData method adds a single form data field and its value in the request instance. + +```go title="Signature" +func (r *Request) AddFormData(key, val string) *Request +``` + +## SetFormData + +SetFormData method sets a single form data field and its value in the request instance. + +```go title="Signature" +func (r *Request) SetFormData(key, val string) *Request +``` + +## AddFormDatas + +AddFormDatas method adds multiple form data fields and its values in the request instance. + +```go title="Signature" +func (r *Request) AddFormDatas(m map[string][]string) *Request +``` + +## SetFormDatas + +SetFormDatas method sets multiple form data fields and its values in the request instance. + +```go title="Signature" +func (r *Request) SetFormDatas(m map[string]string) *Request +``` + +## SetFormDatas + +SetFormDatas method sets multiple form data fields and its values in the request instance. + +```go title="Signature" +func (r *Request) SetFormDatas(m map[string]string) *Request +``` + +## SetFormDatasWithStruct + +SetFormDatasWithStruct method sets multiple form data fields and its values in the request instance via struct. + +```go title="Signature" +func (r *Request) SetFormDatasWithStruct(v any) *Request +``` + +## DelFormDatas + +DelFormDatas method deletes multiple form data fields and its value in the request instance. + +```go title="Signature" +func (r *Request) DelFormDatas(key ...string) *Request +``` + +## File + +File returns file ptr store in request obj by name. +If the name field is empty, it will try to match path. + +```go title="Signature" +func (r *Request) File(name string) *File +``` + +## FileByPath + +FileByPath returns file ptr store in request obj by path. + +```go title="Signature" +func (r *Request) FileByPath(path string) *File +``` + +## AddFile + +AddFile method adds single file field and its value in the request instance via file path. + +```go title="Signature" +func (r *Request) AddFile(path string) *Request +``` + +## AddFileWithReader + +AddFileWithReader method adds single field and its value in the request instance via reader. + +```go title="Signature" +func (r *Request) AddFileWithReader(name string, reader io.ReadCloser) *Request +``` + +## AddFiles + +AddFiles method adds multiple file fields and its value in the request instance via File instance. + +```go title="Signature" +func (r *Request) AddFiles(files ...*File) *Request +``` + +## Timeout + +Timeout returns the length of timeout in request. + +```go title="Signature" +func (r *Request) Timeout() time.Duration +``` + +## SetTimeout + +SetTimeout method sets timeout field and its values at one go in the request instance. +It will override timeout which set in client instance. + +```go title="Signature" +func (r *Request) SetTimeout(t time.Duration) *Request +``` + +## MaxRedirects + +MaxRedirects returns the max redirects count in request. + +```go title="Signature" +func (r *Request) MaxRedirects() int +``` + +## SetMaxRedirects + +SetMaxRedirects method sets the maximum number of redirects at one go in the request instance. +It will override max redirect which set in client instance. + +```go title="Signature" +func (r *Request) SetMaxRedirects(count int) *Request +``` + +## Get + +Get sends the GET request. +It sets URL and HTTP method and then it sends the request. + +```go title="Signature" +func (r *Request) Get(url string) (*Response, error) +``` + +## Post + +Post sends the POST request. +It sets URL and HTTP method and then it sends the request. + +```go title="Signature" +func (r *Request) Post(url string) (*Response, error) +``` + +## Head + +Head sends the HEAD request. +It sets URL and HTTP method and then it sends the request. + +```go title="Signature" +func (r *Request) Head(url string) (*Response, error) +``` + +## Put + +Put sends the PUT request. +It sets URL and HTTP method and then it sends the request. + +```go title="Signature" +func (r *Request) Put(url string) (*Response, error) +``` + +## Delete + +Delete sends the DELETE request. +It sets URL and HTTP method and then it sends the request. + +```go title="Signature" +func (r *Request) Delete(url string) (*Response, error) +``` + +## Options + +Options sends the OPTIONS request. +It sets URL and HTTP method and then it sends the request. + +```go title="Signature" +func (r *Request) Options(url string) (*Response, error) +``` + +## Patch + +Patch sends the PATCH request. +It sets URL and HTTP method and then it sends the request. + +```go title="Signature" +func (r *Request) Patch(url string) (*Response, error) +``` + +## Custom + +Custom sends a request with custom HTTP method. +It sets URL and HTTP method and then it sends the request. +You can use Custom to send requests with methods like TRACE, CONNECT. + +```go title="Signature" +func (r *Request) Custom(url, method string) (*Response, error) +``` + +## Send + +Send sends HTTP request. + +```go title="Signature" +func (r *Request) Send() (*Response, error) +``` + +## Reset + +Reset clears Request object, used by ReleaseRequest method. + +```go title="Signature" +func (r *Request) Reset() +``` + +# Header + +Header is a wrapper which wrap http.Header, the header in client and request will store in it. + +```go +type Header struct { + *fasthttp.RequestHeader +} +``` + +## PeekMultiple + +PeekMultiple methods returns multiple field in header with same key. + +```go title="Signature" +func (h *Header) PeekMultiple(key string) []string +``` + +## AddHeaders + +AddHeaders receives a map and add each value to header. + +```go title="Signature" +func (h *Header) AddHeaders(r map[string][]string) +``` + +## SetHeaders + +SetHeaders will override all headers. + +```go title="Signature" +func (h *Header) SetHeaders(r map[string]string) +``` + +# QueryParam + +QueryParam is a wrapper which wrap url.Values, the query string and formdata in client and request will store in it. + +```go +type QueryParam struct { + *fasthttp.Args +} +``` + +## AddParams + +AddParams receive a map and add each value to param. + +```go title="Signature" +func (p *QueryParam) AddParams(r map[string][]string) +``` + +## SetParams + +SetParams will override all params. + +```go title="Signature" +func (p *QueryParam) SetParams(r map[string]string) +``` + +## SetParamsWithStruct + +SetParamsWithStruct will override all params with struct or pointer of struct. +Nested structs are not currently supported. + +```go title="Signature" +func (p *QueryParam) SetParamsWithStruct(v any) +``` + +# Cookie + +Cookie is a map which to store the cookies. + +```go +type Cookie map[string]string +``` + +## Add + +Add method impl the method in WithStruct interface. + +```go title="Signature" +func (c Cookie) Add(key, val string) +``` + +## Del + +Del method impl the method in WithStruct interface. + +```go title="Signature" +func (c Cookie) Del(key string) +``` + +## SetCookie + +SetCookie method sets a single val in Cookie. + +```go title="Signature" +func (c Cookie) SetCookie(key, val string) +``` + +## SetCookies + +SetCookies method sets multiple val in Cookie. + +```go title="Signature" +func (c Cookie) SetCookies(m map[string]string) +``` + +## SetCookiesWithStruct + +SetCookiesWithStruct method sets multiple val in Cookie via a struct. + +```go title="Signature" +func (c Cookie) SetCookiesWithStruct(v any) +``` + +## DelCookies + +DelCookies method deletes multiple val in Cookie. + +```go title="Signature" +func (c Cookie) DelCookies(key ...string) +``` + +## VisitAll + +VisitAll method receive a function which can travel the all val. + +```go title="Signature" +func (c Cookie) VisitAll(f func(key, val string)) +``` + +## Reset + +Reset clears the Cookie object. + +```go title="Signature" +func (c Cookie) Reset() +``` + +# PathParam + +PathParam is a map which to store path params. + +```go +type PathParam map[string]string +``` + +## Add + +Add method impl the method in WithStruct interface. + +```go title="Signature" +func (p PathParam) Add(key, val string) +``` + +## Del + +Del method impl the method in WithStruct interface. + +```go title="Signature" +func (p PathParam) Del(key string) +``` + +## SetParam + +SetParam method sets a single val in PathParam. + +```go title="Signature" +func (p PathParam) SetParam(key, val string) +``` + +## SetParams + +SetParams method sets multiple val in PathParam. + +```go title="Signature" +func (p PathParam) SetParams(m map[string]string) +``` + +## SetParamsWithStruct + +SetParamsWithStruct method sets multiple val in PathParam via a struct. + +```go title="Signature" +func (p PathParam) SetParamsWithStruct(v any) +``` + +## DelParams + +DelParams method deletes multiple val in PathParams. + +```go title="Signature" +func (p PathParam) DelParams(key ...string) +``` + +## VisitAll + +VisitAll method receive a function which can travel the all val. + +```go title="Signature" +func (p PathParam) VisitAll(f func(key, val string)) +``` + +## Reset + +Reset clears the PathParam object. + +```go title="Signature" +func (p PathParam) Reset() +``` + +# FormData + +FormData is a wrapper of fasthttp.Args and it is used for url encode body and file body. + +```go +type FormData struct { + *fasthttp.Args +} +``` + +## AddData + +AddData method is a wrapper of Args's Add method. + +```go title="Signature" +func (f *FormData) AddData(key, val string) +``` + +## SetData + +SetData method is a wrapper of Args's Set method. + +```go title="Signature" +func (f *FormData) SetData(key, val string) +``` + +## AddDatas + +AddDatas method supports add multiple fields. + +```go title="Signature" +func (f *FormData) AddDatas(m map[string][]string) +``` + +## SetDatas + +SetDatas method supports set multiple fields. + +```go title="Signature" +func (f *FormData) SetDatas(m map[string]string) +``` + +## SetDatasWithStruct + +SetDatasWithStruct method supports set multiple fields via a struct. + +```go title="Signature" +func (f *FormData) SetDatasWithStruct(v any) +``` + +## DelDatas + +DelDatas method deletes multiple fields. + +```go title="Signature" +func (f *FormData) DelDatas(key ...string) +``` + +## Reset + +Reset clear the FormData object. + +```go title="Signature" +func (f *FormData) Reset() +``` + +# File + +File is a struct which support send files via request. + +```go +type File struct { + name string + fieldName string + path string + reader io.ReadCloser +} +``` + +## AcquireFile + +AcquireFile returns an File object from the pool. +And you can set field in the File with SetFileFunc. + +The returned file may be returned to the pool with ReleaseFile when no longer needed. +This allows reducing GC load. + +```go title="Signature" +func AcquireFile(setter ...SetFileFunc) *File +``` + +## ReleaseFile + +ReleaseFile returns the object acquired via AcquireFile to the pool. +Do not access the released File object, otherwise data races may occur. + +```go title="Signature" +func ReleaseFile(f *File) +``` + +## SetName + +SetName method sets file name. + +```go title="Signature" +func (f *File) SetName(n string) +``` + +## SetFieldName + +SetFieldName method sets key of file in the body. + +```go title="Signature" +func (f *File) SetFieldName(n string) +``` + +## SetPath + +SetPath method set file path. + +```go title="Signature" +func (f *File) SetPath(p string) +``` + +## SetReader + +SetReader method can receive a io.ReadCloser which will be closed in parserBody hook. + +```go title="Signature" +func (f *File) SetReader(r io.ReadCloser) +``` + +## Reset + +Reset clear the File object. + +```go title="Signature" +func (f *File) Reset() +``` \ No newline at end of file diff --git a/docs/client/response.md b/docs/client/response.md new file mode 100644 index 0000000000..ed0609bf2b --- /dev/null +++ b/docs/client/response.md @@ -0,0 +1,136 @@ +--- +id: response +title: 🌎 Response +description: >- + Response methods of Gofiber HTTP client. +sidebar_position: 3 +--- + +# Response + +Response is the result of a request. This object is used to access the response data. + +```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 +``` + +## 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 +``` + +## 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 +``` + +## 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 Request object and Response object, after call Close please don't use these object. + +```go title="Signature" +func (r *Response) Close() +``` \ No newline at end of file diff --git a/docs/whats_new.md b/docs/whats_new.md index 12750bebb9..735dc345a3 100644 --- a/docs/whats_new.md +++ b/docs/whats_new.md @@ -227,9 +227,8 @@ DRAFT section ## 🌎 Client package -:::caution -DRAFT section -::: +The Gofiber client has been built from the scratch. It comes with lots of new features like Cookiejar, request/response hooks etc. +You can take a look to [client docs](./client/client.md) to see what's new with the client. ## 📎 Binding From a14bec71e3cd9077db004889b22e3e5d18fdfa1f Mon Sep 17 00:00:00 2001 From: Muhammed Efe Cetin Date: Fri, 10 May 2024 14:07:34 +0300 Subject: [PATCH 02/14] Add docs for client hooks --- docs/client/hooks.md | 256 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 256 insertions(+) create mode 100644 docs/client/hooks.md diff --git a/docs/client/hooks.md b/docs/client/hooks.md new file mode 100644 index 0000000000..8ad2eabbca --- /dev/null +++ b/docs/client/hooks.md @@ -0,0 +1,256 @@ +--- +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) +} +``` + +
+Click here to see the result + +``` +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 +``` +
+ +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) + } +} +``` + +
+Click here to see the result + +``` +Hook 1. +panic: error + +goroutine 1 [running]: +main.main() + main.go:25 +0xaa +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. + +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) + } +} +``` + +
+Click here to see the result + +``` +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 +``` +
+ +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) + } +} +``` + +
+Click here to see the result + +``` +Hook 1 +Hook 2 +panic: error + +goroutine 1 [running]: +main.main() + main.go:30 +0xd6 +exit status 2 +``` +
+ +:::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) + } +} +``` + +
+Click here to see the result + +``` +Hook 1 +Hook 2 +``` +
From 3085f7017ddfc62319677a4b520b6adf134ea522 Mon Sep 17 00:00:00 2001 From: Muhammed Efe Cetin Date: Fri, 10 May 2024 22:51:17 +0300 Subject: [PATCH 03/14] Add docs for client examples --- docs/client/examples.md | 209 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 209 insertions(+) create mode 100644 docs/client/examples.md diff --git a/docs/client/examples.md b/docs/client/examples.md new file mode 100644 index 0000000000..ae291b4748 --- /dev/null +++ b/docs/client/examples.md @@ -0,0 +1,209 @@ +--- +id: examples +title: 🍳 Examples +description: >- + Some useful examples about the client. +sidebar_position: 5 +--- + +# Basic Auth + + + + +```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())) +} +``` + + + +```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") +} +``` + + + +# TLS + + + + +```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())) +} +``` + + + +```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) + } +} +``` + + + +# 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())) +} +``` + +
+Click here to see the result + +``` +{ + "cookies": { + "john": "doe" + } +} +``` +
+ + +## 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)) +} +``` + +
+Click here to see the result + +``` +[john=doe; path=/] +``` +
From 62209904eab14eca6cddd6bdafbf014a272376c2 Mon Sep 17 00:00:00 2001 From: Muhammed Efe Cetin Date: Fri, 10 May 2024 23:11:42 +0300 Subject: [PATCH 04/14] Some fixes. --- docs/client/client.md | 67 ++++++++++++++++++++++++++++++----------- docs/client/request.md | 32 ++++++++++++-------- docs/client/response.md | 13 ++++++-- docs/whats_new.md | 4 +-- 4 files changed, 81 insertions(+), 35 deletions(-) diff --git a/docs/client/client.md b/docs/client/client.md index 70063c6353..70cc51c577 100644 --- a/docs/client/client.md +++ b/docs/client/client.md @@ -8,12 +8,43 @@ sidebar_position: 1 # Client -The Client is used to create a Fiber Client with client-level settings that apply to all requests raise from the client. -Fiber Client also provides an option to override or merge most of the client settings at the request. +The Fiber Client 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. -It is built top on FastHTTP client. +## 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. -# TODO: Add more information about gofiber client. +## 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 { @@ -75,7 +106,7 @@ func New() *Client 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 configurate request data while sending requests using Get, Post etc. +It can be used to configure request data while sending requests using Get, Post, etc. ```go type Config struct { @@ -164,7 +195,7 @@ func (c *Client) JSONUnmarshal() utils.JSONUnmarshal ## SetJSONUnmarshal -Set json decoder. +Set the JSON decoder. ```go title="Signature" func (c *Client) SetJSONUnmarshal(f utils.JSONUnmarshal) *Client @@ -180,7 +211,7 @@ func (c *Client) XMLMarshal() utils.XMLMarshal ## SetXMLMarshal -SetXMLMarshal Set xml encoder. +SetXMLMarshal sets the XML encoder. ```go title="Signature" func (c *Client) SetXMLMarshal(f utils.XMLMarshal) *Client @@ -196,7 +227,7 @@ func (c *Client) XMLUnmarshal() utils.XMLUnmarshal ## SetXMLUnmarshal -SetXMLUnmarshal Set xml decoder. +SetXMLUnmarshal sets the XML decoder. ```go title="Signature" func (c *Client) SetXMLUnmarshal(f utils.XMLUnmarshal) *Client @@ -205,7 +236,7 @@ func (c *Client) SetXMLUnmarshal(f utils.XMLUnmarshal) *Client ## TLSConfig TLSConfig returns tlsConfig in client. -If client don't have tlsConfig, this function will init it. +If the client doesn't have a tlsConfig, this function will initialize it. ```go title="Signature" func (c *Client) TLSConfig() *tls.Config @@ -565,7 +596,7 @@ func (c *Client) SetCookieJar(cookieJar *CookieJar) *Client ## Get -Get provide an API like axios which send get request. +Get provides an API like axios which sends a get request. ```go title="Signature" func (c *Client) Get(url string, cfg ...Config) (*Response, error) @@ -573,7 +604,7 @@ func (c *Client) Get(url string, cfg ...Config) (*Response, error) ## Post -Post provide an API like axios which send post request. +Post provides an API like axios which send post request. ```go title="Signature" func (c *Client) Post(url string, cfg ...Config) (*Response, error) @@ -581,7 +612,7 @@ func (c *Client) Post(url string, cfg ...Config) (*Response, error) ## Head -Head provide an API like axios which send head request. +Head provides an API like axios which send head request. ```go title="Signature" func (c *Client) Head(url string, cfg ...Config) (*Response, error) @@ -589,7 +620,7 @@ func (c *Client) Head(url string, cfg ...Config) (*Response, error) ## Put -Put provide an API like axios which send put request. +Put provides an API like axios which send put request. ```go title="Signature" func (c *Client) Put(url string, cfg ...Config) (*Response, error) @@ -597,7 +628,7 @@ func (c *Client) Put(url string, cfg ...Config) (*Response, error) ## Delete -Delete provide an API like axios which send delete request. +Delete provides an API like axios which send delete request. ```go title="Signature" func (c *Client) Delete(url string, cfg ...Config) (*Response, error) @@ -605,7 +636,7 @@ func (c *Client) Delete(url string, cfg ...Config) (*Response, error) ## Options -Options provide an API like axios which send options request. +Options provides an API like axios which send options request. ```go title="Signature" func (c *Client) Options(url string, cfg ...Config) (*Response, error) @@ -613,7 +644,7 @@ func (c *Client) Options(url string, cfg ...Config) (*Response, error) ## Patch -Patch provide an API like axios which send patch request. +Patch provides an API like axios which send patch request. ```go title="Signature" func (c *Client) Patch(url string, cfg ...Config) (*Response, error) @@ -621,7 +652,7 @@ func (c *Client) Patch(url string, cfg ...Config) (*Response, error) ## Custom -Custom provide an API like axios which send custom request. +Custom provides an API like axios which send custom request. ```go title="Signature" func (c *Client) Custom(url, method string, cfg ...Config) (*Response, error) @@ -738,4 +769,4 @@ Patch send a patch request use defaultClient, a convenient method. ```go title="Signature" func Patch(url string, cfg ...Config) (*Response, error) -``` \ No newline at end of file +``` diff --git a/docs/client/request.md b/docs/client/request.md index 65251105ce..4b9f54cd79 100644 --- a/docs/client/request.md +++ b/docs/client/request.md @@ -8,7 +8,15 @@ sidebar_position: 2 # Request -Request is the structure contains request data. +The `Request` structure in Gofiber's HTTP client represents an HTTP request. It encapsulates all the necessary information required to send a request to a server. This includes: + +- **URL**: The URL to which the request is sent. +- **Method**: The HTTP method used (GET, POST, PUT, DELETE, etc.). +- **Headers**: HTTP headers that provide additional information about the request or the needed responses. +- **Body**: The data sent with the request, typically used with POST and PUT methods. +- **Query Parameters**: Parameters that are appended to the URL, used to modify the request or to provide additional information. + +This structure is designed to be flexible and efficient, allowing users to easily construct and modify HTTP requests according to their needs. ```go type Request struct { @@ -50,7 +58,7 @@ func AcquireRequest() *Request ## ReleaseRequest ReleaseRequest returns the object acquired via AcquireRequest to the pool. -Do not access the released Request object, otherwise data races may occur. +Do not access the released Request object; otherwise, data races may occur. ```go title="Signature" func ReleaseRequest(req *Request) @@ -216,7 +224,7 @@ func (r *Request) SetParamsWithStruct(v any) *Request ## DelParams -DelParams method deletes single or multiple param fields ant its values. +DelParams method deletes single or multiple param fields and their values. ```go title="Signature" func (r *Request) DelParams(key ...string) *Request @@ -532,7 +540,7 @@ func (r *Request) SetMaxRedirects(count int) *Request ## Get Get sends the GET request. -It sets URL and HTTP method and then it sends the request. +It sets the URL and HTTP method, and then it sends the request. ```go title="Signature" func (r *Request) Get(url string) (*Response, error) @@ -541,7 +549,7 @@ func (r *Request) Get(url string) (*Response, error) ## Post Post sends the POST request. -It sets URL and HTTP method and then it sends the request. +It sets the URL and HTTP method, and then it sends the request. ```go title="Signature" func (r *Request) Post(url string) (*Response, error) @@ -550,7 +558,7 @@ func (r *Request) Post(url string) (*Response, error) ## Head Head sends the HEAD request. -It sets URL and HTTP method and then it sends the request. +It sets the URL and HTTP method, and then it sends the request. ```go title="Signature" func (r *Request) Head(url string) (*Response, error) @@ -559,7 +567,7 @@ func (r *Request) Head(url string) (*Response, error) ## Put Put sends the PUT request. -It sets URL and HTTP method and then it sends the request. +It sets the URL and HTTP method, and then it sends the request. ```go title="Signature" func (r *Request) Put(url string) (*Response, error) @@ -568,7 +576,7 @@ func (r *Request) Put(url string) (*Response, error) ## Delete Delete sends the DELETE request. -It sets URL and HTTP method and then it sends the request. +It sets the URL and HTTP method, and then it sends the request. ```go title="Signature" func (r *Request) Delete(url string) (*Response, error) @@ -577,7 +585,7 @@ func (r *Request) Delete(url string) (*Response, error) ## Options Options sends the OPTIONS request. -It sets URL and HTTP method and then it sends the request. +It sets the URL and HTTP method, and then it sends the request. ```go title="Signature" func (r *Request) Options(url string) (*Response, error) @@ -586,7 +594,7 @@ func (r *Request) Options(url string) (*Response, error) ## Patch Patch sends the PATCH request. -It sets URL and HTTP method and then it sends the request. +It sets the URL and HTTP method, and then it sends the request. ```go title="Signature" func (r *Request) Patch(url string) (*Response, error) @@ -595,7 +603,7 @@ func (r *Request) Patch(url string) (*Response, error) ## Custom Custom sends a request with custom HTTP method. -It sets URL and HTTP method and then it sends the request. +It sets the URL and HTTP method, and then it sends the request. You can use Custom to send requests with methods like TRACE, CONNECT. ```go title="Signature" @@ -969,4 +977,4 @@ Reset clear the File object. ```go title="Signature" func (f *File) Reset() -``` \ No newline at end of file +``` diff --git a/docs/client/response.md b/docs/client/response.md index ed0609bf2b..78a08e3bb6 100644 --- a/docs/client/response.md +++ b/docs/client/response.md @@ -8,7 +8,14 @@ sidebar_position: 3 # Response -Response is the result of a request. This object is used to access the response data. +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 { @@ -33,7 +40,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. +Do not access the released Response object, otherwise, data races may occur. ```go title="Signature" func ReleaseResponse(resp *Response) @@ -133,4 +140,4 @@ Close method will release Request object and Response object, after call Close p ```go title="Signature" func (r *Response) Close() -``` \ No newline at end of file +``` diff --git a/docs/whats_new.md b/docs/whats_new.md index 735dc345a3..852533e5ef 100644 --- a/docs/whats_new.md +++ b/docs/whats_new.md @@ -227,9 +227,9 @@ DRAFT section ## 🌎 Client package -The Gofiber client has been built from the scratch. It comes with lots of new features like Cookiejar, request/response hooks etc. +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 :::caution From e2f60acab65d29f71c0bb66bfc71a4ecf6339855 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9?= Date: Sun, 12 May 2024 09:51:50 +0200 Subject: [PATCH 05/14] docs: add docs for new client --- docs/client/client.md | 22 ++++++++++------------ docs/client/examples.md | 17 ++++++++++------- docs/client/hooks.md | 4 ++-- docs/client/request.md | 2 -- docs/client/response.md | 2 -- 5 files changed, 22 insertions(+), 25 deletions(-) diff --git a/docs/client/client.md b/docs/client/client.md index 70cc51c577..e22249cb0f 100644 --- a/docs/client/client.md +++ b/docs/client/client.md @@ -6,8 +6,6 @@ description: >- sidebar_position: 1 --- -# Client - The Fiber Client 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 @@ -690,12 +688,12 @@ Reset clears the Client object func (c *Client) Reset() ``` -# Default Client +## 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 C gets default client. @@ -703,7 +701,7 @@ C gets default client. func C() ``` -## Replace +### Replace Replace the defaultClient, the returned function can undo. @@ -715,7 +713,7 @@ The default client should not be changed concurrently. func Replace() ``` -## Get +### Get Get send a get request use defaultClient, a convenient method. @@ -723,7 +721,7 @@ Get send a get request use defaultClient, a convenient method. func Get(url string, cfg ...Config) (*Response, error) ``` -## Post +### Post Post send a post request use defaultClient, a convenient method. @@ -731,7 +729,7 @@ Post send a post request use defaultClient, a convenient method. func Post(url string, cfg ...Config) (*Response, error) ``` -## Head +### Head Head send a head request use defaultClient, a convenient method. @@ -739,7 +737,7 @@ Head send a head request use defaultClient, a convenient method. func Head(url string, cfg ...Config) (*Response, error) ``` -## Put +### Put Put send a put request use defaultClient, a convenient method. @@ -747,7 +745,7 @@ Put send a put request use defaultClient, a convenient method. func Put(url string, cfg ...Config) (*Response, error) ``` -## Delete +### Delete Delete send a delete request use defaultClient, a convenient method. @@ -755,7 +753,7 @@ Delete send a delete request use defaultClient, a convenient method. func Delete(url string, cfg ...Config) (*Response, error) ``` -## Options +### Options Options send a options request use defaultClient, a convenient method. @@ -763,7 +761,7 @@ Options send a options request use defaultClient, a convenient method. func Options(url string, cfg ...Config) (*Response, error) ``` -## Patch +### Patch Patch send a patch request use defaultClient, a convenient method. diff --git a/docs/client/examples.md b/docs/client/examples.md index ae291b4748..ed86f726b0 100644 --- a/docs/client/examples.md +++ b/docs/client/examples.md @@ -2,11 +2,14 @@ id: examples title: 🍳 Examples description: >- - Some useful examples about the client. + Some useful examples about the client. sidebar_position: 5 --- -# Basic Auth +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +## Basic Auth @@ -68,7 +71,7 @@ func main() { -# TLS +## TLS @@ -140,9 +143,9 @@ func main() { -# Cookiejar +## Cookiejar -## Request +### Request ```go func main() { @@ -166,7 +169,7 @@ func main() {
Click here to see the result -``` +```json { "cookies": { "john": "doe" @@ -176,7 +179,7 @@ func main() {
-## Response +### Response ```go func main() { diff --git a/docs/client/hooks.md b/docs/client/hooks.md index 8ad2eabbca..b3bf5b6d61 100644 --- a/docs/client/hooks.md +++ b/docs/client/hooks.md @@ -10,7 +10,7 @@ With hooks, you can manipulate the client on before request/after response stage There are 2 kinds of hooks: -# Request Hooks +## Request Hooks They are called before the HTTP request has been sent. You can use them make changes on Request object. @@ -119,7 +119,7 @@ exit status 2 ``` -# Response Hooks +## Response Hooks They are called after the HTTP response has been completed. You can use them to get some information about response and request. diff --git a/docs/client/request.md b/docs/client/request.md index 4b9f54cd79..e85a18d320 100644 --- a/docs/client/request.md +++ b/docs/client/request.md @@ -6,8 +6,6 @@ description: >- sidebar_position: 2 --- -# Request - The `Request` structure in Gofiber's HTTP client represents an HTTP request. It encapsulates all the necessary information required to send a request to a server. This includes: - **URL**: The URL to which the request is sent. diff --git a/docs/client/response.md b/docs/client/response.md index 78a08e3bb6..9e14432a29 100644 --- a/docs/client/response.md +++ b/docs/client/response.md @@ -6,8 +6,6 @@ description: >- sidebar_position: 3 --- -# Response - 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). From a245aa97d86d9c6e45450868a0fe27fa3308f9db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9?= Date: Sun, 12 May 2024 10:07:17 +0200 Subject: [PATCH 06/14] docs: add docs for new client --- docs/client/_category_.json | 4 ++-- docs/client/request.md | 2 +- docs/client/response.md | 2 +- docs/client/{client.md => rest.md} | 4 ++-- 4 files changed, 6 insertions(+), 6 deletions(-) rename docs/client/{client.md => rest.md} (99%) diff --git a/docs/client/_category_.json b/docs/client/_category_.json index 35fb941567..61fad7ac4e 100644 --- a/docs/client/_category_.json +++ b/docs/client/_category_.json @@ -1,8 +1,8 @@ { - "label": "\uD83D\uDCD6 Client", + "label": "\uD83C\uDF0E Client", "position": 5, "link": { "type": "generated-index", "description": "HTTP client for Fiber." } -} \ No newline at end of file +} diff --git a/docs/client/request.md b/docs/client/request.md index e85a18d320..18f286d1f1 100644 --- a/docs/client/request.md +++ b/docs/client/request.md @@ -1,6 +1,6 @@ --- id: request -title: 🌎 Request +title: 📤 Request description: >- Request methods of Gofiber HTTP client. sidebar_position: 2 diff --git a/docs/client/response.md b/docs/client/response.md index 9e14432a29..1a0329b0fb 100644 --- a/docs/client/response.md +++ b/docs/client/response.md @@ -1,6 +1,6 @@ --- id: response -title: 🌎 Response +title: 📥 Response description: >- Response methods of Gofiber HTTP client. sidebar_position: 3 diff --git a/docs/client/client.md b/docs/client/rest.md similarity index 99% rename from docs/client/client.md rename to docs/client/rest.md index e22249cb0f..fe6ab25f27 100644 --- a/docs/client/client.md +++ b/docs/client/rest.md @@ -1,6 +1,6 @@ --- -id: client -title: 🌎 Client +id: rest +title: 🖥️ REST description: >- HTTP client for Gofiber. sidebar_position: 1 From 59d782c435f13f86189642950bdf753a29a94d5d Mon Sep 17 00:00:00 2001 From: Muhammed Efe Cetin Date: Sun, 12 May 2024 22:08:00 +0300 Subject: [PATCH 07/14] Add more examples for methods --- docs/client/request.md | 405 ++++++++++++++++++++++++++++++++++++++-- docs/client/response.md | 70 ++++++- docs/client/rest.md | 205 ++++++++++++-------- 3 files changed, 584 insertions(+), 96 deletions(-) diff --git a/docs/client/request.md b/docs/client/request.md index 18f286d1f1..41535cfe14 100644 --- a/docs/client/request.md +++ b/docs/client/request.md @@ -113,7 +113,7 @@ func (r *Request) SetClient(c *Client) *Request ## Context -Context returns the Context if its already set in request. Otherwise it returns `context.Background()`. +Context returns the Context if it's already set in the request; otherwise, it returns `context.Background()`. ```go title="Signature" func (r *Request) Context() context.Context @@ -121,7 +121,7 @@ func (r *Request) Context() context.Context ## SetContext -SetContext sets the context.Context for current Request. It allows to interrupt the request execution if ctx.Done() channel is closed. +SetContext sets the context.Context for current Request. It allows interruption of the request execution if the ctx.Done() channel is closed. See https://blog.golang.org/context article and the "context" package documentation. ```go title="Signature" @@ -143,15 +143,80 @@ AddHeader method adds a single header field and its value in the request instanc func (r *Request) AddHeader(key, val string) *Request ``` +```go title="Example" +req := client.AcquireRequest() +defer client.ReleaseRequest(req) + +req.AddHeader("Golang", "Fiber") +req.AddHeader("Test", "123456") +req.AddHeader("Test", "654321") + +resp, err := req.Get("https://httpbin.org/headers") +if err != nil { + panic(err) +} + +fmt.Println(resp.String()) +``` + +
+Click here to see the result + +``` +{ + "headers": { + "Golang": "Fiber", + "Host": "httpbin.org", + "Referer": "", + "Test": "123456,654321", + "User-Agent": "fiber", + "X-Amzn-Trace-Id": "Root=1-664105d2-033cf7173457adb56d9e7193" + } +} +``` +
+ ## SetHeader SetHeader method sets a single header field and its value in the request instance. -It will override header which has been set in client instance. +It will override the header which has been set in the client instance. ```go title="Signature" func (r *Request) SetHeader(key, val string) *Request ``` +```go title="Example" +req := client.AcquireRequest() +defer client.ReleaseRequest(req) + +req.SetHeader("Test", "123456") +req.SetHeader("Test", "654321") + +resp, err := req.Get("https://httpbin.org/headers") +if err != nil { + panic(err) +} + +fmt.Println(resp.String()) +``` + +
+Click here to see the result + +``` +{ + "headers": { + "Golang": "Fiber", + "Host": "httpbin.org", + "Referer": "", + "Test": "654321", + "User-Agent": "fiber", + "X-Amzn-Trace-Id": "Root=1-664105e5-5d676ba348450cdb62847f04" + } +} +``` +
+ ## AddHeaders AddHeaders method adds multiple header fields and its values at one go in the request instance. @@ -163,7 +228,7 @@ func (r *Request) AddHeaders(h map[string][]string) *Request ## SetHeaders SetHeaders method sets multiple header fields and its values at one go in the request instance. -It will override header which has been set in client instance. +It will override the header which has been set in the client instance. ```go title="Signature" func (r *Request) SetHeaders(h map[string]string) *Request @@ -185,10 +250,42 @@ AddParam method adds a single param field and its value in the request instance. func (r *Request) AddParam(key, val string) *Request ``` +```go title="Example" +req := client.AcquireRequest() +defer client.ReleaseRequest(req) + +req.AddParam("name", "john") +req.AddParam("hobbies", "football") +req.AddParam("hobbies", "basketball") + +resp, err := req.Get("https://httpbin.org/response-headers") +if err != nil { + panic(err) +} + +fmt.Println(string(resp.Body())) +``` + +
+Click here to see the result + +``` +{ + "Content-Length": "145", + "Content-Type": "application/json", + "hobbies": [ + "football", + "basketball" + ], + "name": "efectn" +} +``` +
+ ## SetParam SetParam method sets a single param field and its value in the request instance. -It will override param which has been set in client instance. +It will override param, which has been set in client instance. ```go title="Signature" func (r *Request) SetParam(key, val string) *Request @@ -205,7 +302,7 @@ func (r *Request) AddParams(m map[string][]string) *Request ## SetParams SetParams method sets multiple param fields and its values at one go in the request instance. -It will override param which has been set in client instance. +It will override param, which has been set in client instance. ```go title="Signature" func (r *Request) SetParams(m map[string]string) *Request @@ -214,12 +311,51 @@ func (r *Request) SetParams(m map[string]string) *Request ## SetParamsWithStruct SetParamsWithStruct method sets multiple param fields and its values at one go in the request instance. -It will override param which has been set in client instance. +It will override param, which has been set in client instance. ```go title="Signature" func (r *Request) SetParamsWithStruct(v any) *Request ``` +```go title="Example" +req := client.AcquireRequest() +defer client.ReleaseRequest(req) + +req.SetParamsWithStruct(struct { + Name string `json:"name"` + Hobbies []string `json:"hobbies"` +}{ + Name: "John Doe", + Hobbies: []string{ + "Football", + "Basketball", + }, +}) + +resp, err := req.Get("https://httpbin.org/response-headers") +if err != nil { + panic(err) +} + +fmt.Println(string(resp.Body())) +``` + +
+Click here to see the result + +``` +{ + "Content-Length": "147", + "Content-Type": "application/json", + "Hobbies": [ + "Football", + "Basketball" + ], + "Name": "John Doe" +} +``` +
+ ## DelParams DelParams method deletes single or multiple param fields and their values. @@ -280,7 +416,7 @@ func (r *Request) SetReferer(referer string) *Request ## Cookie -Cookie returns the cookie be set in request instance. If the cookie doesn't exist, returns empty string. +Cookie returns the cookie set in the request instance. If the cookie doesn't exist, returns empty string. ```go title="Signature" func (r *Request) Cookie(key string) string @@ -289,7 +425,7 @@ func (r *Request) Cookie(key string) string ## SetCookie SetCookie method sets a single cookie field and its value in the request instance. -It will override cookie which set in client instance. +It will override the cookie which is set in the client instance. ```go title="Signature" func (r *Request) SetCookie(key, val string) *Request @@ -298,16 +434,45 @@ func (r *Request) SetCookie(key, val string) *Request ## SetCookies SetCookies method sets multiple cookie fields and its values at one go in the request instance. -It will override cookie which set in client instance. +It will override the cookie which is set in the client instance. ```go title="Signature" func (r *Request) SetCookies(m map[string]string) *Request ``` +```go title="Example" +req := client.AcquireRequest() +defer client.ReleaseRequest(req) + +req.SetCookies(map[string]string{ + "cookie1": "value1", + "cookie2": "value2", +}) + +resp, err := req.Get("https://httpbin.org/cookies") +if err != nil { + panic(err) +} + +fmt.Println(string(resp.Body())) +``` + +
+Click here to see the result + +``` +{ + "cookies": { + "test": "123" + } +} +``` +
+ ## SetCookiesWithStruct SetCookiesWithStruct method sets multiple cookie fields and its values at one go in the request instance. -It will override cookie which set in client instance. +It will override the cookie which is set in the client instance. ```go title="Signature" func (r *Request) SetCookiesWithStruct(v any) *Request @@ -323,7 +488,7 @@ func (r *Request) DelCookies(key ...string) *Request ## PathParam -PathParam returns the path param be set in request instance. If the path param doesn't exist, return empty string. +PathParam returns the path param set in the request instance. If the path param doesn't exist, return empty string. ```go title="Signature" func (r *Request) PathParam(key string) string @@ -338,6 +503,28 @@ It will override path param which set in client instance. func (r *Request) SetPathParam(key, val string) *Request ``` +```go title="Example" +req := client.AcquireRequest() +defer client.ReleaseRequest(req) + +req.SetPathParam("base64", "R29maWJlcg==") + +resp, err := req.Get("https://httpbin.org/base64/:base64") +if err != nil { + panic(err) +} + +fmt.Println(string(resp.Body())) +``` + +
+Click here to see the result + +``` +Gofiber +``` +
+ ## SetPathParams SetPathParams method sets multiple path param fields and its values at one go in the request instance. @@ -412,6 +599,42 @@ AddFormData method adds a single form data field and its value in the request in func (r *Request) AddFormData(key, val string) *Request ``` +```go title="Example" +req := client.AcquireRequest() +defer client.ReleaseRequest(req) + +req.AddFormData("points", "80") +req.AddFormData("points", "90") +req.AddFormData("points", "100") + +resp, err := req.Post("https://httpbin.org/post") +if err != nil { + panic(err) +} + +fmt.Println(string(resp.Body())) +``` + +
+Click here to see the result + +``` +{ + "args": {}, + "data": "", + "files": {}, + "form": { + "points": [ + "80", + "90", + "100" + ] + }, + ... +} +``` +
+ ## SetFormData SetFormData method sets a single form data field and its value in the request instance. @@ -420,6 +643,38 @@ SetFormData method sets a single form data field and its value in the request in func (r *Request) SetFormData(key, val string) *Request ``` +```go title="Example" +req := client.AcquireRequest() +defer client.ReleaseRequest(req) + +req.SetFormData("name", "john") +req.SetFormData("email", "john@doe.com") + +resp, err := req.Post("https://httpbin.org/post") +if err != nil { + panic(err) +} + +fmt.Println(string(resp.Body())) +``` + +
+Click here to see the result + +``` +{ + "args": {}, + "data": "", + "files": {}, + "form": { + "email": "john@doe.com", + "name": "john" + }, + ... +} +``` +
+ ## AddFormDatas AddFormDatas method adds multiple form data fields and its values in the request instance. @@ -479,20 +734,81 @@ func (r *Request) FileByPath(path string) *File ## AddFile -AddFile method adds single file field and its value in the request instance via file path. +AddFile method adds a single file field and its value in the request instance via file path. ```go title="Signature" func (r *Request) AddFile(path string) *Request ``` +```go title="Example" +req := client.AcquireRequest() +defer client.ReleaseRequest(req) + +req.AddFile("test.txt") + +resp, err := req.Post("https://httpbin.org/post") +if err != nil { + panic(err) +} + +fmt.Println(string(resp.Body())) +``` + +
+Click here to see the result + +``` +{ + "args": {}, + "data": "", + "files": { + "file1": "This is an empty file!\n" + }, + "form": {}, + ... +} +``` +
+ ## AddFileWithReader -AddFileWithReader method adds single field and its value in the request instance via reader. +AddFileWithReader method adds a single field and its value in the request instance via reader. ```go title="Signature" func (r *Request) AddFileWithReader(name string, reader io.ReadCloser) *Request ``` +```go title="Example" +req := client.AcquireRequest() +defer client.ReleaseRequest(req) + +buf := bytes.NewBuffer([]byte("Hello, World!")) +req.AddFileWithReader("test.txt", io.NopCloser(buf)) + +resp, err := req.Post("https://httpbin.org/post") +if err != nil { + panic(err) +} + +fmt.Println(string(resp.Body())) +``` + +
+Click here to see the result + +``` +{ + "args": {}, + "data": "", + "files": { + "file1": "Hello, World!" + }, + "form": {}, + ... +} +``` +
+ ## AddFiles AddFiles method adds multiple file fields and its value in the request instance via File instance. @@ -511,16 +827,71 @@ func (r *Request) Timeout() time.Duration ## SetTimeout -SetTimeout method sets timeout field and its values at one go in the request instance. +SetTimeout method sets the timeout field and its values at one go in the request instance. It will override timeout which set in client instance. ```go title="Signature" func (r *Request) SetTimeout(t time.Duration) *Request ``` +```go title="Example 1" +req := client.AcquireRequest() +defer client.ReleaseRequest(req) + +req.SetTimeout(5 * time.Second) + +resp, err := req.Get("https://httpbin.org/delay/4") +if err != nil { + panic(err) +} + +fmt.Println(string(resp.Body())) +``` + +
+Click here to see the result + +``` +{ + "args": {}, + "data": "", + "files": {}, + "form": {}, + ... +} +``` +
+ +```go title="Example 2" +req := client.AcquireRequest() +defer client.ReleaseRequest(req) + +req.SetTimeout(5 * time.Second) + +resp, err := req.Get("https://httpbin.org/delay/6") +if err != nil { + panic(err) +} + +fmt.Println(string(resp.Body())) +``` + +
+Click here to see the result + +``` +panic: timeout or cancel + +goroutine 1 [running]: +main.main() + main.go:18 +0xeb +exit status 2 +``` +
+ ## MaxRedirects -MaxRedirects returns the max redirects count in request. +MaxRedirects returns the max redirects count in the request. ```go title="Signature" func (r *Request) MaxRedirects() int @@ -529,7 +900,7 @@ func (r *Request) MaxRedirects() int ## SetMaxRedirects SetMaxRedirects method sets the maximum number of redirects at one go in the request instance. -It will override max redirect which set in client instance. +It will override max redirect, which is set in the client instance. ```go title="Signature" func (r *Request) SetMaxRedirects(count int) *Request diff --git a/docs/client/response.md b/docs/client/response.md index 1a0329b0fb..240bea919f 100644 --- a/docs/client/response.md +++ b/docs/client/response.md @@ -38,7 +38,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. +Do not access the released Response object; otherwise, data races may occur. ```go title="Signature" func ReleaseResponse(resp *Response) @@ -68,6 +68,23 @@ Protocol method returns the HTTP response protocol used for the request. 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()) +``` + +
+Click here to see the result + +``` +HTTP/1.1 +``` +
+ ## Header Header method returns the response headers. @@ -84,6 +101,26 @@ Cookies method to access all the response cookies. 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())) +} +``` + +
+Click here to see the result + +``` +go => fiber +``` +
+ ## Body Body method returns HTTP response as []byte array for the executed request. @@ -108,6 +145,37 @@ JSON method will unmarshal body to json. 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) +``` + +
+Click here to see the result + +``` +{Slideshow:{Author:Yours Truly Date:date of publication Title:Sample Slide Show}} +``` +
+ ## XML XML method will unmarshal body to xml. diff --git a/docs/client/rest.md b/docs/client/rest.md index fe6ab25f27..60b9e373ee 100644 --- a/docs/client/rest.md +++ b/docs/client/rest.md @@ -8,13 +8,13 @@ sidebar_position: 1 The Fiber Client 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 +# 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 +# Usage To use the Fiber Client, instantiate it with the desired configuration. Here's a simple example: ```go @@ -92,7 +92,7 @@ type Client struct { } ``` -## New + New New creates and returns a new Client object. @@ -100,7 +100,73 @@ New creates and returns a new Client object. func New() *Client ``` -## Request Config +# 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) +``` + +## Head + +Head provides an API like axios which send head request. + +```go title="Signature" +func (c *Client) Head(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) +``` + +## Delete + +Delete provides an API like axios which send delete request. + +```go title="Signature" +func (c *Client) Delete(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) +``` + +## Patch + +Patch provides an API like axios which send patch request. + +```go title="Signature" +func (c *Client) Patch(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. @@ -312,6 +378,29 @@ SetBaseURL Set baseUrl which is prefix of real url. 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())) +``` + +
+Click here to see the result + +``` +{ + "args": {}, + ... +} +``` +
+ ## Header Header method returns header value via key, this method will visit all field in the header @@ -512,6 +601,30 @@ Also it can be overridden at request level cookie options. 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())) +``` + +
+Click here to see the result + +``` +{ + "cookies": { + "john": "doe" + } +} +``` +
+ ## SetCookies SetCookies method sets multiple cookies field and its values at one go in the client instance. @@ -592,70 +705,6 @@ SetCookieJar sets cookie jar in client instance. func (c *Client) SetCookieJar(cookieJar *CookieJar) *Client ``` -## 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) -``` - -## Head - -Head provides an API like axios which send head request. - -```go title="Signature" -func (c *Client) Head(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) -``` - -## Delete - -Delete provides an API like axios which send delete request. - -```go title="Signature" -func (c *Client) Delete(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) -``` - -## Patch - -Patch provides an API like axios which send patch request. - -```go title="Signature" -func (c *Client) Patch(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) -``` - ## SetDial SetDial sets dial function in client. @@ -688,12 +737,12 @@ Reset clears the Client object func (c *Client) Reset() ``` -## Default Client +# 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 C gets default client. @@ -701,7 +750,7 @@ C gets default client. func C() ``` -### Replace +## Replace Replace the defaultClient, the returned function can undo. @@ -713,7 +762,7 @@ The default client should not be changed concurrently. func Replace() ``` -### Get +## Get Get send a get request use defaultClient, a convenient method. @@ -721,7 +770,7 @@ Get send a get request use defaultClient, a convenient method. func Get(url string, cfg ...Config) (*Response, error) ``` -### Post +## Post Post send a post request use defaultClient, a convenient method. @@ -729,7 +778,7 @@ Post send a post request use defaultClient, a convenient method. func Post(url string, cfg ...Config) (*Response, error) ``` -### Head +## Head Head send a head request use defaultClient, a convenient method. @@ -737,7 +786,7 @@ Head send a head request use defaultClient, a convenient method. func Head(url string, cfg ...Config) (*Response, error) ``` -### Put +## Put Put send a put request use defaultClient, a convenient method. @@ -745,7 +794,7 @@ Put send a put request use defaultClient, a convenient method. func Put(url string, cfg ...Config) (*Response, error) ``` -### Delete +## Delete Delete send a delete request use defaultClient, a convenient method. @@ -753,7 +802,7 @@ Delete send a delete request use defaultClient, a convenient method. func Delete(url string, cfg ...Config) (*Response, error) ``` -### Options +## Options Options send a options request use defaultClient, a convenient method. @@ -761,7 +810,7 @@ Options send a options request use defaultClient, a convenient method. func Options(url string, cfg ...Config) (*Response, error) ``` -### Patch +## Patch Patch send a patch request use defaultClient, a convenient method. From 918c669c7734d4bb4904dd14fc9c3c4e756df1a9 Mon Sep 17 00:00:00 2001 From: RW Date: Mon, 13 May 2024 08:21:00 +0200 Subject: [PATCH 08/14] Update docs/client/examples.md Co-authored-by: Jason McNeil --- docs/client/examples.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/client/examples.md b/docs/client/examples.md index ed86f726b0..0a8c59dfdb 100644 --- a/docs/client/examples.md +++ b/docs/client/examples.md @@ -2,7 +2,7 @@ id: examples title: 🍳 Examples description: >- - Some useful examples about the client. +Client usage examples. sidebar_position: 5 --- From dc7d3d949698207b570e872d9c419ee33c7f6419 Mon Sep 17 00:00:00 2001 From: Muhammed Efe Cetin Date: Mon, 13 May 2024 14:33:38 +0300 Subject: [PATCH 09/14] Add one more example for cookiejar --- docs/client/examples.md | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/docs/client/examples.md b/docs/client/examples.md index 0a8c59dfdb..4c476d44b1 100644 --- a/docs/client/examples.md +++ b/docs/client/examples.md @@ -210,3 +210,39 @@ func main() { [john=doe; path=/] ``` + +### 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()) +} +``` + +
+Click here to see the result + +``` +{ + "cookies": { + "john": "doe" + } +} +``` +
From 92efa573fc69f6007922188b7fd3108acdc73ee1 Mon Sep 17 00:00:00 2001 From: Muhammed Efe Cetin Date: Mon, 13 May 2024 14:43:25 +0300 Subject: [PATCH 10/14] apply review --- docs/client/examples.md | 1 - docs/client/request.md | 22 ++--- docs/client/response.md | 2 +- docs/client/rest.md | 172 ++++++++++++++++++++-------------------- 4 files changed, 98 insertions(+), 99 deletions(-) diff --git a/docs/client/examples.md b/docs/client/examples.md index 4c476d44b1..b2324b6268 100644 --- a/docs/client/examples.md +++ b/docs/client/examples.md @@ -178,7 +178,6 @@ func main() { ``` - ### Response ```go diff --git a/docs/client/request.md b/docs/client/request.md index 41535cfe14..4c8c7d38e7 100644 --- a/docs/client/request.md +++ b/docs/client/request.md @@ -122,7 +122,7 @@ func (r *Request) Context() context.Context ## SetContext SetContext sets the context.Context for current Request. It allows interruption of the request execution if the ctx.Done() channel is closed. -See https://blog.golang.org/context article and the "context" package documentation. +See [the article](https://blog.golang.org/context) and the [context](https://pkg.go.dev/context) package documentation. ```go title="Signature" func (r *Request) SetContext(ctx context.Context) *Request @@ -375,7 +375,7 @@ func (r *Request) UserAgent() string ## SetUserAgent SetUserAgent method sets user agent in request. -It will override user agent which has been set in client instance. +It will override the user agent which has been set in the client instance. ```go title="Signature" func (r *Request) SetUserAgent(ua string) *Request @@ -908,7 +908,7 @@ func (r *Request) SetMaxRedirects(count int) *Request ## Get -Get sends the GET request. +Get sends the GET request. It sets the URL and HTTP method, and then it sends the request. ```go title="Signature" @@ -917,7 +917,7 @@ func (r *Request) Get(url string) (*Response, error) ## Post -Post sends the POST request. +Post sends the POST request. It sets the URL and HTTP method, and then it sends the request. ```go title="Signature" @@ -926,7 +926,7 @@ func (r *Request) Post(url string) (*Response, error) ## Head -Head sends the HEAD request. +Head sends the HEAD request. It sets the URL and HTTP method, and then it sends the request. ```go title="Signature" @@ -935,7 +935,7 @@ func (r *Request) Head(url string) (*Response, error) ## Put -Put sends the PUT request. +Put sends the PUT request. It sets the URL and HTTP method, and then it sends the request. ```go title="Signature" @@ -944,7 +944,7 @@ func (r *Request) Put(url string) (*Response, error) ## Delete -Delete sends the DELETE request. +Delete sends the DELETE request. It sets the URL and HTTP method, and then it sends the request. ```go title="Signature" @@ -953,7 +953,7 @@ func (r *Request) Delete(url string) (*Response, error) ## Options -Options sends the OPTIONS request. +Options sends the OPTIONS request. It sets the URL and HTTP method, and then it sends the request. ```go title="Signature" @@ -962,7 +962,7 @@ func (r *Request) Options(url string) (*Response, error) ## Patch -Patch sends the PATCH request. +Patch sends the PATCH request. It sets the URL and HTTP method, and then it sends the request. ```go title="Signature" @@ -971,7 +971,7 @@ func (r *Request) Patch(url string) (*Response, error) ## Custom -Custom sends a request with custom HTTP method. +Custom sends a request with custom HTTP method. It sets the URL and HTTP method, and then it sends the request. You can use Custom to send requests with methods like TRACE, CONNECT. @@ -1334,7 +1334,7 @@ func (f *File) SetPath(p string) ## SetReader -SetReader method can receive a io.ReadCloser which will be closed in parserBody hook. +SetReader method can receive an io.ReadCloser which will be closed in parserBody hook. ```go title="Signature" func (f *File) SetReader(r io.ReadCloser) diff --git a/docs/client/response.md b/docs/client/response.md index 240bea919f..7c7f874a67 100644 --- a/docs/client/response.md +++ b/docs/client/response.md @@ -202,7 +202,7 @@ func (r *Response) Reset() ## Close -Close method will release Request object and Response object, after call Close please don't use these object. +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() diff --git a/docs/client/rest.md b/docs/client/rest.md index 60b9e373ee..5b13b2ea97 100644 --- a/docs/client/rest.md +++ b/docs/client/rest.md @@ -8,13 +8,13 @@ sidebar_position: 1 The Fiber Client 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 +## 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 +## Usage To use the Fiber Client, instantiate it with the desired configuration. Here's a simple example: ```go @@ -100,9 +100,9 @@ New creates and returns a new Client object. func New() *Client ``` -# REST Methods +## REST Methods -## Get +### Get Get provides an API like axios which sends a get request. @@ -110,7 +110,7 @@ Get provides an API like axios which sends a get request. func (c *Client) Get(url string, cfg ...Config) (*Response, error) ``` -## Post +### Post Post provides an API like axios which send post request. @@ -118,7 +118,7 @@ Post provides an API like axios which send post request. func (c *Client) Post(url string, cfg ...Config) (*Response, error) ``` -## Head +### Head Head provides an API like axios which send head request. @@ -126,7 +126,7 @@ Head provides an API like axios which send head request. func (c *Client) Head(url string, cfg ...Config) (*Response, error) ``` -## Put +### Put Put provides an API like axios which send put request. @@ -134,7 +134,7 @@ Put provides an API like axios which send put request. func (c *Client) Put(url string, cfg ...Config) (*Response, error) ``` -## Delete +### Delete Delete provides an API like axios which send delete request. @@ -142,7 +142,7 @@ Delete provides an API like axios which send delete request. func (c *Client) Delete(url string, cfg ...Config) (*Response, error) ``` -## Options +### Options Options provides an API like axios which send options request. @@ -150,7 +150,7 @@ Options provides an API like axios which send options request. func (c *Client) Options(url string, cfg ...Config) (*Response, error) ``` -## Patch +### Patch Patch provides an API like axios which send patch request. @@ -158,7 +158,7 @@ Patch provides an API like axios which send patch request. func (c *Client) Patch(url string, cfg ...Config) (*Response, error) ``` -## Custom +### Custom Custom provides an API like axios which send custom request. @@ -166,7 +166,7 @@ Custom provides an API like axios which send custom request. func (c *Client) Custom(url, method string, cfg ...Config) (*Response, error) ``` -# Request Configuration +## 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. @@ -192,7 +192,7 @@ 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. @@ -201,7 +201,7 @@ It acquires a request from the pool. You have to release it using `ReleaseReques func (c *Client) R() *Request ``` -## RequestHook +### RequestHook RequestHook Request returns user-defined request hooks. @@ -209,7 +209,7 @@ RequestHook Request returns user-defined request hooks. func (c *Client) RequestHook() []RequestHook ``` -## AddRequestHook +### AddRequestHook AddRequestHook Add user-defined request hooks. @@ -217,7 +217,7 @@ AddRequestHook Add user-defined request hooks. func (c *Client) AddRequestHook(h ...RequestHook) *Client ``` -## ResponseHook +### ResponseHook ResponseHook return user-define response hooks. @@ -225,7 +225,7 @@ ResponseHook return user-define response hooks. func (c *Client) ResponseHook() []ResponseHook ``` -## AddResponseHook +### AddResponseHook AddResponseHook Add user-defined response hooks. @@ -233,7 +233,7 @@ AddResponseHook Add user-defined response hooks. func (c *Client) AddResponseHook(h ...ResponseHook) *Client ``` -## JSONMarshal +### JSONMarshal JSONMarshal returns json marshal function in Core. @@ -241,7 +241,7 @@ JSONMarshal returns json marshal function in Core. func (c *Client) JSONMarshal() utils.JSONMarshal ``` -## SetJSONMarshal +### SetJSONMarshal SetJSONMarshal sets the JSON encoder. @@ -249,7 +249,7 @@ SetJSONMarshal sets the JSON encoder. func (c *Client) SetJSONMarshal(f utils.JSONMarshal) *Client ``` -## JSONUnmarshal +### JSONUnmarshal JSONUnmarshal returns json unmarshal function in Core. @@ -257,7 +257,7 @@ JSONUnmarshal returns json unmarshal function in Core. func (c *Client) JSONUnmarshal() utils.JSONUnmarshal ``` -## SetJSONUnmarshal +### SetJSONUnmarshal Set the JSON decoder. @@ -265,7 +265,7 @@ Set the JSON decoder. func (c *Client) SetJSONUnmarshal(f utils.JSONUnmarshal) *Client ``` -## XMLMarshal +### XMLMarshal XMLMarshal returns xml marshal function in Core. @@ -273,7 +273,7 @@ XMLMarshal returns xml marshal function in Core. func (c *Client) XMLMarshal() utils.XMLMarshal ``` -## SetXMLMarshal +### SetXMLMarshal SetXMLMarshal sets the XML encoder. @@ -281,7 +281,7 @@ SetXMLMarshal sets the XML encoder. func (c *Client) SetXMLMarshal(f utils.XMLMarshal) *Client ``` -## XMLUnmarshal +### XMLUnmarshal XMLUnmarshal returns xml unmarshal function in Core. @@ -289,7 +289,7 @@ XMLUnmarshal returns xml unmarshal function in Core. func (c *Client) XMLUnmarshal() utils.XMLUnmarshal ``` -## SetXMLUnmarshal +### SetXMLUnmarshal SetXMLUnmarshal sets the XML decoder. @@ -297,7 +297,7 @@ SetXMLUnmarshal sets the XML decoder. func (c *Client) SetXMLUnmarshal(f utils.XMLUnmarshal) *Client ``` -## TLSConfig +### TLSConfig TLSConfig returns tlsConfig in client. If the client doesn't have a tlsConfig, this function will initialize it. @@ -306,7 +306,7 @@ If the client doesn't have a tlsConfig, this function will initialize it. func (c *Client) TLSConfig() *tls.Config ``` -## SetTLSConfig +### SetTLSConfig SetTLSConfig sets tlsConfig in client. @@ -314,7 +314,7 @@ SetTLSConfig sets tlsConfig in client. func (c *Client) SetTLSConfig(config *tls.Config) *Client ``` -## SetCertificates +### SetCertificates SetCertificates method sets client certificates into client. @@ -322,7 +322,7 @@ SetCertificates method sets client certificates into client. func (c *Client) SetCertificates(certs ...tls.Certificate) *Client ``` -## SetRootCertificate +### SetRootCertificate SetRootCertificate adds one or more root certificates into client. @@ -330,7 +330,7 @@ SetRootCertificate adds one or more root certificates into client. func (c *Client) SetRootCertificate(path string) *Client ``` -## SetRootCertificateFromString +### SetRootCertificateFromString SetRootCertificateFromString method adds one or more root certificates into client. @@ -338,7 +338,7 @@ SetRootCertificateFromString method adds one or more root certificates into clie func (c *Client) SetRootCertificateFromString(pem string) *Client ``` -## SetProxyURL +### SetProxyURL SetProxyURL sets proxy url in client. It will apply via core to hostclient. @@ -346,7 +346,7 @@ SetProxyURL sets proxy url in client. It will apply via core to hostclient. func (c *Client) SetProxyURL(proxyURL string) error ``` -## RetryConfig +### RetryConfig RetryConfig returns retry config in client. @@ -354,7 +354,7 @@ RetryConfig returns retry config in client. func (c *Client) RetryConfig() *RetryConfig ``` -## SetRetryConfig +### SetRetryConfig SetRetryConfig sets retry config in client which is impl by addon/retry package. @@ -362,7 +362,7 @@ SetRetryConfig sets retry config in client which is impl by addon/retry package. func (c *Client) SetRetryConfig(config *RetryConfig) *Client ``` -## BaseURL +### BaseURL BaseURL returns baseurl in Client instance. @@ -370,7 +370,7 @@ BaseURL returns baseurl in Client instance. func (c *Client) BaseURL() string ``` -## SetBaseURL +### SetBaseURL SetBaseURL Set baseUrl which is prefix of real url. @@ -401,7 +401,7 @@ fmt.Println(string(resp.Body())) ``` -## Header +### Header Header method returns header value via key, this method will visit all field in the header @@ -409,7 +409,7 @@ Header method returns header value via key, this method will visit all field in 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. @@ -419,7 +419,7 @@ Also, it can be overridden at request level header options. 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. @@ -429,7 +429,7 @@ Also, it can be overridden at request level header options. 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. @@ -439,7 +439,7 @@ Also it can be overridden at request level headers options. 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. @@ -449,7 +449,7 @@ Also it can be overridden at request level headers options. func (c *Client) SetHeaders(h map[string]string) *Client ``` -## Param +### Param Param method returns params value via key, this method will visit all field in the query param. @@ -457,7 +457,7 @@ Param method returns params value via key, this method will visit all field in t 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. @@ -467,7 +467,7 @@ Also, it can be overridden at request level param options. 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. @@ -477,7 +477,7 @@ Also, it can be overridden at request level param options. 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. @@ -487,7 +487,7 @@ Also it can be overridden at request level params options. 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. @@ -497,7 +497,7 @@ Also it can be overridden at request level params options. 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. @@ -507,7 +507,7 @@ Also it can be overridden at request level params options. func (c *Client) SetParamsWithStruct(v any) *Client ``` -## DelParams +### DelParams DelParams method deletes single or multiple params field and its values in client. @@ -515,7 +515,7 @@ DelParams method deletes single or multiple params field and its values in clien func (c *Client) DelParams(key ...string) *Client ``` -## SetUserAgent +### SetUserAgent SetUserAgent method sets userAgent field and its value in the client instance. This ua will be applied to all requests raised from this client instance. @@ -525,7 +525,7 @@ Also it can be overridden at request level ua options. func (c *Client) SetUserAgent(ua string) *Client ``` -## SetReferer +### 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. @@ -535,7 +535,7 @@ Also it can be overridden at request level referer options. func (c *Client) SetReferer(r string) *Client ``` -## PathParam +### PathParam PathParam returns the path param be set in request instance. If the path param doesn't exist, return empty string. @@ -544,7 +544,7 @@ If the path param doesn't exist, return empty string. 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. @@ -554,7 +554,7 @@ Also it can be overridden at request level path params options. 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. @@ -564,7 +564,7 @@ Also it can be overridden at request level path params options. 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. @@ -574,7 +574,7 @@ Also it can be overridden at request level path params options. func (c *Client) SetPathParamsWithStruct(v any) *Client ``` -## DelPathParams +### DelPathParams DelPathParams method deletes single or multiple path params field and its values in client. @@ -582,7 +582,7 @@ DelPathParams method deletes single or multiple path params field and its values func (c *Client) DelPathParams(key ...string) *Client ``` -## Cookie +### Cookie Cookie returns the cookie be set in request instance. If cookie doesn't exist, return empty string. @@ -591,7 +591,7 @@ If cookie doesn't exist, return empty string. 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. @@ -625,7 +625,7 @@ 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. @@ -635,7 +635,7 @@ Also it can be overridden at request level cookie options. 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. @@ -645,7 +645,7 @@ Also it can be overridden at request level cookies options. func (c *Client) SetCookiesWithStruct(v any) *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. @@ -655,7 +655,7 @@ Also it can be overridden at request level cookies options. func (c *Client) SetCookiesWithStruct(v any) *Client ``` -## DelCookies +### DelCookies DelCookies method deletes single or multiple cookies field and its values in client. @@ -663,7 +663,7 @@ DelCookies method deletes single or multiple cookies field and its values in cli func (c *Client) DelCookies(key ...string) *Client ``` -## SetTimeout +### SetTimeout SetTimeout method sets timeout val in client instance. This value will be applied to all requests raised from this client instance. @@ -673,7 +673,7 @@ Also, it can be overridden at request level timeout options. func (c *Client) SetTimeout(t time.Duration) *Client ``` -## Debug +### Debug Debug enable log debug level output. @@ -681,7 +681,7 @@ Debug enable log debug level output. func (c *Client) Debug() *Client ``` -## DisableDebug +### DisableDebug DisableDebug disables log debug level output. @@ -689,7 +689,7 @@ DisableDebug disables log debug level output. func (c *Client) DisableDebug() *Client ``` -## SetCookieJar +### SetCookieJar DisableDebug disables log debug level output. @@ -697,7 +697,7 @@ DisableDebug disables log debug level output. func (c *Client) SetCookieJar(cookieJar *CookieJar) *Client ``` -## SetCookieJar +### SetCookieJar SetCookieJar sets cookie jar in client instance. @@ -705,7 +705,7 @@ SetCookieJar sets cookie jar in client instance. func (c *Client) SetCookieJar(cookieJar *CookieJar) *Client ``` -## SetDial +### SetDial SetDial sets dial function in client. @@ -713,7 +713,7 @@ SetDial sets dial function in client. func (c *Client) SetDial(dial fasthttp.DialFunc) *Client ``` -## SetLogger +### SetLogger SetLogger sets logger instance in client. @@ -721,7 +721,7 @@ SetLogger sets logger instance in client. func (c *Client) SetLogger(logger log.CommonLogger) *Client ``` -## Logger +### Logger Logger returns logger instance of client. @@ -729,7 +729,7 @@ Logger returns logger instance of client. func (c *Client) Logger() log.CommonLogger ``` -## Reset +### Reset Reset clears the Client object @@ -737,12 +737,12 @@ Reset clears the Client object func (c *Client) Reset() ``` -# Default Client +## 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 C gets default client. @@ -750,7 +750,7 @@ C gets default client. func C() ``` -## Replace +### Replace Replace the defaultClient, the returned function can undo. @@ -762,57 +762,57 @@ The default client should not be changed concurrently. func Replace() ``` -## Get +### Get -Get send a get request use defaultClient, a convenient method. +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 -Post send a post request use defaultClient, a convenient method. +Post is a convenience method that sends a POST request using the `defaultClient`. ```go title="Signature" func Post(url string, cfg ...Config) (*Response, error) ``` -## Head +### Head -Head send a head request use defaultClient, a convenient method. +Head sends a HEAD request using the `defaultClient`, a convenience method. ```go title="Signature" func Head(url string, cfg ...Config) (*Response, error) ``` -## Put +### Put -Put send a put request use defaultClient, a convenient method. +Put is a convenience method that sends a PUT request using the `defaultClient`. ```go title="Signature" func Put(url string, cfg ...Config) (*Response, error) ``` -## Delete +### Delete -Delete send a delete request use defaultClient, a convenient method. +Delete is a convenience method that sends a DELETE request using the `defaultClient`. ```go title="Signature" func Delete(url string, cfg ...Config) (*Response, error) ``` -## Options +### Options -Options send a options request use defaultClient, a convenient method. +Options is a convenience method that sends an OPTIONS request using the `defaultClient`. ```go title="Signature" func Options(url string, cfg ...Config) (*Response, error) ``` -## Patch +### Patch -Patch send a patch request use defaultClient, a convenient method. +Patch is a convenience method that sends a PATCH request using the `defaultClient`. ```go title="Signature" func Patch(url string, cfg ...Config) (*Response, error) From 9a17e42acd9e2c117d1d0aaab918ea41d8f19dd1 Mon Sep 17 00:00:00 2001 From: Muhammed Efe Cetin Date: Mon, 13 May 2024 14:54:34 +0300 Subject: [PATCH 11/14] apply review --- docs/client/examples.md | 7 +++++-- docs/client/hooks.md | 15 +++++++++----- docs/client/request.md | 46 ++++++++++++++++++++++++++--------------- docs/client/response.md | 3 +++ docs/client/rest.md | 8 +++---- 5 files changed, 51 insertions(+), 28 deletions(-) diff --git a/docs/client/examples.md b/docs/client/examples.md index b2324b6268..d5f8190cde 100644 --- a/docs/client/examples.md +++ b/docs/client/examples.md @@ -176,6 +176,7 @@ func main() { } } ``` + ### Response @@ -205,9 +206,10 @@ func main() {
Click here to see the result -``` +```plaintext [john=doe; path=/] ``` +
### Response 2 @@ -237,11 +239,12 @@ func main() {
Click here to see the result -``` +```json { "cookies": { "john": "doe" } } ``` +
diff --git a/docs/client/hooks.md b/docs/client/hooks.md index b3bf5b6d61..3ae510f354 100644 --- a/docs/client/hooks.md +++ b/docs/client/hooks.md @@ -61,7 +61,7 @@ func main() {
Click here to see the result -``` +```plaintext Status code: 200 Repository: gofiber/fiber Description: ⚡️ Express inspired web framework written in Go @@ -70,6 +70,7 @@ Owner: gofiber Name: fiber Full Name: gofiber/fiber ``` +
There are also some builtin request hooks provide some functionalities for Fiber client. Here is a list of them: @@ -108,7 +109,7 @@ func main() {
Click here to see the result -``` +```shell Hook 1. panic: error @@ -117,6 +118,7 @@ main.main() main.go:25 +0xaa exit status 2 ``` +
## Response Hooks @@ -151,7 +153,7 @@ func main() {
Click here to see the result -``` +```plaintext Response Status Code: 200 HTTP protocol: HTTP/1.1 @@ -168,6 +170,7 @@ Last-Modified: Thu, 17 Oct 2019 07:18:26 GMT Vary: Accept-Encoding X-Cache: HIT ``` +
There are also some builtin request hooks provide some functionalities for Fiber client. Here is a list of them: @@ -209,7 +212,7 @@ func main() {
Click here to see the result -``` +```shell Hook 1 Hook 2 panic: error @@ -219,6 +222,7 @@ main.main() main.go:30 +0xd6 exit status 2 ``` +
:::info @@ -249,8 +253,9 @@ func main() {
Click here to see the result -``` +```plaintext Hook 1 Hook 2 ``` +
diff --git a/docs/client/request.md b/docs/client/request.md index 4c8c7d38e7..02b662718a 100644 --- a/docs/client/request.md +++ b/docs/client/request.md @@ -162,7 +162,7 @@ fmt.Println(resp.String())
Click here to see the result -``` +```json { "headers": { "Golang": "Fiber", @@ -174,6 +174,7 @@ fmt.Println(resp.String()) } } ``` +
## SetHeader @@ -203,7 +204,7 @@ fmt.Println(resp.String())
Click here to see the result -``` +```json { "headers": { "Golang": "Fiber", @@ -215,6 +216,7 @@ fmt.Println(resp.String()) } } ``` +
## AddHeaders @@ -269,7 +271,7 @@ fmt.Println(string(resp.Body()))
Click here to see the result -``` +```json { "Content-Length": "145", "Content-Type": "application/json", @@ -280,6 +282,7 @@ fmt.Println(string(resp.Body())) "name": "efectn" } ``` +
## SetParam @@ -343,7 +346,7 @@ fmt.Println(string(resp.Body()))
Click here to see the result -``` +```json { "Content-Length": "147", "Content-Type": "application/json", @@ -354,6 +357,7 @@ fmt.Println(string(resp.Body())) "Name": "John Doe" } ``` +
## DelParams @@ -460,13 +464,14 @@ fmt.Println(string(resp.Body()))
Click here to see the result -``` +```json { "cookies": { "test": "123" } } ``` +
## SetCookiesWithStruct @@ -520,9 +525,10 @@ fmt.Println(string(resp.Body()))
Click here to see the result -``` +```plaintext Gofiber ``` +
## SetPathParams @@ -618,7 +624,7 @@ fmt.Println(string(resp.Body()))
Click here to see the result -``` +```json { "args": {}, "data": "", @@ -630,9 +636,10 @@ fmt.Println(string(resp.Body())) "100" ] }, - ... + // ... } ``` +
## SetFormData @@ -661,7 +668,7 @@ fmt.Println(string(resp.Body()))
Click here to see the result -``` +```json { "args": {}, "data": "", @@ -670,9 +677,10 @@ fmt.Println(string(resp.Body())) "email": "john@doe.com", "name": "john" }, - ... + // ... } ``` +
## AddFormDatas @@ -757,7 +765,7 @@ fmt.Println(string(resp.Body()))
Click here to see the result -``` +```json { "args": {}, "data": "", @@ -765,9 +773,10 @@ fmt.Println(string(resp.Body())) "file1": "This is an empty file!\n" }, "form": {}, - ... + // ... } ``` +
## AddFileWithReader @@ -796,7 +805,7 @@ fmt.Println(string(resp.Body()))
Click here to see the result -``` +```json { "args": {}, "data": "", @@ -804,9 +813,10 @@ fmt.Println(string(resp.Body())) "file1": "Hello, World!" }, "form": {}, - ... + // ... } ``` +
## AddFiles @@ -851,15 +861,16 @@ fmt.Println(string(resp.Body()))
Click here to see the result -``` +```json { "args": {}, "data": "", "files": {}, "form": {}, - ... + // ... } ``` +
```go title="Example 2" @@ -879,7 +890,7 @@ fmt.Println(string(resp.Body()))
Click here to see the result -``` +```shell panic: timeout or cancel goroutine 1 [running]: @@ -887,6 +898,7 @@ main.main() main.go:18 +0xeb exit status 2 ``` +
## MaxRedirects diff --git a/docs/client/response.md b/docs/client/response.md index 7c7f874a67..85ea79c483 100644 --- a/docs/client/response.md +++ b/docs/client/response.md @@ -83,6 +83,7 @@ fmt.Println(resp.Protocol()) ``` HTTP/1.1 ``` + ## Header @@ -119,6 +120,7 @@ for _, cookie := range cookies { ``` go => fiber ``` + ## Body @@ -174,6 +176,7 @@ fmt.Printf("%+v\n", out) ``` {Slideshow:{Author:Yours Truly Date:date of publication Title:Sample Slide Show}} ``` + ## XML diff --git a/docs/client/rest.md b/docs/client/rest.md index 5b13b2ea97..c65e361961 100644 --- a/docs/client/rest.md +++ b/docs/client/rest.md @@ -6,7 +6,7 @@ description: >- sidebar_position: 1 --- -The Fiber Client 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 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. @@ -332,7 +332,7 @@ func (c *Client) SetRootCertificate(path string) *Client ### SetRootCertificateFromString -SetRootCertificateFromString method adds one or more root certificates into client. +SetRootCertificateFromString method adds one or more root certificates into the client. ```go title="Signature" func (c *Client) SetRootCertificateFromString(pem string) *Client @@ -356,7 +356,7 @@ func (c *Client) RetryConfig() *RetryConfig ### SetRetryConfig -SetRetryConfig sets retry config in client which is impl by addon/retry package. +SetRetryConfig sets retry config in client, which is impl by addon/retry package. ```go title="Signature" func (c *Client) SetRetryConfig(config *RetryConfig) *Client @@ -517,7 +517,7 @@ func (c *Client) DelParams(key ...string) *Client ### SetUserAgent -SetUserAgent method sets userAgent field and its value in the client instance. +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. From 7dea200fb88b3a019f384ff90e234db201bb476b Mon Sep 17 00:00:00 2001 From: Muhammed Efe Cetin Date: Mon, 13 May 2024 15:01:14 +0300 Subject: [PATCH 12/14] apply review --- docs/client/request.md | 86 +++++++++++++++++++++--------------------- 1 file changed, 43 insertions(+), 43 deletions(-) diff --git a/docs/client/request.md b/docs/client/request.md index 02b662718a..c910fc9540 100644 --- a/docs/client/request.md +++ b/docs/client/request.md @@ -1007,7 +1007,7 @@ Reset clears Request object, used by ReleaseRequest method. func (r *Request) Reset() ``` -# Header +## Header Header is a wrapper which wrap http.Header, the header in client and request will store in it. @@ -1017,7 +1017,7 @@ type Header struct { } ``` -## PeekMultiple +### PeekMultiple PeekMultiple methods returns multiple field in header with same key. @@ -1025,7 +1025,7 @@ PeekMultiple methods returns multiple field in header with same key. func (h *Header) PeekMultiple(key string) []string ``` -## AddHeaders +### AddHeaders AddHeaders receives a map and add each value to header. @@ -1033,7 +1033,7 @@ AddHeaders receives a map and add each value to header. func (h *Header) AddHeaders(r map[string][]string) ``` -## SetHeaders +### SetHeaders SetHeaders will override all headers. @@ -1041,7 +1041,7 @@ SetHeaders will override all headers. func (h *Header) SetHeaders(r map[string]string) ``` -# QueryParam +## QueryParam QueryParam is a wrapper which wrap url.Values, the query string and formdata in client and request will store in it. @@ -1051,7 +1051,7 @@ type QueryParam struct { } ``` -## AddParams +### AddParams AddParams receive a map and add each value to param. @@ -1059,7 +1059,7 @@ AddParams receive a map and add each value to param. func (p *QueryParam) AddParams(r map[string][]string) ``` -## SetParams +### SetParams SetParams will override all params. @@ -1067,7 +1067,7 @@ SetParams will override all params. func (p *QueryParam) SetParams(r map[string]string) ``` -## SetParamsWithStruct +### SetParamsWithStruct SetParamsWithStruct will override all params with struct or pointer of struct. Nested structs are not currently supported. @@ -1076,7 +1076,7 @@ Nested structs are not currently supported. func (p *QueryParam) SetParamsWithStruct(v any) ``` -# Cookie +## Cookie Cookie is a map which to store the cookies. @@ -1084,7 +1084,7 @@ Cookie is a map which to store the cookies. type Cookie map[string]string ``` -## Add +### Add Add method impl the method in WithStruct interface. @@ -1092,7 +1092,7 @@ Add method impl the method in WithStruct interface. func (c Cookie) Add(key, val string) ``` -## Del +### Del Del method impl the method in WithStruct interface. @@ -1100,7 +1100,7 @@ Del method impl the method in WithStruct interface. func (c Cookie) Del(key string) ``` -## SetCookie +### SetCookie SetCookie method sets a single val in Cookie. @@ -1108,7 +1108,7 @@ SetCookie method sets a single val in Cookie. func (c Cookie) SetCookie(key, val string) ``` -## SetCookies +### SetCookies SetCookies method sets multiple val in Cookie. @@ -1116,7 +1116,7 @@ SetCookies method sets multiple val in Cookie. func (c Cookie) SetCookies(m map[string]string) ``` -## SetCookiesWithStruct +### SetCookiesWithStruct SetCookiesWithStruct method sets multiple val in Cookie via a struct. @@ -1124,7 +1124,7 @@ SetCookiesWithStruct method sets multiple val in Cookie via a struct. func (c Cookie) SetCookiesWithStruct(v any) ``` -## DelCookies +### DelCookies DelCookies method deletes multiple val in Cookie. @@ -1132,7 +1132,7 @@ DelCookies method deletes multiple val in Cookie. func (c Cookie) DelCookies(key ...string) ``` -## VisitAll +### VisitAll VisitAll method receive a function which can travel the all val. @@ -1140,7 +1140,7 @@ VisitAll method receive a function which can travel the all val. func (c Cookie) VisitAll(f func(key, val string)) ``` -## Reset +### Reset Reset clears the Cookie object. @@ -1148,7 +1148,7 @@ Reset clears the Cookie object. func (c Cookie) Reset() ``` -# PathParam +## PathParam PathParam is a map which to store path params. @@ -1156,7 +1156,7 @@ PathParam is a map which to store path params. type PathParam map[string]string ``` -## Add +### Add Add method impl the method in WithStruct interface. @@ -1164,7 +1164,7 @@ Add method impl the method in WithStruct interface. func (p PathParam) Add(key, val string) ``` -## Del +### Del Del method impl the method in WithStruct interface. @@ -1172,7 +1172,7 @@ Del method impl the method in WithStruct interface. func (p PathParam) Del(key string) ``` -## SetParam +### SetParam SetParam method sets a single val in PathParam. @@ -1180,7 +1180,7 @@ SetParam method sets a single val in PathParam. func (p PathParam) SetParam(key, val string) ``` -## SetParams +### SetParams SetParams method sets multiple val in PathParam. @@ -1188,7 +1188,7 @@ SetParams method sets multiple val in PathParam. func (p PathParam) SetParams(m map[string]string) ``` -## SetParamsWithStruct +### SetParamsWithStruct SetParamsWithStruct method sets multiple val in PathParam via a struct. @@ -1196,7 +1196,7 @@ SetParamsWithStruct method sets multiple val in PathParam via a struct. func (p PathParam) SetParamsWithStruct(v any) ``` -## DelParams +### DelParams DelParams method deletes multiple val in PathParams. @@ -1204,7 +1204,7 @@ DelParams method deletes multiple val in PathParams. func (p PathParam) DelParams(key ...string) ``` -## VisitAll +### VisitAll VisitAll method receive a function which can travel the all val. @@ -1212,7 +1212,7 @@ VisitAll method receive a function which can travel the all val. func (p PathParam) VisitAll(f func(key, val string)) ``` -## Reset +### Reset Reset clears the PathParam object. @@ -1220,7 +1220,7 @@ Reset clears the PathParam object. func (p PathParam) Reset() ``` -# FormData +## FormData FormData is a wrapper of fasthttp.Args and it is used for url encode body and file body. @@ -1230,7 +1230,7 @@ type FormData struct { } ``` -## AddData +### AddData AddData method is a wrapper of Args's Add method. @@ -1238,7 +1238,7 @@ AddData method is a wrapper of Args's Add method. func (f *FormData) AddData(key, val string) ``` -## SetData +### SetData SetData method is a wrapper of Args's Set method. @@ -1246,7 +1246,7 @@ SetData method is a wrapper of Args's Set method. func (f *FormData) SetData(key, val string) ``` -## AddDatas +### AddDatas AddDatas method supports add multiple fields. @@ -1254,7 +1254,7 @@ AddDatas method supports add multiple fields. func (f *FormData) AddDatas(m map[string][]string) ``` -## SetDatas +### SetDatas SetDatas method supports set multiple fields. @@ -1262,7 +1262,7 @@ SetDatas method supports set multiple fields. func (f *FormData) SetDatas(m map[string]string) ``` -## SetDatasWithStruct +### SetDatasWithStruct SetDatasWithStruct method supports set multiple fields via a struct. @@ -1270,7 +1270,7 @@ SetDatasWithStruct method supports set multiple fields via a struct. func (f *FormData) SetDatasWithStruct(v any) ``` -## DelDatas +### DelDatas DelDatas method deletes multiple fields. @@ -1278,7 +1278,7 @@ DelDatas method deletes multiple fields. func (f *FormData) DelDatas(key ...string) ``` -## Reset +### Reset Reset clear the FormData object. @@ -1286,7 +1286,7 @@ Reset clear the FormData object. func (f *FormData) Reset() ``` -# File +## File File is a struct which support send files via request. @@ -1299,9 +1299,9 @@ type File struct { } ``` -## AcquireFile +### AcquireFile -AcquireFile returns an File object from the pool. +AcquireFile returns a File object from the pool. And you can set field in the File with SetFileFunc. The returned file may be returned to the pool with ReleaseFile when no longer needed. @@ -1311,7 +1311,7 @@ This allows reducing GC load. func AcquireFile(setter ...SetFileFunc) *File ``` -## ReleaseFile +### ReleaseFile ReleaseFile returns the object acquired via AcquireFile to the pool. Do not access the released File object, otherwise data races may occur. @@ -1320,7 +1320,7 @@ Do not access the released File object, otherwise data races may occur. func ReleaseFile(f *File) ``` -## SetName +### SetName SetName method sets file name. @@ -1328,7 +1328,7 @@ SetName method sets file name. func (f *File) SetName(n string) ``` -## SetFieldName +### SetFieldName SetFieldName method sets key of file in the body. @@ -1336,7 +1336,7 @@ SetFieldName method sets key of file in the body. func (f *File) SetFieldName(n string) ``` -## SetPath +### SetPath SetPath method set file path. @@ -1344,7 +1344,7 @@ SetPath method set file path. func (f *File) SetPath(p string) ``` -## SetReader +### SetReader SetReader method can receive an io.ReadCloser which will be closed in parserBody hook. @@ -1352,7 +1352,7 @@ SetReader method can receive an io.ReadCloser which will be closed in parserBody func (f *File) SetReader(r io.ReadCloser) ``` -## Reset +### Reset Reset clear the File object. From 1e44b9cb0f2fbaa5e551a95aa4505ec5a9f329ab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9?= Date: Mon, 13 May 2024 14:35:29 +0200 Subject: [PATCH 13/14] docs: add docs for new client --- docs/client/examples.md | 2 +- docs/client/hooks.md | 1 + docs/client/request.md | 209 ++++++++++++++++++++-------------------- docs/client/rest.md | 191 +++++++++++++++++------------------- 4 files changed, 199 insertions(+), 204 deletions(-) diff --git a/docs/client/examples.md b/docs/client/examples.md index d5f8190cde..2ea79609da 100644 --- a/docs/client/examples.md +++ b/docs/client/examples.md @@ -2,7 +2,7 @@ id: examples title: 🍳 Examples description: >- -Client usage examples. + Client usage examples. sidebar_position: 5 --- diff --git a/docs/client/hooks.md b/docs/client/hooks.md index 3ae510f354..3115cf8e05 100644 --- a/docs/client/hooks.md +++ b/docs/client/hooks.md @@ -4,6 +4,7 @@ title: 🎣 Hooks description: >- Hooks are used to manipulate request/response proccess of Fiber client. sidebar_position: 4 +toc --- With hooks, you can manipulate the client on before request/after response stages or more complex logging/tracing cases. diff --git a/docs/client/request.md b/docs/client/request.md index c910fc9540..a5a025bdad 100644 --- a/docs/client/request.md +++ b/docs/client/request.md @@ -43,6 +43,82 @@ type Request struct { } ``` + +## REST Methods + +### Get + +Get sends the GET request. +It sets the URL and HTTP method, and then it sends the request. + +```go title="Signature" +func (r *Request) Get(url string) (*Response, error) +``` + +### Post + +Post sends the POST request. +It sets the URL and HTTP method, and then it sends the request. + +```go title="Signature" +func (r *Request) Post(url string) (*Response, error) +``` + +### Put + +Put sends the PUT request. +It sets the URL and HTTP method, and then it sends the request. + +```go title="Signature" +func (r *Request) Put(url string) (*Response, error) +``` + +### Patch + +Patch sends the PATCH request. +It sets the URL and HTTP method, and then it sends the request. + +```go title="Signature" +func (r *Request) Patch(url string) (*Response, error) +``` + +### Delete + +Delete sends the DELETE request. +It sets the URL and HTTP method, and then it sends the request. + +```go title="Signature" +func (r *Request) Delete(url string) (*Response, error) +``` + +### Head + +Head sends the HEAD request. +It sets the URL and HTTP method, and then it sends the request. + +```go title="Signature" +func (r *Request) Head(url string) (*Response, error) +``` + +### Options + +Options sends the OPTIONS request. +It sets the URL and HTTP method, and then it sends the request. + +```go title="Signature" +func (r *Request) Options(url string) (*Response, error) +``` + +### Custom + +Custom sends a request with custom HTTP method. +It sets the URL and HTTP method, and then it sends the request. +You can use Custom to send requests with methods like TRACE, CONNECT. + +```go title="Signature" +func (r *Request) Custom(url, method string) (*Response, error) +``` + ## AcquireRequest AcquireRequest returns an empty request object from the pool. @@ -135,7 +211,7 @@ Header method returns header value via key, this method will visit all field in func (r *Request) Header(key string) []string ``` -## AddHeader +### AddHeader AddHeader method adds a single header field and its value in the request instance. @@ -177,7 +253,7 @@ fmt.Println(resp.String()) -## SetHeader +### SetHeader SetHeader method sets a single header field and its value in the request instance. It will override the header which has been set in the client instance. @@ -219,7 +295,7 @@ fmt.Println(resp.String()) -## AddHeaders +### AddHeaders AddHeaders method adds multiple header fields and its values at one go in the request instance. @@ -227,7 +303,7 @@ AddHeaders method adds multiple header fields and its values at one go in the re func (r *Request) AddHeaders(h map[string][]string) *Request ``` -## SetHeaders +### SetHeaders SetHeaders method sets multiple header fields and its values at one go in the request instance. It will override the header which has been set in the client instance. @@ -244,7 +320,7 @@ Param method returns params value via key, this method will visit all field in t func (r *Request) Param(key string) []string ``` -## AddParam +### AddParam AddParam method adds a single param field and its value in the request instance. @@ -285,7 +361,7 @@ fmt.Println(string(resp.Body())) -## SetParam +### SetParam SetParam method sets a single param field and its value in the request instance. It will override param, which has been set in client instance. @@ -294,7 +370,7 @@ It will override param, which has been set in client instance. func (r *Request) SetParam(key, val string) *Request ``` -## AddParams +### AddParams AddParams method adds multiple param fields and its values at one go in the request instance. @@ -302,7 +378,7 @@ AddParams method adds multiple param fields and its values at one go in the requ func (r *Request) AddParams(m map[string][]string) *Request ``` -## SetParams +### SetParams SetParams method sets multiple param fields and its values at one go in the request instance. It will override param, which has been set in client instance. @@ -311,7 +387,7 @@ It will override param, which has been set in client instance. func (r *Request) SetParams(m map[string]string) *Request ``` -## SetParamsWithStruct +### SetParamsWithStruct SetParamsWithStruct method sets multiple param fields and its values at one go in the request instance. It will override param, which has been set in client instance. @@ -360,7 +436,7 @@ fmt.Println(string(resp.Body())) -## DelParams +### DelParams DelParams method deletes single or multiple param fields and their values. @@ -426,7 +502,7 @@ Cookie returns the cookie set in the request instance. If the cookie doesn't exi func (r *Request) Cookie(key string) string ``` -## SetCookie +### SetCookie SetCookie method sets a single cookie field and its value in the request instance. It will override the cookie which is set in the client instance. @@ -435,7 +511,7 @@ It will override the cookie which is set in the client instance. func (r *Request) SetCookie(key, val string) *Request ``` -## SetCookies +### SetCookies SetCookies method sets multiple cookie fields and its values at one go in the request instance. It will override the cookie which is set in the client instance. @@ -474,7 +550,7 @@ fmt.Println(string(resp.Body())) -## SetCookiesWithStruct +### SetCookiesWithStruct SetCookiesWithStruct method sets multiple cookie fields and its values at one go in the request instance. It will override the cookie which is set in the client instance. @@ -483,7 +559,7 @@ It will override the cookie which is set in the client instance. func (r *Request) SetCookiesWithStruct(v any) *Request ``` -## DelCookies +### DelCookies DelCookies method deletes single or multiple cookie fields ant its values. @@ -499,7 +575,7 @@ PathParam returns the path param set in the request instance. If the path param func (r *Request) PathParam(key string) string ``` -## SetPathParam +### SetPathParam SetPathParam method sets a single path param field and its value in the request instance. It will override path param which set in client instance. @@ -531,7 +607,7 @@ Gofiber -## SetPathParams +### SetPathParams SetPathParams method sets multiple path param fields and its values at one go in the request instance. It will override path param which set in client instance. @@ -540,7 +616,7 @@ It will override path param which set in client instance. func (r *Request) SetPathParams(m map[string]string) *Request ``` -## SetPathParamsWithStruct +### SetPathParamsWithStruct SetPathParamsWithStruct method sets multiple path param fields and its values at one go in the request instance. It will override path param which set in client instance. @@ -549,7 +625,7 @@ It will override path param which set in client instance. func (r *Request) SetPathParamsWithStruct(v any) *Request ``` -## DelPathParams +### DelPathParams DelPathParams method deletes single or multiple path param fields ant its values. @@ -557,7 +633,7 @@ DelPathParams method deletes single or multiple path param fields ant its values func (r *Request) DelPathParams(key ...string) *Request ``` -## ResetPathParams +### ResetPathParams ResetPathParams deletes all path params. @@ -597,7 +673,7 @@ FormData method returns form data value via key, this method will visit all fiel func (r *Request) FormData(key string) []string ``` -## AddFormData +### AddFormData AddFormData method adds a single form data field and its value in the request instance. @@ -642,7 +718,7 @@ fmt.Println(string(resp.Body())) -## SetFormData +### SetFormData SetFormData method sets a single form data field and its value in the request instance. @@ -683,7 +759,7 @@ fmt.Println(string(resp.Body())) -## AddFormDatas +### AddFormDatas AddFormDatas method adds multiple form data fields and its values in the request instance. @@ -691,7 +767,7 @@ AddFormDatas method adds multiple form data fields and its values in the request func (r *Request) AddFormDatas(m map[string][]string) *Request ``` -## SetFormDatas +### SetFormDatas SetFormDatas method sets multiple form data fields and its values in the request instance. @@ -699,7 +775,7 @@ SetFormDatas method sets multiple form data fields and its values in the request func (r *Request) SetFormDatas(m map[string]string) *Request ``` -## SetFormDatas +### SetFormDatas SetFormDatas method sets multiple form data fields and its values in the request instance. @@ -707,7 +783,7 @@ SetFormDatas method sets multiple form data fields and its values in the request func (r *Request) SetFormDatas(m map[string]string) *Request ``` -## SetFormDatasWithStruct +### SetFormDatasWithStruct SetFormDatasWithStruct method sets multiple form data fields and its values in the request instance via struct. @@ -715,7 +791,7 @@ SetFormDatasWithStruct method sets multiple form data fields and its values in t func (r *Request) SetFormDatasWithStruct(v any) *Request ``` -## DelFormDatas +### DelFormDatas DelFormDatas method deletes multiple form data fields and its value in the request instance. @@ -732,7 +808,7 @@ If the name field is empty, it will try to match path. func (r *Request) File(name string) *File ``` -## FileByPath +### FileByPath FileByPath returns file ptr store in request obj by path. @@ -740,7 +816,7 @@ FileByPath returns file ptr store in request obj by path. func (r *Request) FileByPath(path string) *File ``` -## AddFile +### AddFile AddFile method adds a single file field and its value in the request instance via file path. @@ -779,7 +855,7 @@ fmt.Println(string(resp.Body())) -## AddFileWithReader +### AddFileWithReader AddFileWithReader method adds a single field and its value in the request instance via reader. @@ -819,7 +895,7 @@ fmt.Println(string(resp.Body())) -## AddFiles +### AddFiles AddFiles method adds multiple file fields and its value in the request instance via File instance. @@ -918,79 +994,6 @@ It will override max redirect, which is set in the client instance. func (r *Request) SetMaxRedirects(count int) *Request ``` -## Get - -Get sends the GET request. -It sets the URL and HTTP method, and then it sends the request. - -```go title="Signature" -func (r *Request) Get(url string) (*Response, error) -``` - -## Post - -Post sends the POST request. -It sets the URL and HTTP method, and then it sends the request. - -```go title="Signature" -func (r *Request) Post(url string) (*Response, error) -``` - -## Head - -Head sends the HEAD request. -It sets the URL and HTTP method, and then it sends the request. - -```go title="Signature" -func (r *Request) Head(url string) (*Response, error) -``` - -## Put - -Put sends the PUT request. -It sets the URL and HTTP method, and then it sends the request. - -```go title="Signature" -func (r *Request) Put(url string) (*Response, error) -``` - -## Delete - -Delete sends the DELETE request. -It sets the URL and HTTP method, and then it sends the request. - -```go title="Signature" -func (r *Request) Delete(url string) (*Response, error) -``` - -## Options - -Options sends the OPTIONS request. -It sets the URL and HTTP method, and then it sends the request. - -```go title="Signature" -func (r *Request) Options(url string) (*Response, error) -``` - -## Patch - -Patch sends the PATCH request. -It sets the URL and HTTP method, and then it sends the request. - -```go title="Signature" -func (r *Request) Patch(url string) (*Response, error) -``` - -## Custom - -Custom sends a request with custom HTTP method. -It sets the URL and HTTP method, and then it sends the request. -You can use Custom to send requests with methods like TRACE, CONNECT. - -```go title="Signature" -func (r *Request) Custom(url, method string) (*Response, error) -``` - ## Send Send sends HTTP request. diff --git a/docs/client/rest.md b/docs/client/rest.md index c65e361961..9b34b80f42 100644 --- a/docs/client/rest.md +++ b/docs/client/rest.md @@ -4,6 +4,7 @@ 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. @@ -118,20 +119,20 @@ Post provides an API like axios which send post request. func (c *Client) Post(url string, cfg ...Config) (*Response, error) ``` -### Head +### Put -Head provides an API like axios which send head request. +Put provides an API like axios which send put request. ```go title="Signature" -func (c *Client) Head(url string, cfg ...Config) (*Response, error) +func (c *Client) Put(url string, cfg ...Config) (*Response, error) ``` -### Put +### Patch -Put provides an API like axios which send put request. +Patch provides an API like axios which send patch request. ```go title="Signature" -func (c *Client) Put(url string, cfg ...Config) (*Response, error) +func (c *Client) Patch(url string, cfg ...Config) (*Response, error) ``` ### Delete @@ -142,20 +143,20 @@ Delete provides an API like axios which send delete request. func (c *Client) Delete(url string, cfg ...Config) (*Response, error) ``` -### Options +### Head -Options provides an API like axios which send options request. +Head provides an API like axios which send head request. ```go title="Signature" -func (c *Client) Options(url string, cfg ...Config) (*Response, error) +func (c *Client) Head(url string, cfg ...Config) (*Response, error) ``` -### Patch +### Options -Patch provides an API like axios which send patch request. +Options provides an API like axios which send options request. ```go title="Signature" -func (c *Client) Patch(url string, cfg ...Config) (*Response, error) +func (c *Client) Options(url string, cfg ...Config) (*Response, error) ``` ### Custom @@ -201,7 +202,9 @@ It acquires a request from the pool. You have to release it using `ReleaseReques func (c *Client) R() *Request ``` -### RequestHook +### Hooks + +#### RequestHook RequestHook Request returns user-defined request hooks. @@ -209,23 +212,23 @@ RequestHook Request returns user-defined request hooks. func (c *Client) RequestHook() []RequestHook ``` -### AddRequestHook +#### ResponseHook -AddRequestHook Add user-defined request hooks. +ResponseHook return user-define response hooks. ```go title="Signature" -func (c *Client) AddRequestHook(h ...RequestHook) *Client +func (c *Client) ResponseHook() []ResponseHook ``` -### ResponseHook +#### AddRequestHook -ResponseHook return user-define response hooks. +AddRequestHook Add user-defined request hooks. ```go title="Signature" -func (c *Client) ResponseHook() []ResponseHook +func (c *Client) AddRequestHook(h ...RequestHook) *Client ``` -### AddResponseHook +#### AddResponseHook AddResponseHook Add user-defined response hooks. @@ -233,7 +236,9 @@ AddResponseHook Add user-defined response hooks. func (c *Client) AddResponseHook(h ...ResponseHook) *Client ``` -### JSONMarshal +### JSON + +#### JSONMarshal JSONMarshal returns json marshal function in Core. @@ -241,23 +246,23 @@ JSONMarshal returns json marshal function in Core. func (c *Client) JSONMarshal() utils.JSONMarshal ``` -### SetJSONMarshal +#### JSONUnmarshal -SetJSONMarshal sets the JSON encoder. +JSONUnmarshal returns json unmarshal function in Core. ```go title="Signature" -func (c *Client) SetJSONMarshal(f utils.JSONMarshal) *Client +func (c *Client) JSONUnmarshal() utils.JSONUnmarshal ``` -### JSONUnmarshal +#### SetJSONMarshal -JSONUnmarshal returns json unmarshal function in Core. +SetJSONMarshal sets the JSON encoder. ```go title="Signature" -func (c *Client) JSONUnmarshal() utils.JSONUnmarshal +func (c *Client) SetJSONMarshal(f utils.JSONMarshal) *Client ``` -### SetJSONUnmarshal +#### SetJSONUnmarshal Set the JSON decoder. @@ -265,7 +270,9 @@ Set the JSON decoder. func (c *Client) SetJSONUnmarshal(f utils.JSONUnmarshal) *Client ``` -### XMLMarshal +### XML + +#### XMLMarshal XMLMarshal returns xml marshal function in Core. @@ -273,23 +280,23 @@ XMLMarshal returns xml marshal function in Core. func (c *Client) XMLMarshal() utils.XMLMarshal ``` -### SetXMLMarshal +#### XMLUnmarshal -SetXMLMarshal sets the XML encoder. +XMLUnmarshal returns xml unmarshal function in Core. ```go title="Signature" -func (c *Client) SetXMLMarshal(f utils.XMLMarshal) *Client +func (c *Client) XMLUnmarshal() utils.XMLUnmarshal ``` -### XMLUnmarshal +#### SetXMLMarshal -XMLUnmarshal returns xml unmarshal function in Core. +SetXMLMarshal sets the XML encoder. ```go title="Signature" -func (c *Client) XMLUnmarshal() utils.XMLUnmarshal +func (c *Client) SetXMLMarshal(f utils.XMLMarshal) *Client ``` -### SetXMLUnmarshal +#### SetXMLUnmarshal SetXMLUnmarshal sets the XML decoder. @@ -297,7 +304,9 @@ SetXMLUnmarshal sets the XML decoder. func (c *Client) SetXMLUnmarshal(f utils.XMLUnmarshal) *Client ``` -### TLSConfig +### TLS + +#### TLSConfig TLSConfig returns tlsConfig in client. If the client doesn't have a tlsConfig, this function will initialize it. @@ -306,7 +315,7 @@ If the client doesn't have a tlsConfig, this function will initialize it. func (c *Client) TLSConfig() *tls.Config ``` -### SetTLSConfig +#### SetTLSConfig SetTLSConfig sets tlsConfig in client. @@ -314,7 +323,7 @@ SetTLSConfig sets tlsConfig in client. func (c *Client) SetTLSConfig(config *tls.Config) *Client ``` -### SetCertificates +#### SetCertificates SetCertificates method sets client certificates into client. @@ -322,7 +331,7 @@ SetCertificates method sets client certificates into client. func (c *Client) SetCertificates(certs ...tls.Certificate) *Client ``` -### SetRootCertificate +#### SetRootCertificate SetRootCertificate adds one or more root certificates into client. @@ -330,7 +339,7 @@ SetRootCertificate adds one or more root certificates into client. func (c *Client) SetRootCertificate(path string) *Client ``` -### SetRootCertificateFromString +#### SetRootCertificateFromString SetRootCertificateFromString method adds one or more root certificates into the client. @@ -409,7 +418,7 @@ Header method returns header value via key, this method will visit all field in 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. @@ -419,7 +428,7 @@ Also, it can be overridden at request level header options. 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. @@ -429,7 +438,7 @@ Also, it can be overridden at request level header options. 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. @@ -439,7 +448,7 @@ Also it can be overridden at request level headers options. 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. @@ -457,7 +466,7 @@ Param method returns params value via key, this method will visit all field in t 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. @@ -467,7 +476,7 @@ Also, it can be overridden at request level param options. 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. @@ -477,7 +486,7 @@ Also, it can be overridden at request level param options. 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. @@ -487,7 +496,7 @@ Also it can be overridden at request level params options. 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. @@ -497,7 +506,7 @@ Also it can be overridden at request level params options. 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. @@ -507,7 +516,7 @@ Also it can be overridden at request level params options. func (c *Client) SetParamsWithStruct(v any) *Client ``` -### DelParams +#### DelParams DelParams method deletes single or multiple params field and its values in client. @@ -544,7 +553,7 @@ If the path param doesn't exist, return empty string. 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. @@ -554,7 +563,7 @@ Also it can be overridden at request level path params options. 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. @@ -564,7 +573,7 @@ Also it can be overridden at request level path params options. 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. @@ -574,7 +583,7 @@ Also it can be overridden at request level path params options. func (c *Client) SetPathParamsWithStruct(v any) *Client ``` -### DelPathParams +#### DelPathParams DelPathParams method deletes single or multiple path params field and its values in client. @@ -591,7 +600,7 @@ If cookie doesn't exist, return empty string. 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. @@ -625,7 +634,7 @@ 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. @@ -635,7 +644,7 @@ Also it can be overridden at request level cookie options. 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. @@ -645,17 +654,7 @@ Also it can be overridden at request level cookies options. func (c *Client) SetCookiesWithStruct(v any) *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 DelCookies method deletes single or multiple cookies field and its values in client. @@ -681,7 +680,7 @@ Debug enable log debug level output. func (c *Client) Debug() *Client ``` -### DisableDebug +#### DisableDebug DisableDebug disables log debug level output. @@ -691,14 +690,6 @@ func (c *Client) DisableDebug() *Client ### SetCookieJar -DisableDebug disables log debug level output. - -```go title="Signature" -func (c *Client) SetCookieJar(cookieJar *CookieJar) *Client -``` - -### SetCookieJar - SetCookieJar sets cookie jar in client instance. ```go title="Signature" @@ -747,19 +738,7 @@ You can configurate it as you wish or replace it with another clients. C gets default client. ```go title="Signature" -func C() -``` - -### Replace - -Replace the defaultClient, the returned function can undo. - -:::caution -The default client should not be changed concurrently. -::: - -```go title="Signature" -func Replace() +func C() *Client ``` ### Get @@ -778,20 +757,20 @@ Post is a convenience method that sends a POST request using the `defaultClient` func Post(url string, cfg ...Config) (*Response, error) ``` -### Head +### Put -Head sends a HEAD request using the `defaultClient`, a convenience method. +Put is a convenience method that sends a PUT request using the `defaultClient`. ```go title="Signature" -func Head(url string, cfg ...Config) (*Response, error) +func Put(url string, cfg ...Config) (*Response, error) ``` -### Put +### Patch -Put is a convenience method that sends a PUT request using the `defaultClient`. +Patch is a convenience method that sends a PATCH request using the `defaultClient`. ```go title="Signature" -func Put(url string, cfg ...Config) (*Response, error) +func Patch(url string, cfg ...Config) (*Response, error) ``` ### Delete @@ -802,6 +781,14 @@ Delete is a convenience method that sends a DELETE request using the `defaultCli 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`. @@ -810,10 +797,14 @@ Options is a convenience method that sends an OPTIONS request using the `default func Options(url string, cfg ...Config) (*Response, error) ``` -### Patch +### Replace -Patch is a convenience method that sends a PATCH request using the `defaultClient`. +Replace the defaultClient, the returned function can undo. + +:::caution +The default client should not be changed concurrently. +::: ```go title="Signature" -func Patch(url string, cfg ...Config) (*Response, error) +func Replace(c *Client) func() ``` From 5bd9e0a3034559c7492b1a86b75d1f943a16aa07 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9?= Date: Mon, 13 May 2024 14:35:59 +0200 Subject: [PATCH 14/14] docs: add docs for new client --- docs/client/hooks.md | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/client/hooks.md b/docs/client/hooks.md index 3115cf8e05..3ae510f354 100644 --- a/docs/client/hooks.md +++ b/docs/client/hooks.md @@ -4,7 +4,6 @@ title: 🎣 Hooks description: >- Hooks are used to manipulate request/response proccess of Fiber client. sidebar_position: 4 -toc --- With hooks, you can manipulate the client on before request/after response stages or more complex logging/tracing cases.