π Client
Start requestβ
Start a http request with http method and url.
// 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
β¨ Agentβ
Agent
is built on top of FastHTTP's HostClient
which has lots of convenient helper methods such as dedicated methods for request methods.
Parseβ
Parse initializes a HostClient.
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.
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
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.
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
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.
func (a *Agent) ConnectionClose() *Agent
agent.ConnectionClose()
// ...
UserAgentβ
UserAgent sets User-Agent
header value.
func (a *Agent) UserAgent(userAgent string) *Agent
func (a *Agent) UserAgentBytes(userAgent []byte) *Agent
agent.UserAgent("fiber")
// ...
Cookieβ
Cookie sets a cookie in key: value
form. Cookies
can be used to set multiple cookies.
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
agent.Cookie("k", "v")
agent.Cookies("k1", "v1", "k2", "v2")
// ...
Refererβ
Referer sets the Referer header value.
func (a *Agent) Referer(referer string) *Agent
func (a *Agent) RefererBytes(referer []byte) *Agent
agent.Referer("https://docs.gofiber.io")
// ...
ContentTypeβ
ContentType sets Content-Type header value.
func (a *Agent) ContentType(contentType string) *Agent
func (a *Agent) ContentTypeBytes(contentType []byte) *Agent
agent.ContentType("custom-type")
// ...
Hostβ
Host sets the Host header.
func (a *Agent) Host(host string) *Agent
func (a *Agent) HostBytes(host []byte) *Agent
agent.Host("example.com")
// ...
QueryStringβ
QueryString sets the URI query string.
func (a *Agent) QueryString(queryString string) *Agent
func (a *Agent) QueryStringBytes(queryString []byte) *Agent
agent.QueryString("foo=bar")
// ...
BasicAuthβ
BasicAuth sets the URI username and password using HTTP Basic Auth.
func (a *Agent) BasicAuth(username, password string) *Agent
func (a *Agent) BasicAuthBytes(username, password []byte) *Agent
agent.BasicAuth("foo", "bar")
// ...
Bodyβ
There are several ways to set request body.
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
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 application/json
.
func (a *Agent) JSON(v interface{}) *Agent
agent.JSON(fiber.Map{"success": true})
// ...
XMLβ
XML sends an XML request by setting the Content-Type header to application/xml
.
func (a *Agent) XML(v interface{}) *Agent
agent.XML(fiber.Map{"success": true})
// ...
Formβ
Form sends a form request by setting the Content-Type header to application/x-www-form-urlencoded
.
// 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
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.
// 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
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.
func (a *Agent) Boundary(boundary string) *Agent
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.
func (a *Agent) SendFile(filename string, fieldname ...string) *Agent
func (a *Agent) SendFiles(filenamesAndFieldnames ...string) *Agent
agent.SendFile("f", "field name")
.SendFiles("f1", "field name1", "f2").
.MultipartForm(nil)
// ...
FileDataβ
FileData appends file data for multipart form request.
// 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
}
// 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
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
).
func (a *Agent) Debug(w ...io.Writer) *Agent
agent.Debug()
// ...
Timeoutβ
Timeout sets request timeout duration.
func (a *Agent) Timeout(timeout time.Duration) *Agent
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.
func (a *Agent) Reuse() *Agent
agent.Reuse()
// ...
InsecureSkipVerifyβ
InsecureSkipVerify controls whether the Agent verifies the server certificate chain and host name.
func (a *Agent) InsecureSkipVerify() *Agent
agent.InsecureSkipVerify()
// ...
TLSConfigβ
TLSConfig sets tls config.
func (a *Agent) TLSConfig(config *tls.Config) *Agent
// 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.
func (a *Agent) MaxRedirectsCount(count int) *Agent
agent.MaxRedirectsCount(7)
// ...
JSONEncoderβ
JSONEncoder sets custom json encoder.
func (a *Agent) JSONEncoder(jsonEncoder utils.JSONMarshal) *Agent
agent.JSONEncoder(json.Marshal)
// ...
JSONDecoderβ
JSONDecoder sets custom json decoder.
func (a *Agent) JSONDecoder(jsonDecoder utils.JSONUnmarshal) *Agent
agent.JSONDecoder(json.Unmarshal)
// ...
Requestβ
Request returns Agent request instance.
func (a *Agent) Request() *Request
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.
func (a *Agent) SetResponse(customResp *Response) *Agent
resp := AcquireResponse()
agent.SetResponse(resp)
// ...
ReleaseResponse(resp)
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.
func (a *Agent) Dest(dest []byte) *Agent {
agent.Dest(nil)
// ...
Bytesβ
Bytes returns the status code, bytes body and errors of url.
func (a *Agent) Bytes() (code int, body []byte, errs []error)
code, body, errs := agent.Bytes()
// ...
Stringβ
String returns the status code, string body and errors of url.
func (a *Agent) String() (int, string, []error)
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.
func (a *Agent) Struct(v interface{}) (code int, body []byte, errs []error)
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
func (a *Agent) RetryIf(retryIf RetryIfFunc) *Agent
agent.Get("https://example.com").RetryIf(func (req *fiber.Request) bool {
return req.URI() == "https://example.com"
})
// ...