client.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011
  1. package fiber
  2. import (
  3. "bytes"
  4. "crypto/tls"
  5. "encoding/json"
  6. "encoding/xml"
  7. "fmt"
  8. "io"
  9. "io/ioutil"
  10. "mime/multipart"
  11. "net"
  12. "os"
  13. "path/filepath"
  14. "strconv"
  15. "strings"
  16. "sync"
  17. "time"
  18. "github.com/gofiber/fiber/v2/utils"
  19. "github.com/valyala/fasthttp"
  20. )
  21. // Request represents HTTP request.
  22. //
  23. // It is forbidden copying Request instances. Create new instances
  24. // and use CopyTo instead.
  25. //
  26. // Request instance MUST NOT be used from concurrently running goroutines.
  27. // Copy from fasthttp
  28. type Request = fasthttp.Request
  29. // Response represents HTTP response.
  30. //
  31. // It is forbidden copying Response instances. Create new instances
  32. // and use CopyTo instead.
  33. //
  34. // Response instance MUST NOT be used from concurrently running goroutines.
  35. // Copy from fasthttp
  36. type Response = fasthttp.Response
  37. // Args represents query arguments.
  38. //
  39. // It is forbidden copying Args instances. Create new instances instead
  40. // and use CopyTo().
  41. //
  42. // Args instance MUST NOT be used from concurrently running goroutines.
  43. // Copy from fasthttp
  44. type Args = fasthttp.Args
  45. // RetryIfFunc signature of retry if function
  46. // Request argument passed to RetryIfFunc, if there are any request errors.
  47. // Copy from fasthttp
  48. type RetryIfFunc = fasthttp.RetryIfFunc
  49. var defaultClient Client
  50. // Client implements http client.
  51. //
  52. // It is safe calling Client methods from concurrently running goroutines.
  53. type Client struct {
  54. mutex sync.RWMutex
  55. // UserAgent is used in User-Agent request header.
  56. UserAgent string
  57. // NoDefaultUserAgentHeader when set to true, causes the default
  58. // User-Agent header to be excluded from the Request.
  59. NoDefaultUserAgentHeader bool
  60. // When set by an external client of Fiber it will use the provided implementation of a
  61. // JSONMarshal
  62. //
  63. // Allowing for flexibility in using another json library for encoding
  64. JSONEncoder utils.JSONMarshal
  65. // When set by an external client of Fiber it will use the provided implementation of a
  66. // JSONUnmarshal
  67. //
  68. // Allowing for flexibility in using another json library for decoding
  69. JSONDecoder utils.JSONUnmarshal
  70. }
  71. // Get returns a agent with http method GET.
  72. func Get(url string) *Agent { return defaultClient.Get(url) }
  73. // Get returns a agent with http method GET.
  74. func (c *Client) Get(url string) *Agent {
  75. return c.createAgent(MethodGet, url)
  76. }
  77. // Head returns a agent with http method HEAD.
  78. func Head(url string) *Agent { return defaultClient.Head(url) }
  79. // Head returns a agent with http method GET.
  80. func (c *Client) Head(url string) *Agent {
  81. return c.createAgent(MethodHead, url)
  82. }
  83. // Post sends POST request to the given url.
  84. func Post(url string) *Agent { return defaultClient.Post(url) }
  85. // Post sends POST request to the given url.
  86. func (c *Client) Post(url string) *Agent {
  87. return c.createAgent(MethodPost, url)
  88. }
  89. // Put sends PUT request to the given url.
  90. func Put(url string) *Agent { return defaultClient.Put(url) }
  91. // Put sends PUT request to the given url.
  92. func (c *Client) Put(url string) *Agent {
  93. return c.createAgent(MethodPut, url)
  94. }
  95. // Patch sends PATCH request to the given url.
  96. func Patch(url string) *Agent { return defaultClient.Patch(url) }
  97. // Patch sends PATCH request to the given url.
  98. func (c *Client) Patch(url string) *Agent {
  99. return c.createAgent(MethodPatch, url)
  100. }
  101. // Delete sends DELETE request to the given url.
  102. func Delete(url string) *Agent { return defaultClient.Delete(url) }
  103. // Delete sends DELETE request to the given url.
  104. func (c *Client) Delete(url string) *Agent {
  105. return c.createAgent(MethodDelete, url)
  106. }
  107. func (c *Client) createAgent(method, url string) *Agent {
  108. a := AcquireAgent()
  109. a.req.Header.SetMethod(method)
  110. a.req.SetRequestURI(url)
  111. c.mutex.RLock()
  112. a.Name = c.UserAgent
  113. a.NoDefaultUserAgentHeader = c.NoDefaultUserAgentHeader
  114. a.jsonDecoder = c.JSONDecoder
  115. a.jsonEncoder = c.JSONEncoder
  116. if a.jsonDecoder == nil {
  117. a.jsonDecoder = json.Unmarshal
  118. }
  119. c.mutex.RUnlock()
  120. if err := a.Parse(); err != nil {
  121. a.errs = append(a.errs, err)
  122. }
  123. return a
  124. }
  125. // Agent is an object storing all request data for client.
  126. // Agent instance MUST NOT be used from concurrently running goroutines.
  127. type Agent struct {
  128. // Name is used in User-Agent request header.
  129. Name string
  130. // NoDefaultUserAgentHeader when set to true, causes the default
  131. // User-Agent header to be excluded from the Request.
  132. NoDefaultUserAgentHeader bool
  133. // HostClient is an embedded fasthttp HostClient
  134. *fasthttp.HostClient
  135. req *Request
  136. resp *Response
  137. dest []byte
  138. args *Args
  139. timeout time.Duration
  140. errs []error
  141. formFiles []*FormFile
  142. debugWriter io.Writer
  143. mw multipartWriter
  144. jsonEncoder utils.JSONMarshal
  145. jsonDecoder utils.JSONUnmarshal
  146. maxRedirectsCount int
  147. boundary string
  148. reuse bool
  149. parsed bool
  150. }
  151. // Parse initializes URI and HostClient.
  152. func (a *Agent) Parse() error {
  153. if a.parsed {
  154. return nil
  155. }
  156. a.parsed = true
  157. uri := a.req.URI()
  158. isTLS := false
  159. scheme := uri.Scheme()
  160. if bytes.Equal(scheme, strHTTPS) {
  161. isTLS = true
  162. } else if !bytes.Equal(scheme, strHTTP) {
  163. return fmt.Errorf("unsupported protocol %q. http and https are supported", scheme)
  164. }
  165. name := a.Name
  166. if name == "" && !a.NoDefaultUserAgentHeader {
  167. name = defaultUserAgent
  168. }
  169. a.HostClient = &fasthttp.HostClient{
  170. Addr: addMissingPort(string(uri.Host()), isTLS),
  171. Name: name,
  172. NoDefaultUserAgentHeader: a.NoDefaultUserAgentHeader,
  173. IsTLS: isTLS,
  174. }
  175. return nil
  176. }
  177. func addMissingPort(addr string, isTLS bool) string {
  178. n := strings.Index(addr, ":")
  179. if n >= 0 {
  180. return addr
  181. }
  182. port := 80
  183. if isTLS {
  184. port = 443
  185. }
  186. return net.JoinHostPort(addr, strconv.Itoa(port))
  187. }
  188. /************************** Header Setting **************************/
  189. // Set sets the given 'key: value' header.
  190. //
  191. // Use Add for setting multiple header values under the same key.
  192. func (a *Agent) Set(k, v string) *Agent {
  193. a.req.Header.Set(k, v)
  194. return a
  195. }
  196. // SetBytesK sets the given 'key: value' header.
  197. //
  198. // Use AddBytesK for setting multiple header values under the same key.
  199. func (a *Agent) SetBytesK(k []byte, v string) *Agent {
  200. a.req.Header.SetBytesK(k, v)
  201. return a
  202. }
  203. // SetBytesV sets the given 'key: value' header.
  204. //
  205. // Use AddBytesV for setting multiple header values under the same key.
  206. func (a *Agent) SetBytesV(k string, v []byte) *Agent {
  207. a.req.Header.SetBytesV(k, v)
  208. return a
  209. }
  210. // SetBytesKV sets the given 'key: value' header.
  211. //
  212. // Use AddBytesKV for setting multiple header values under the same key.
  213. func (a *Agent) SetBytesKV(k []byte, v []byte) *Agent {
  214. a.req.Header.SetBytesKV(k, v)
  215. return a
  216. }
  217. // Add adds the given 'key: value' header.
  218. //
  219. // Multiple headers with the same key may be added with this function.
  220. // Use Set for setting a single header for the given key.
  221. func (a *Agent) Add(k, v string) *Agent {
  222. a.req.Header.Add(k, v)
  223. return a
  224. }
  225. // AddBytesK adds the given 'key: value' header.
  226. //
  227. // Multiple headers with the same key may be added with this function.
  228. // Use SetBytesK for setting a single header for the given key.
  229. func (a *Agent) AddBytesK(k []byte, v string) *Agent {
  230. a.req.Header.AddBytesK(k, v)
  231. return a
  232. }
  233. // AddBytesV adds the given 'key: value' header.
  234. //
  235. // Multiple headers with the same key may be added with this function.
  236. // Use SetBytesV for setting a single header for the given key.
  237. func (a *Agent) AddBytesV(k string, v []byte) *Agent {
  238. a.req.Header.AddBytesV(k, v)
  239. return a
  240. }
  241. // AddBytesKV adds the given 'key: value' header.
  242. //
  243. // Multiple headers with the same key may be added with this function.
  244. // Use SetBytesKV for setting a single header for the given key.
  245. func (a *Agent) AddBytesKV(k []byte, v []byte) *Agent {
  246. a.req.Header.AddBytesKV(k, v)
  247. return a
  248. }
  249. // ConnectionClose sets 'Connection: close' header.
  250. func (a *Agent) ConnectionClose() *Agent {
  251. a.req.Header.SetConnectionClose()
  252. return a
  253. }
  254. // UserAgent sets User-Agent header value.
  255. func (a *Agent) UserAgent(userAgent string) *Agent {
  256. a.req.Header.SetUserAgent(userAgent)
  257. return a
  258. }
  259. // UserAgentBytes sets User-Agent header value.
  260. func (a *Agent) UserAgentBytes(userAgent []byte) *Agent {
  261. a.req.Header.SetUserAgentBytes(userAgent)
  262. return a
  263. }
  264. // Cookie sets one 'key: value' cookie.
  265. func (a *Agent) Cookie(key, value string) *Agent {
  266. a.req.Header.SetCookie(key, value)
  267. return a
  268. }
  269. // CookieBytesK sets one 'key: value' cookie.
  270. func (a *Agent) CookieBytesK(key []byte, value string) *Agent {
  271. a.req.Header.SetCookieBytesK(key, value)
  272. return a
  273. }
  274. // CookieBytesKV sets one 'key: value' cookie.
  275. func (a *Agent) CookieBytesKV(key, value []byte) *Agent {
  276. a.req.Header.SetCookieBytesKV(key, value)
  277. return a
  278. }
  279. // Cookies sets multiple 'key: value' cookies.
  280. func (a *Agent) Cookies(kv ...string) *Agent {
  281. for i := 1; i < len(kv); i += 2 {
  282. a.req.Header.SetCookie(kv[i-1], kv[i])
  283. }
  284. return a
  285. }
  286. // CookiesBytesKV sets multiple 'key: value' cookies.
  287. func (a *Agent) CookiesBytesKV(kv ...[]byte) *Agent {
  288. for i := 1; i < len(kv); i += 2 {
  289. a.req.Header.SetCookieBytesKV(kv[i-1], kv[i])
  290. }
  291. return a
  292. }
  293. // Referer sets Referer header value.
  294. func (a *Agent) Referer(referer string) *Agent {
  295. a.req.Header.SetReferer(referer)
  296. return a
  297. }
  298. // RefererBytes sets Referer header value.
  299. func (a *Agent) RefererBytes(referer []byte) *Agent {
  300. a.req.Header.SetRefererBytes(referer)
  301. return a
  302. }
  303. // ContentType sets Content-Type header value.
  304. func (a *Agent) ContentType(contentType string) *Agent {
  305. a.req.Header.SetContentType(contentType)
  306. return a
  307. }
  308. // ContentTypeBytes sets Content-Type header value.
  309. func (a *Agent) ContentTypeBytes(contentType []byte) *Agent {
  310. a.req.Header.SetContentTypeBytes(contentType)
  311. return a
  312. }
  313. /************************** End Header Setting **************************/
  314. /************************** URI Setting **************************/
  315. // Host sets host for the uri.
  316. func (a *Agent) Host(host string) *Agent {
  317. a.req.URI().SetHost(host)
  318. return a
  319. }
  320. // HostBytes sets host for the URI.
  321. func (a *Agent) HostBytes(host []byte) *Agent {
  322. a.req.URI().SetHostBytes(host)
  323. return a
  324. }
  325. // QueryString sets URI query string.
  326. func (a *Agent) QueryString(queryString string) *Agent {
  327. a.req.URI().SetQueryString(queryString)
  328. return a
  329. }
  330. // QueryStringBytes sets URI query string.
  331. func (a *Agent) QueryStringBytes(queryString []byte) *Agent {
  332. a.req.URI().SetQueryStringBytes(queryString)
  333. return a
  334. }
  335. // BasicAuth sets URI username and password.
  336. func (a *Agent) BasicAuth(username, password string) *Agent {
  337. a.req.URI().SetUsername(username)
  338. a.req.URI().SetPassword(password)
  339. return a
  340. }
  341. // BasicAuthBytes sets URI username and password.
  342. func (a *Agent) BasicAuthBytes(username, password []byte) *Agent {
  343. a.req.URI().SetUsernameBytes(username)
  344. a.req.URI().SetPasswordBytes(password)
  345. return a
  346. }
  347. /************************** End URI Setting **************************/
  348. /************************** Request Setting **************************/
  349. // BodyString sets request body.
  350. func (a *Agent) BodyString(bodyString string) *Agent {
  351. a.req.SetBodyString(bodyString)
  352. return a
  353. }
  354. // Body sets request body.
  355. func (a *Agent) Body(body []byte) *Agent {
  356. a.req.SetBody(body)
  357. return a
  358. }
  359. // BodyStream sets request body stream and, optionally body size.
  360. //
  361. // If bodySize is >= 0, then the bodyStream must provide exactly bodySize bytes
  362. // before returning io.EOF.
  363. //
  364. // If bodySize < 0, then bodyStream is read until io.EOF.
  365. //
  366. // bodyStream.Close() is called after finishing reading all body data
  367. // if it implements io.Closer.
  368. //
  369. // Note that GET and HEAD requests cannot have body.
  370. func (a *Agent) BodyStream(bodyStream io.Reader, bodySize int) *Agent {
  371. a.req.SetBodyStream(bodyStream, bodySize)
  372. return a
  373. }
  374. // JSON sends a JSON request.
  375. func (a *Agent) JSON(v interface{}) *Agent {
  376. if a.jsonEncoder == nil {
  377. a.jsonEncoder = json.Marshal
  378. }
  379. a.req.Header.SetContentType(MIMEApplicationJSON)
  380. if body, err := a.jsonEncoder(v); err != nil {
  381. a.errs = append(a.errs, err)
  382. } else {
  383. a.req.SetBody(body)
  384. }
  385. return a
  386. }
  387. // XML sends an XML request.
  388. func (a *Agent) XML(v interface{}) *Agent {
  389. a.req.Header.SetContentType(MIMEApplicationXML)
  390. if body, err := xml.Marshal(v); err != nil {
  391. a.errs = append(a.errs, err)
  392. } else {
  393. a.req.SetBody(body)
  394. }
  395. return a
  396. }
  397. // Form sends form request with body if args is non-nil.
  398. //
  399. // It is recommended obtaining args via AcquireArgs and release it
  400. // manually in performance-critical code.
  401. func (a *Agent) Form(args *Args) *Agent {
  402. a.req.Header.SetContentType(MIMEApplicationForm)
  403. if args != nil {
  404. a.req.SetBody(args.QueryString())
  405. }
  406. return a
  407. }
  408. // FormFile represents multipart form file
  409. type FormFile struct {
  410. // Fieldname is form file's field name
  411. Fieldname string
  412. // Name is form file's name
  413. Name string
  414. // Content is form file's content
  415. Content []byte
  416. // autoRelease indicates if returns the object
  417. // acquired via AcquireFormFile to the pool.
  418. autoRelease bool
  419. }
  420. // FileData appends files for multipart form request.
  421. //
  422. // It is recommended obtaining formFile via AcquireFormFile and release it
  423. // manually in performance-critical code.
  424. func (a *Agent) FileData(formFiles ...*FormFile) *Agent {
  425. a.formFiles = append(a.formFiles, formFiles...)
  426. return a
  427. }
  428. // SendFile reads file and appends it to multipart form request.
  429. func (a *Agent) SendFile(filename string, fieldname ...string) *Agent {
  430. content, err := ioutil.ReadFile(filepath.Clean(filename))
  431. if err != nil {
  432. a.errs = append(a.errs, err)
  433. return a
  434. }
  435. ff := AcquireFormFile()
  436. if len(fieldname) > 0 && fieldname[0] != "" {
  437. ff.Fieldname = fieldname[0]
  438. } else {
  439. ff.Fieldname = "file" + strconv.Itoa(len(a.formFiles)+1)
  440. }
  441. ff.Name = filepath.Base(filename)
  442. ff.Content = append(ff.Content, content...)
  443. ff.autoRelease = true
  444. a.formFiles = append(a.formFiles, ff)
  445. return a
  446. }
  447. // SendFiles reads files and appends them to multipart form request.
  448. //
  449. // Examples:
  450. //
  451. // SendFile("/path/to/file1", "fieldname1", "/path/to/file2")
  452. func (a *Agent) SendFiles(filenamesAndFieldnames ...string) *Agent {
  453. pairs := len(filenamesAndFieldnames)
  454. if pairs&1 == 1 {
  455. filenamesAndFieldnames = append(filenamesAndFieldnames, "")
  456. }
  457. for i := 0; i < pairs; i += 2 {
  458. a.SendFile(filenamesAndFieldnames[i], filenamesAndFieldnames[i+1])
  459. }
  460. return a
  461. }
  462. // Boundary sets boundary for multipart form request.
  463. func (a *Agent) Boundary(boundary string) *Agent {
  464. a.boundary = boundary
  465. return a
  466. }
  467. // MultipartForm sends multipart form request with k-v and files.
  468. //
  469. // It is recommended obtaining args via AcquireArgs and release it
  470. // manually in performance-critical code.
  471. func (a *Agent) MultipartForm(args *Args) *Agent {
  472. if a.mw == nil {
  473. a.mw = multipart.NewWriter(a.req.BodyWriter())
  474. }
  475. if a.boundary != "" {
  476. if err := a.mw.SetBoundary(a.boundary); err != nil {
  477. a.errs = append(a.errs, err)
  478. return a
  479. }
  480. }
  481. a.req.Header.SetMultipartFormBoundary(a.mw.Boundary())
  482. if args != nil {
  483. args.VisitAll(func(key, value []byte) {
  484. if err := a.mw.WriteField(utils.UnsafeString(key), utils.UnsafeString(value)); err != nil {
  485. a.errs = append(a.errs, err)
  486. }
  487. })
  488. }
  489. for _, ff := range a.formFiles {
  490. w, err := a.mw.CreateFormFile(ff.Fieldname, ff.Name)
  491. if err != nil {
  492. a.errs = append(a.errs, err)
  493. continue
  494. }
  495. if _, err = w.Write(ff.Content); err != nil {
  496. a.errs = append(a.errs, err)
  497. }
  498. }
  499. if err := a.mw.Close(); err != nil {
  500. a.errs = append(a.errs, err)
  501. }
  502. return a
  503. }
  504. /************************** End Request Setting **************************/
  505. /************************** Agent Setting **************************/
  506. // Debug mode enables logging request and response detail
  507. func (a *Agent) Debug(w ...io.Writer) *Agent {
  508. a.debugWriter = os.Stdout
  509. if len(w) > 0 {
  510. a.debugWriter = w[0]
  511. }
  512. return a
  513. }
  514. // Timeout sets request timeout duration.
  515. func (a *Agent) Timeout(timeout time.Duration) *Agent {
  516. a.timeout = timeout
  517. return a
  518. }
  519. // Reuse enables the Agent instance to be used again after one request.
  520. //
  521. // If agent is reusable, then it should be released manually when it is no
  522. // longer used.
  523. func (a *Agent) Reuse() *Agent {
  524. a.reuse = true
  525. return a
  526. }
  527. // InsecureSkipVerify controls whether the Agent verifies the server
  528. // certificate chain and host name.
  529. func (a *Agent) InsecureSkipVerify() *Agent {
  530. if a.HostClient.TLSConfig == nil {
  531. /* #nosec G402 */
  532. a.HostClient.TLSConfig = &tls.Config{InsecureSkipVerify: true} // #nosec G402
  533. } else {
  534. /* #nosec G402 */
  535. a.HostClient.TLSConfig.InsecureSkipVerify = true
  536. }
  537. return a
  538. }
  539. // TLSConfig sets tls config.
  540. func (a *Agent) TLSConfig(config *tls.Config) *Agent {
  541. a.HostClient.TLSConfig = config
  542. return a
  543. }
  544. // MaxRedirectsCount sets max redirect count for GET and HEAD.
  545. func (a *Agent) MaxRedirectsCount(count int) *Agent {
  546. a.maxRedirectsCount = count
  547. return a
  548. }
  549. // JSONEncoder sets custom json encoder.
  550. func (a *Agent) JSONEncoder(jsonEncoder utils.JSONMarshal) *Agent {
  551. a.jsonEncoder = jsonEncoder
  552. return a
  553. }
  554. // JSONDecoder sets custom json decoder.
  555. func (a *Agent) JSONDecoder(jsonDecoder utils.JSONUnmarshal) *Agent {
  556. a.jsonDecoder = jsonDecoder
  557. return a
  558. }
  559. // Request returns Agent request instance.
  560. func (a *Agent) Request() *Request {
  561. return a.req
  562. }
  563. // SetResponse sets custom response for the Agent instance.
  564. //
  565. // It is recommended obtaining custom response via AcquireResponse and release it
  566. // manually in performance-critical code.
  567. func (a *Agent) SetResponse(customResp *Response) *Agent {
  568. a.resp = customResp
  569. return a
  570. }
  571. // Dest sets custom dest.
  572. //
  573. // The contents of dest will be replaced by the response body, if the dest
  574. // is too small a new slice will be allocated.
  575. func (a *Agent) Dest(dest []byte) *Agent {
  576. a.dest = dest
  577. return a
  578. }
  579. // RetryIf controls whether a retry should be attempted after an error.
  580. //
  581. // By default, will use isIdempotent function from fasthttp
  582. func (a *Agent) RetryIf(retryIf RetryIfFunc) *Agent {
  583. a.HostClient.RetryIf = retryIf
  584. return a
  585. }
  586. /************************** End Agent Setting **************************/
  587. // Bytes returns the status code, bytes body and errors of url.
  588. //
  589. // it's not safe to use Agent after calling [Agent.Bytes]
  590. func (a *Agent) Bytes() (code int, body []byte, errs []error) {
  591. defer a.release()
  592. return a.bytes()
  593. }
  594. func (a *Agent) bytes() (code int, body []byte, errs []error) {
  595. if errs = append(errs, a.errs...); len(errs) > 0 {
  596. return
  597. }
  598. var (
  599. req = a.req
  600. resp *Response
  601. nilResp bool
  602. )
  603. if a.resp == nil {
  604. resp = AcquireResponse()
  605. nilResp = true
  606. } else {
  607. resp = a.resp
  608. }
  609. defer func() {
  610. if a.debugWriter != nil {
  611. printDebugInfo(req, resp, a.debugWriter)
  612. }
  613. if len(errs) == 0 {
  614. code = resp.StatusCode()
  615. }
  616. body = append(a.dest, resp.Body()...)
  617. if nilResp {
  618. ReleaseResponse(resp)
  619. }
  620. }()
  621. if a.timeout > 0 {
  622. if err := a.HostClient.DoTimeout(req, resp, a.timeout); err != nil {
  623. errs = append(errs, err)
  624. return
  625. }
  626. } else if a.maxRedirectsCount > 0 && (string(req.Header.Method()) == MethodGet || string(req.Header.Method()) == MethodHead) {
  627. if err := a.HostClient.DoRedirects(req, resp, a.maxRedirectsCount); err != nil {
  628. errs = append(errs, err)
  629. return
  630. }
  631. } else if err := a.HostClient.Do(req, resp); err != nil {
  632. errs = append(errs, err)
  633. }
  634. return
  635. }
  636. func printDebugInfo(req *Request, resp *Response, w io.Writer) {
  637. msg := fmt.Sprintf("Connected to %s(%s)\r\n\r\n", req.URI().Host(), resp.RemoteAddr())
  638. _, _ = w.Write(utils.UnsafeBytes(msg))
  639. _, _ = req.WriteTo(w)
  640. _, _ = resp.WriteTo(w)
  641. }
  642. // String returns the status code, string body and errors of url.
  643. //
  644. // it's not safe to use Agent after calling [Agent.String]
  645. func (a *Agent) String() (int, string, []error) {
  646. defer a.release()
  647. code, body, errs := a.bytes()
  648. return code, utils.UnsafeString(body), errs
  649. }
  650. // Struct returns the status code, bytes body and errors of url.
  651. // And bytes body will be unmarshalled to given v.
  652. //
  653. // it's not safe to use Agent after calling [Agent.Struct]
  654. func (a *Agent) Struct(v interface{}) (code int, body []byte, errs []error) {
  655. defer a.release()
  656. if code, body, errs = a.bytes(); len(errs) > 0 {
  657. return
  658. }
  659. if a.jsonDecoder == nil {
  660. a.jsonDecoder = json.Unmarshal
  661. }
  662. if err := a.jsonDecoder(body, v); err != nil {
  663. errs = append(errs, err)
  664. }
  665. return
  666. }
  667. func (a *Agent) release() {
  668. if !a.reuse {
  669. ReleaseAgent(a)
  670. } else {
  671. a.errs = a.errs[:0]
  672. }
  673. }
  674. func (a *Agent) reset() {
  675. a.HostClient = nil
  676. a.req.Reset()
  677. a.resp = nil
  678. a.dest = nil
  679. a.timeout = 0
  680. a.args = nil
  681. a.errs = a.errs[:0]
  682. a.debugWriter = nil
  683. a.mw = nil
  684. a.reuse = false
  685. a.parsed = false
  686. a.maxRedirectsCount = 0
  687. a.boundary = ""
  688. a.Name = ""
  689. a.NoDefaultUserAgentHeader = false
  690. for i, ff := range a.formFiles {
  691. if ff.autoRelease {
  692. ReleaseFormFile(ff)
  693. }
  694. a.formFiles[i] = nil
  695. }
  696. a.formFiles = a.formFiles[:0]
  697. }
  698. var (
  699. clientPool sync.Pool
  700. agentPool = sync.Pool{
  701. New: func() interface{} {
  702. return &Agent{req: &Request{}}
  703. },
  704. }
  705. responsePool sync.Pool
  706. argsPool sync.Pool
  707. formFilePool sync.Pool
  708. )
  709. // AcquireClient returns an empty Client instance from client pool.
  710. //
  711. // The returned Client instance may be passed to ReleaseClient when it is
  712. // no longer needed. This allows Client recycling, reduces GC pressure
  713. // and usually improves performance.
  714. func AcquireClient() *Client {
  715. v := clientPool.Get()
  716. if v == nil {
  717. return &Client{}
  718. }
  719. return v.(*Client)
  720. }
  721. // ReleaseClient returns c acquired via AcquireClient to client pool.
  722. //
  723. // It is forbidden accessing req and/or its' members after returning
  724. // it to client pool.
  725. func ReleaseClient(c *Client) {
  726. c.UserAgent = ""
  727. c.NoDefaultUserAgentHeader = false
  728. c.JSONEncoder = nil
  729. c.JSONDecoder = nil
  730. clientPool.Put(c)
  731. }
  732. // AcquireAgent returns an empty Agent instance from Agent pool.
  733. //
  734. // The returned Agent instance may be passed to ReleaseAgent when it is
  735. // no longer needed. This allows Agent recycling, reduces GC pressure
  736. // and usually improves performance.
  737. func AcquireAgent() *Agent {
  738. return agentPool.Get().(*Agent)
  739. }
  740. // ReleaseAgent returns a acquired via AcquireAgent to Agent pool.
  741. //
  742. // It is forbidden accessing req and/or its' members after returning
  743. // it to Agent pool.
  744. func ReleaseAgent(a *Agent) {
  745. a.reset()
  746. agentPool.Put(a)
  747. }
  748. // AcquireResponse returns an empty Response instance from response pool.
  749. //
  750. // The returned Response instance may be passed to ReleaseResponse when it is
  751. // no longer needed. This allows Response recycling, reduces GC pressure
  752. // and usually improves performance.
  753. // Copy from fasthttp
  754. func AcquireResponse() *Response {
  755. v := responsePool.Get()
  756. if v == nil {
  757. return &Response{}
  758. }
  759. return v.(*Response)
  760. }
  761. // ReleaseResponse return resp acquired via AcquireResponse to response pool.
  762. //
  763. // It is forbidden accessing resp and/or its' members after returning
  764. // it to response pool.
  765. // Copy from fasthttp
  766. func ReleaseResponse(resp *Response) {
  767. resp.Reset()
  768. responsePool.Put(resp)
  769. }
  770. // AcquireArgs returns an empty Args object from the pool.
  771. //
  772. // The returned Args may be returned to the pool with ReleaseArgs
  773. // when no longer needed. This allows reducing GC load.
  774. // Copy from fasthttp
  775. func AcquireArgs() *Args {
  776. v := argsPool.Get()
  777. if v == nil {
  778. return &Args{}
  779. }
  780. return v.(*Args)
  781. }
  782. // ReleaseArgs returns the object acquired via AcquireArgs to the pool.
  783. //
  784. // String not access the released Args object, otherwise data races may occur.
  785. // Copy from fasthttp
  786. func ReleaseArgs(a *Args) {
  787. a.Reset()
  788. argsPool.Put(a)
  789. }
  790. // AcquireFormFile returns an empty FormFile object from the pool.
  791. //
  792. // The returned FormFile may be returned to the pool with ReleaseFormFile
  793. // when no longer needed. This allows reducing GC load.
  794. func AcquireFormFile() *FormFile {
  795. v := formFilePool.Get()
  796. if v == nil {
  797. return &FormFile{}
  798. }
  799. return v.(*FormFile)
  800. }
  801. // ReleaseFormFile returns the object acquired via AcquireFormFile to the pool.
  802. //
  803. // String not access the released FormFile object, otherwise data races may occur.
  804. func ReleaseFormFile(ff *FormFile) {
  805. ff.Fieldname = ""
  806. ff.Name = ""
  807. ff.Content = ff.Content[:0]
  808. ff.autoRelease = false
  809. formFilePool.Put(ff)
  810. }
  811. var (
  812. strHTTP = []byte("http")
  813. strHTTPS = []byte("https")
  814. defaultUserAgent = "fiber"
  815. )
  816. type multipartWriter interface {
  817. Boundary() string
  818. SetBoundary(boundary string) error
  819. CreateFormFile(fieldname, filename string) (io.Writer, error)
  820. WriteField(fieldname, value string) error
  821. Close() error
  822. }