github.com/gofiber/fiber/v2@v2.47.0/docs/api/client.md (about) 1 --- 2 id: client 3 title: 🌎 Client 4 description: The Client struct represents the Fiber HTTP Client. 5 sidebar_position: 5 6 --- 7 8 ## Start request 9 10 Start a http request with http method and url. 11 12 ```go title="Signatures" 13 // Client http methods 14 func (c *Client) Get(url string) *Agent 15 func (c *Client) Head(url string) *Agent 16 func (c *Client) Post(url string) *Agent 17 func (c *Client) Put(url string) *Agent 18 func (c *Client) Patch(url string) *Agent 19 func (c *Client) Delete(url string) *Agent 20 ``` 21 22 ## ✨ Agent 23 24 `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. 25 26 ### Parse 27 28 Parse initializes a HostClient. 29 30 ```go title="Parse" 31 a := AcquireAgent() 32 req := a.Request() 33 req.Header.SetMethod(MethodGet) 34 req.SetRequestURI("http://example.com") 35 36 if err := a.Parse(); err != nil { 37 panic(err) 38 } 39 40 code, body, errs := a.Bytes() // ... 41 ``` 42 43 ### Set 44 45 Set sets the given `key: value` header. 46 47 ```go title="Signature" 48 func (a *Agent) Set(k, v string) *Agent 49 func (a *Agent) SetBytesK(k []byte, v string) *Agent 50 func (a *Agent) SetBytesV(k string, v []byte) *Agent 51 func (a *Agent) SetBytesKV(k []byte, v []byte) *Agent 52 ``` 53 54 ```go title="Example" 55 agent.Set("k1", "v1"). 56 SetBytesK([]byte("k1"), "v1"). 57 SetBytesV("k1", []byte("v1")). 58 SetBytesKV([]byte("k2"), []byte("v2")) 59 // ... 60 ``` 61 62 ### Add 63 64 Add adds the given `key: value` header. Multiple headers with the same key may be added with this function. 65 66 ```go title="Signature" 67 func (a *Agent) Add(k, v string) *Agent 68 func (a *Agent) AddBytesK(k []byte, v string) *Agent 69 func (a *Agent) AddBytesV(k string, v []byte) *Agent 70 func (a *Agent) AddBytesKV(k []byte, v []byte) *Agent 71 ``` 72 73 ```go title="Example" 74 agent.Add("k1", "v1"). 75 AddBytesK([]byte("k1"), "v1"). 76 AddBytesV("k1", []byte("v1")). 77 AddBytesKV([]byte("k2"), []byte("v2")) 78 // Headers: 79 // K1: v1 80 // K1: v1 81 // K1: v1 82 // K2: v2 83 ``` 84 85 ### ConnectionClose 86 87 ConnectionClose adds the `Connection: close` header. 88 89 ```go title="Signature" 90 func (a *Agent) ConnectionClose() *Agent 91 ``` 92 93 ```go title="Example" 94 agent.ConnectionClose() 95 // ... 96 ``` 97 98 ### UserAgent 99 100 UserAgent sets `User-Agent` header value. 101 102 ```go title="Signature" 103 func (a *Agent) UserAgent(userAgent string) *Agent 104 func (a *Agent) UserAgentBytes(userAgent []byte) *Agent 105 ``` 106 107 ```go title="Example" 108 agent.UserAgent("fiber") 109 // ... 110 ``` 111 112 ### Cookie 113 114 Cookie sets a cookie in `key: value` form. `Cookies` can be used to set multiple cookies. 115 116 ```go title="Signature" 117 func (a *Agent) Cookie(key, value string) *Agent 118 func (a *Agent) CookieBytesK(key []byte, value string) *Agent 119 func (a *Agent) CookieBytesKV(key, value []byte) *Agent 120 func (a *Agent) Cookies(kv ...string) *Agent 121 func (a *Agent) CookiesBytesKV(kv ...[]byte) *Agent 122 ``` 123 124 ```go title="Example" 125 agent.Cookie("k", "v") 126 agent.Cookies("k1", "v1", "k2", "v2") 127 // ... 128 ``` 129 130 ### Referer 131 132 Referer sets the Referer header value. 133 134 ```go title="Signature" 135 func (a *Agent) Referer(referer string) *Agent 136 func (a *Agent) RefererBytes(referer []byte) *Agent 137 ``` 138 139 ```go title="Example" 140 agent.Referer("https://docs.gofiber.io") 141 // ... 142 ``` 143 144 ### ContentType 145 146 ContentType sets Content-Type header value. 147 148 ```go title="Signature" 149 func (a *Agent) ContentType(contentType string) *Agent 150 func (a *Agent) ContentTypeBytes(contentType []byte) *Agent 151 ``` 152 153 ```go title="Example" 154 agent.ContentType("custom-type") 155 // ... 156 ``` 157 158 ### Host 159 160 Host sets the Host header. 161 162 ```go title="Signature" 163 func (a *Agent) Host(host string) *Agent 164 func (a *Agent) HostBytes(host []byte) *Agent 165 ``` 166 167 ```go title="Example" 168 agent.Host("example.com") 169 // ... 170 ``` 171 172 ### QueryString 173 174 QueryString sets the URI query string. 175 176 ```go title="Signature" 177 func (a *Agent) QueryString(queryString string) *Agent 178 func (a *Agent) QueryStringBytes(queryString []byte) *Agent 179 ``` 180 181 ```go title="Example" 182 agent.QueryString("foo=bar") 183 // ... 184 ``` 185 186 ### BasicAuth 187 188 BasicAuth sets the URI username and password using HTTP Basic Auth. 189 190 ```go title="Signature" 191 func (a *Agent) BasicAuth(username, password string) *Agent 192 func (a *Agent) BasicAuthBytes(username, password []byte) *Agent 193 ``` 194 195 ```go title="Example" 196 agent.BasicAuth("foo", "bar") 197 // ... 198 ``` 199 200 ### Body 201 202 There are several ways to set request body. 203 204 ```go title="Signature" 205 func (a *Agent) BodyString(bodyString string) *Agent 206 func (a *Agent) Body(body []byte) *Agent 207 208 // BodyStream sets request body stream and, optionally body size. 209 // 210 // If bodySize is >= 0, then the bodyStream must provide exactly bodySize bytes 211 // before returning io.EOF. 212 // 213 // If bodySize < 0, then bodyStream is read until io.EOF. 214 // 215 // bodyStream.Close() is called after finishing reading all body data 216 // if it implements io.Closer. 217 // 218 // Note that GET and HEAD requests cannot have body. 219 func (a *Agent) BodyStream(bodyStream io.Reader, bodySize int) *Agent 220 ``` 221 222 ```go title="Example" 223 agent.BodyString("foo=bar") 224 agent.Body([]byte("bar=baz")) 225 agent.BodyStream(strings.NewReader("body=stream"), -1) 226 // ... 227 ``` 228 229 ### JSON 230 231 JSON sends a JSON request by setting the Content-Type header to `application/json`. 232 233 ```go title="Signature" 234 func (a *Agent) JSON(v interface{}) *Agent 235 ``` 236 237 ```go title="Example" 238 agent.JSON(fiber.Map{"success": true}) 239 // ... 240 ``` 241 242 ### XML 243 244 XML sends an XML request by setting the Content-Type header to `application/xml`. 245 246 ```go title="Signature" 247 func (a *Agent) XML(v interface{}) *Agent 248 ``` 249 250 ```go title="Example" 251 agent.XML(fiber.Map{"success": true}) 252 // ... 253 ``` 254 255 ### Form 256 257 Form sends a form request by setting the Content-Type header to `application/x-www-form-urlencoded`. 258 259 ```go title="Signature" 260 // Form sends form request with body if args is non-nil. 261 // 262 // It is recommended obtaining args via AcquireArgs and release it 263 // manually in performance-critical code. 264 func (a *Agent) Form(args *Args) *Agent 265 ``` 266 267 ```go title="Example" 268 args := AcquireArgs() 269 args.Set("foo", "bar") 270 271 agent.Form(args) 272 // ... 273 ReleaseArgs(args) 274 ``` 275 276 ### MultipartForm 277 278 MultipartForm sends multipart form request by setting the Content-Type header to `multipart/form-data`. These requests can include key-value's and files. 279 280 ```go title="Signature" 281 // MultipartForm sends multipart form request with k-v and files. 282 // 283 // It is recommended to obtain args via AcquireArgs and release it 284 // manually in performance-critical code. 285 func (a *Agent) MultipartForm(args *Args) *Agent 286 ``` 287 288 ```go title="Example" 289 args := AcquireArgs() 290 args.Set("foo", "bar") 291 292 agent.MultipartForm(args) 293 // ... 294 ReleaseArgs(args) 295 ``` 296 297 Fiber provides several methods for sending files. Note that they must be called before `MultipartForm`. 298 299 #### Boundary 300 301 Boundary sets boundary for multipart form request. 302 303 ```go title="Signature" 304 func (a *Agent) Boundary(boundary string) *Agent 305 ``` 306 307 ```go title="Example" 308 agent.Boundary("myBoundary") 309 .MultipartForm(nil) 310 // ... 311 ``` 312 313 #### SendFile\(s\) 314 315 SendFile read a file and appends it to a multipart form request. Sendfiles can be used to append multiple files. 316 317 ```go title="Signature" 318 func (a *Agent) SendFile(filename string, fieldname ...string) *Agent 319 func (a *Agent) SendFiles(filenamesAndFieldnames ...string) *Agent 320 ``` 321 322 ```go title="Example" 323 agent.SendFile("f", "field name") 324 .SendFiles("f1", "field name1", "f2"). 325 .MultipartForm(nil) 326 // ... 327 ``` 328 329 #### FileData 330 331 FileData appends file data for multipart form request. 332 333 ```go 334 // FormFile represents multipart form file 335 type FormFile struct { 336 // Fieldname is form file's field name 337 Fieldname string 338 // Name is form file's name 339 Name string 340 // Content is form file's content 341 Content []byte 342 } 343 ``` 344 345 ```go title="Signature" 346 // FileData appends files for multipart form request. 347 // 348 // It is recommended obtaining formFile via AcquireFormFile and release it 349 // manually in performance-critical code. 350 func (a *Agent) FileData(formFiles ...*FormFile) *Agent 351 ``` 352 353 ```go title="Example" 354 ff1 := &FormFile{"filename1", "field name1", []byte("content")} 355 ff2 := &FormFile{"filename2", "field name2", []byte("content")} 356 agent.FileData(ff1, ff2). 357 MultipartForm(nil) 358 // ... 359 ``` 360 361 ### Debug 362 363 Debug mode enables logging request and response detail to `io.writer`\(default is `os.Stdout`\). 364 365 ```go title="Signature" 366 func (a *Agent) Debug(w ...io.Writer) *Agent 367 ``` 368 369 ```go title="Example" 370 agent.Debug() 371 // ... 372 ``` 373 374 ### Timeout 375 376 Timeout sets request timeout duration. 377 378 ```go title="Signature" 379 func (a *Agent) Timeout(timeout time.Duration) *Agent 380 ``` 381 382 ```go title="Example" 383 agent.Timeout(time.Second) 384 // ... 385 ``` 386 387 ### Reuse 388 389 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. 390 391 ```go title="Signature" 392 func (a *Agent) Reuse() *Agent 393 ``` 394 395 ```go title="Example" 396 agent.Reuse() 397 // ... 398 ``` 399 400 ### InsecureSkipVerify 401 402 InsecureSkipVerify controls whether the Agent verifies the server certificate chain and host name. 403 404 ```go title="Signature" 405 func (a *Agent) InsecureSkipVerify() *Agent 406 ``` 407 408 ```go title="Example" 409 agent.InsecureSkipVerify() 410 // ... 411 ``` 412 413 ### TLSConfig 414 415 TLSConfig sets tls config. 416 417 ```go title="Signature" 418 func (a *Agent) TLSConfig(config *tls.Config) *Agent 419 ``` 420 421 ```go title="Example" 422 // Create tls certificate 423 cer, _ := tls.LoadX509KeyPair("pem", "key") 424 425 config := &tls.Config{ 426 Certificates: []tls.Certificate{cer}, 427 } 428 429 agent.TLSConfig(config) 430 // ... 431 ``` 432 433 ### MaxRedirectsCount 434 435 MaxRedirectsCount sets max redirect count for GET and HEAD. 436 437 ```go title="Signature" 438 func (a *Agent) MaxRedirectsCount(count int) *Agent 439 ``` 440 441 ```go title="Example" 442 agent.MaxRedirectsCount(7) 443 // ... 444 ``` 445 446 ### JSONEncoder 447 448 JSONEncoder sets custom json encoder. 449 450 ```go title="Signature" 451 func (a *Agent) JSONEncoder(jsonEncoder utils.JSONMarshal) *Agent 452 ``` 453 454 ```go title="Example" 455 agent.JSONEncoder(json.Marshal) 456 // ... 457 ``` 458 459 ### JSONDecoder 460 461 JSONDecoder sets custom json decoder. 462 463 ```go title="Signature" 464 func (a *Agent) JSONDecoder(jsonDecoder utils.JSONUnmarshal) *Agent 465 ``` 466 467 ```go title="Example" 468 agent.JSONDecoder(json.Unmarshal) 469 // ... 470 ``` 471 472 ### Request 473 474 Request returns Agent request instance. 475 476 ```go title="Signature" 477 func (a *Agent) Request() *Request 478 ``` 479 480 ```go title="Example" 481 req := agent.Request() 482 // ... 483 ``` 484 485 ### SetResponse 486 487 SetResponse sets custom response for the Agent instance. It is recommended obtaining custom response via AcquireResponse and release it manually in performance-critical code. 488 489 ```go title="Signature" 490 func (a *Agent) SetResponse(customResp *Response) *Agent 491 ``` 492 493 ```go title="Example" 494 resp := AcquireResponse() 495 agent.SetResponse(resp) 496 // ... 497 ReleaseResponse(resp) 498 ``` 499 500 ### Dest 501 502 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. 503 504 ```go title="Signature" 505 func (a *Agent) Dest(dest []byte) *Agent { 506 ``` 507 508 ```go title="Example" 509 agent.Dest(nil) 510 // ... 511 ``` 512 513 ### Bytes 514 515 Bytes returns the status code, bytes body and errors of url. 516 517 ```go title="Signature" 518 func (a *Agent) Bytes() (code int, body []byte, errs []error) 519 ``` 520 521 ```go title="Example" 522 code, body, errs := agent.Bytes() 523 // ... 524 ``` 525 526 ### String 527 528 String returns the status code, string body and errors of url. 529 530 ```go title="Signature" 531 func (a *Agent) String() (int, string, []error) 532 ``` 533 534 ```go title="Example" 535 code, body, errs := agent.String() 536 // ... 537 ``` 538 539 ### Struct 540 541 Struct returns the status code, bytes body and errors of url. And bytes body will be unmarshalled to given v. 542 543 ```go title="Signature" 544 func (a *Agent) Struct(v interface{}) (code int, body []byte, errs []error) 545 ``` 546 547 ```go title="Example" 548 var d data 549 code, body, errs := agent.Struct(&d) 550 // ... 551 ``` 552 553 ### RetryIf 554 555 RetryIf controls whether a retry should be attempted after an error. 556 By default, will use isIdempotent function from fasthttp 557 558 ```go title="Signature" 559 func (a *Agent) RetryIf(retryIf RetryIfFunc) *Agent 560 ``` 561 562 ```go title="Example" 563 agent.Get("https://example.com").RetryIf(func (req *fiber.Request) bool { 564 return req.URI() == "https://example.com" 565 }) 566 // ... 567 ```