client.go 25 KB

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