client.go 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087
  1. package fasthttp
  2. import (
  3. "bufio"
  4. "bytes"
  5. "crypto/tls"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "net"
  10. "strings"
  11. "sync"
  12. "sync/atomic"
  13. "time"
  14. )
  15. // Do performs the given http request and fills the given http response.
  16. //
  17. // Request must contain at least non-zero RequestURI with full url (including
  18. // scheme and host) or non-zero Host header + RequestURI.
  19. //
  20. // Client determines the server to be requested in the following order:
  21. //
  22. // - from RequestURI if it contains full url with scheme and host;
  23. // - from Host header otherwise.
  24. //
  25. // The function doesn't follow redirects. Use Get* for following redirects.
  26. //
  27. // Response is ignored if resp is nil.
  28. //
  29. // ErrNoFreeConns is returned if all DefaultMaxConnsPerHost connections
  30. // to the requested host are busy.
  31. //
  32. // It is recommended obtaining req and resp via AcquireRequest
  33. // and AcquireResponse in performance-critical code.
  34. func Do(req *Request, resp *Response) error {
  35. return defaultClient.Do(req, resp)
  36. }
  37. // DoTimeout performs the given request and waits for response during
  38. // the given timeout duration.
  39. //
  40. // Request must contain at least non-zero RequestURI with full url (including
  41. // scheme and host) or non-zero Host header + RequestURI.
  42. //
  43. // Client determines the server to be requested in the following order:
  44. //
  45. // - from RequestURI if it contains full url with scheme and host;
  46. // - from Host header otherwise.
  47. //
  48. // The function doesn't follow redirects. Use Get* for following redirects.
  49. //
  50. // Response is ignored if resp is nil.
  51. //
  52. // ErrTimeout is returned if the response wasn't returned during
  53. // the given timeout.
  54. //
  55. // ErrNoFreeConns is returned if all DefaultMaxConnsPerHost connections
  56. // to the requested host are busy.
  57. //
  58. // It is recommended obtaining req and resp via AcquireRequest
  59. // and AcquireResponse in performance-critical code.
  60. func DoTimeout(req *Request, resp *Response, timeout time.Duration) error {
  61. return defaultClient.DoTimeout(req, resp, timeout)
  62. }
  63. // DoDeadline performs the given request and waits for response until
  64. // the given deadline.
  65. //
  66. // Request must contain at least non-zero RequestURI with full url (including
  67. // scheme and host) or non-zero Host header + RequestURI.
  68. //
  69. // Client determines the server to be requested in the following order:
  70. //
  71. // - from RequestURI if it contains full url with scheme and host;
  72. // - from Host header otherwise.
  73. //
  74. // The function doesn't follow redirects. Use Get* for following redirects.
  75. //
  76. // Response is ignored if resp is nil.
  77. //
  78. // ErrTimeout is returned if the response wasn't returned until
  79. // the given deadline.
  80. //
  81. // ErrNoFreeConns is returned if all DefaultMaxConnsPerHost connections
  82. // to the requested host are busy.
  83. //
  84. // It is recommended obtaining req and resp via AcquireRequest
  85. // and AcquireResponse in performance-critical code.
  86. func DoDeadline(req *Request, resp *Response, deadline time.Time) error {
  87. return defaultClient.DoDeadline(req, resp, deadline)
  88. }
  89. // DoRedirects performs the given http request and fills the given http response,
  90. // following up to maxRedirectsCount redirects. When the redirect count exceeds
  91. // maxRedirectsCount, ErrTooManyRedirects is returned.
  92. //
  93. // Request must contain at least non-zero RequestURI with full url (including
  94. // scheme and host) or non-zero Host header + RequestURI.
  95. //
  96. // Client determines the server to be requested in the following order:
  97. //
  98. // - from RequestURI if it contains full url with scheme and host;
  99. // - from Host header otherwise.
  100. //
  101. // Response is ignored if resp is nil.
  102. //
  103. // ErrNoFreeConns is returned if all DefaultMaxConnsPerHost connections
  104. // to the requested host are busy.
  105. //
  106. // It is recommended obtaining req and resp via AcquireRequest
  107. // and AcquireResponse in performance-critical code.
  108. func DoRedirects(req *Request, resp *Response, maxRedirectsCount int) error {
  109. if defaultClient.DisablePathNormalizing {
  110. req.URI().DisablePathNormalizing = true
  111. }
  112. _, _, err := doRequestFollowRedirects(req, resp, req.URI().String(), maxRedirectsCount, &defaultClient)
  113. return err
  114. }
  115. // Get returns the status code and body of url.
  116. //
  117. // The contents of dst will be replaced by the body and returned, if the dst
  118. // is too small a new slice will be allocated.
  119. //
  120. // The function follows redirects. Use Do* for manually handling redirects.
  121. func Get(dst []byte, url string) (statusCode int, body []byte, err error) {
  122. return defaultClient.Get(dst, url)
  123. }
  124. // GetTimeout returns the status code and body of url.
  125. //
  126. // The contents of dst will be replaced by the body and returned, if the dst
  127. // is too small a new slice will be allocated.
  128. //
  129. // The function follows redirects. Use Do* for manually handling redirects.
  130. //
  131. // ErrTimeout error is returned if url contents couldn't be fetched
  132. // during the given timeout.
  133. func GetTimeout(dst []byte, url string, timeout time.Duration) (statusCode int, body []byte, err error) {
  134. return defaultClient.GetTimeout(dst, url, timeout)
  135. }
  136. // GetDeadline returns the status code and body of url.
  137. //
  138. // The contents of dst will be replaced by the body and returned, if the dst
  139. // is too small a new slice will be allocated.
  140. //
  141. // The function follows redirects. Use Do* for manually handling redirects.
  142. //
  143. // ErrTimeout error is returned if url contents couldn't be fetched
  144. // until the given deadline.
  145. func GetDeadline(dst []byte, url string, deadline time.Time) (statusCode int, body []byte, err error) {
  146. return defaultClient.GetDeadline(dst, url, deadline)
  147. }
  148. // Post sends POST request to the given url with the given POST arguments.
  149. //
  150. // The contents of dst will be replaced by the body and returned, if the dst
  151. // is too small a new slice will be allocated.
  152. //
  153. // The function follows redirects. Use Do* for manually handling redirects.
  154. //
  155. // Empty POST body is sent if postArgs is nil.
  156. func Post(dst []byte, url string, postArgs *Args) (statusCode int, body []byte, err error) {
  157. return defaultClient.Post(dst, url, postArgs)
  158. }
  159. var defaultClient Client
  160. // Client implements http client.
  161. //
  162. // Copying Client by value is prohibited. Create new instance instead.
  163. //
  164. // It is safe calling Client methods from concurrently running goroutines.
  165. //
  166. // The fields of a Client should not be changed while it is in use.
  167. type Client struct {
  168. noCopy noCopy
  169. readerPool sync.Pool
  170. writerPool sync.Pool
  171. // Transport defines a transport-like mechanism that wraps every request/response.
  172. Transport RoundTripper
  173. // Callback for establishing new connections to hosts.
  174. //
  175. // Default DialTimeout is used if not set.
  176. DialTimeout DialFuncWithTimeout
  177. // Callback for establishing new connections to hosts.
  178. //
  179. // Note that if Dial is set instead of DialTimeout, Dial will ignore Request timeout.
  180. // If you want the tcp dial process to account for request timeouts, use DialTimeout instead.
  181. //
  182. // If not set, DialTimeout is used.
  183. Dial DialFunc
  184. // TLS config for https connections.
  185. //
  186. // Default TLS config is used if not set.
  187. TLSConfig *tls.Config
  188. // RetryIf controls whether a retry should be attempted after an error.
  189. //
  190. // By default will use isIdempotent function.
  191. //
  192. // Deprecated: Use RetryIfErr instead.
  193. // This field is only effective when the `RetryIfErr` field is not set.
  194. RetryIf RetryIfFunc
  195. // When the client encounters an error during a request, the behavior—whether to retry
  196. // and whether to reset the request timeout—should be determined
  197. // based on the return value of this field.
  198. // This field is only effective within the range of MaxIdemponentCallAttempts.
  199. RetryIfErr RetryIfErrFunc
  200. // ConfigureClient configures the fasthttp.HostClient.
  201. ConfigureClient func(hc *HostClient) error
  202. m map[string]*HostClient
  203. ms map[string]*HostClient
  204. // Client name. Used in User-Agent request header.
  205. //
  206. // Default client name is used if not set.
  207. Name string
  208. // Maximum number of connections per each host which may be established.
  209. //
  210. // DefaultMaxConnsPerHost is used if not set.
  211. MaxConnsPerHost int
  212. // Idle keep-alive connections are closed after this duration.
  213. //
  214. // By default idle connections are closed
  215. // after DefaultMaxIdleConnDuration.
  216. MaxIdleConnDuration time.Duration
  217. // Keep-alive connections are closed after this duration.
  218. //
  219. // By default connection duration is unlimited.
  220. MaxConnDuration time.Duration
  221. // Maximum number of attempts for idempotent calls.
  222. //
  223. // DefaultMaxIdemponentCallAttempts is used if not set.
  224. MaxIdemponentCallAttempts int
  225. // Per-connection buffer size for responses' reading.
  226. // This also limits the maximum header size.
  227. //
  228. // Default buffer size is used if 0.
  229. ReadBufferSize int
  230. // Per-connection buffer size for requests' writing.
  231. //
  232. // Default buffer size is used if 0.
  233. WriteBufferSize int
  234. // Maximum duration for full response reading (including body).
  235. //
  236. // By default response read timeout is unlimited.
  237. ReadTimeout time.Duration
  238. // Maximum duration for full request writing (including body).
  239. //
  240. // By default request write timeout is unlimited.
  241. WriteTimeout time.Duration
  242. // Maximum response body size.
  243. //
  244. // The client returns ErrBodyTooLarge if this limit is greater than 0
  245. // and response body is greater than the limit.
  246. //
  247. // By default response body size is unlimited.
  248. MaxResponseBodySize int
  249. // Maximum duration for waiting for a free connection.
  250. //
  251. // By default will not waiting, return ErrNoFreeConns immediately.
  252. MaxConnWaitTimeout time.Duration
  253. // Connection pool strategy. Can be either LIFO or FIFO (default).
  254. ConnPoolStrategy ConnPoolStrategyType
  255. mLock sync.RWMutex
  256. mOnce sync.Once
  257. // NoDefaultUserAgentHeader when set to true, causes the default
  258. // User-Agent header to be excluded from the Request.
  259. NoDefaultUserAgentHeader bool
  260. // Attempt to connect to both ipv4 and ipv6 addresses if set to true.
  261. //
  262. // This option is used only if default TCP dialer is used,
  263. // i.e. if Dial is blank.
  264. //
  265. // By default client connects only to ipv4 addresses,
  266. // since unfortunately ipv6 remains broken in many networks worldwide :)
  267. DialDualStack bool
  268. // Header names are passed as-is without normalization
  269. // if this option is set.
  270. //
  271. // Disabled header names' normalization may be useful only for proxying
  272. // responses to other clients expecting case-sensitive
  273. // header names. See https://github.com/valyala/fasthttp/issues/57
  274. // for details.
  275. //
  276. // By default request and response header names are normalized, i.e.
  277. // The first letter and the first letters following dashes
  278. // are uppercased, while all the other letters are lowercased.
  279. // Examples:
  280. //
  281. // * HOST -> Host
  282. // * content-type -> Content-Type
  283. // * cONTENT-lenGTH -> Content-Length
  284. DisableHeaderNamesNormalizing bool
  285. // Path values are sent as-is without normalization.
  286. //
  287. // Disabled path normalization may be useful for proxying incoming requests
  288. // to servers that are expecting paths to be forwarded as-is.
  289. //
  290. // By default path values are normalized, i.e.
  291. // extra slashes are removed, special characters are encoded.
  292. DisablePathNormalizing bool
  293. // StreamResponseBody enables response body streaming.
  294. StreamResponseBody bool
  295. }
  296. // Get returns the status code and body of url.
  297. //
  298. // The contents of dst will be replaced by the body and returned, if the dst
  299. // is too small a new slice will be allocated.
  300. //
  301. // The function follows redirects. Use Do* for manually handling redirects.
  302. func (c *Client) Get(dst []byte, url string) (statusCode int, body []byte, err error) {
  303. return clientGetURL(dst, url, c)
  304. }
  305. // GetTimeout returns the status code and body of url.
  306. //
  307. // The contents of dst will be replaced by the body and returned, if the dst
  308. // is too small a new slice will be allocated.
  309. //
  310. // The function follows redirects. Use Do* for manually handling redirects.
  311. //
  312. // ErrTimeout error is returned if url contents couldn't be fetched
  313. // during the given timeout.
  314. func (c *Client) GetTimeout(dst []byte, url string, timeout time.Duration) (statusCode int, body []byte, err error) {
  315. return clientGetURLTimeout(dst, url, timeout, c)
  316. }
  317. // GetDeadline returns the status code and body of url.
  318. //
  319. // The contents of dst will be replaced by the body and returned, if the dst
  320. // is too small a new slice will be allocated.
  321. //
  322. // The function follows redirects. Use Do* for manually handling redirects.
  323. //
  324. // ErrTimeout error is returned if url contents couldn't be fetched
  325. // until the given deadline.
  326. func (c *Client) GetDeadline(dst []byte, url string, deadline time.Time) (statusCode int, body []byte, err error) {
  327. return clientGetURLDeadline(dst, url, deadline, c)
  328. }
  329. // Post sends POST request to the given url with the given POST arguments.
  330. //
  331. // The contents of dst will be replaced by the body and returned, if the dst
  332. // is too small a new slice will be allocated.
  333. //
  334. // The function follows redirects. Use Do* for manually handling redirects.
  335. //
  336. // Empty POST body is sent if postArgs is nil.
  337. func (c *Client) Post(dst []byte, url string, postArgs *Args) (statusCode int, body []byte, err error) {
  338. return clientPostURL(dst, url, postArgs, c)
  339. }
  340. // DoTimeout performs the given request and waits for response during
  341. // the given timeout duration.
  342. //
  343. // Request must contain at least non-zero RequestURI with full url (including
  344. // scheme and host) or non-zero Host header + RequestURI.
  345. //
  346. // Client determines the server to be requested in the following order:
  347. //
  348. // - from RequestURI if it contains full url with scheme and host;
  349. // - from Host header otherwise.
  350. //
  351. // The function doesn't follow redirects. Use Get* for following redirects.
  352. //
  353. // Response is ignored if resp is nil.
  354. //
  355. // ErrTimeout is returned if the response wasn't returned during
  356. // the given timeout.
  357. // Immediately returns ErrTimeout if timeout value is negative.
  358. //
  359. // ErrNoFreeConns is returned if all Client.MaxConnsPerHost connections
  360. // to the requested host are busy.
  361. //
  362. // It is recommended obtaining req and resp via AcquireRequest
  363. // and AcquireResponse in performance-critical code.
  364. func (c *Client) DoTimeout(req *Request, resp *Response, timeout time.Duration) error {
  365. req.timeout = timeout
  366. if req.timeout <= 0 {
  367. return ErrTimeout
  368. }
  369. return c.Do(req, resp)
  370. }
  371. // DoDeadline performs the given request and waits for response until
  372. // the given deadline.
  373. //
  374. // Request must contain at least non-zero RequestURI with full url (including
  375. // scheme and host) or non-zero Host header + RequestURI.
  376. //
  377. // Client determines the server to be requested in the following order:
  378. //
  379. // - from RequestURI if it contains full url with scheme and host;
  380. // - from Host header otherwise.
  381. //
  382. // The function doesn't follow redirects. Use Get* for following redirects.
  383. //
  384. // Response is ignored if resp is nil.
  385. //
  386. // ErrTimeout is returned if the response wasn't returned until
  387. // the given deadline.
  388. // Immediately returns ErrTimeout if the deadline has already been reached.
  389. //
  390. // ErrNoFreeConns is returned if all Client.MaxConnsPerHost connections
  391. // to the requested host are busy.
  392. //
  393. // It is recommended obtaining req and resp via AcquireRequest
  394. // and AcquireResponse in performance-critical code.
  395. func (c *Client) DoDeadline(req *Request, resp *Response, deadline time.Time) error {
  396. req.timeout = time.Until(deadline)
  397. if req.timeout <= 0 {
  398. return ErrTimeout
  399. }
  400. return c.Do(req, resp)
  401. }
  402. // DoRedirects performs the given http request and fills the given http response,
  403. // following up to maxRedirectsCount redirects. When the redirect count exceeds
  404. // maxRedirectsCount, ErrTooManyRedirects is returned.
  405. //
  406. // Request must contain at least non-zero RequestURI with full url (including
  407. // scheme and host) or non-zero Host header + RequestURI.
  408. //
  409. // Client determines the server to be requested in the following order:
  410. //
  411. // - from RequestURI if it contains full url with scheme and host;
  412. // - from Host header otherwise.
  413. //
  414. // Response is ignored if resp is nil.
  415. //
  416. // ErrNoFreeConns is returned if all DefaultMaxConnsPerHost connections
  417. // to the requested host are busy.
  418. //
  419. // It is recommended obtaining req and resp via AcquireRequest
  420. // and AcquireResponse in performance-critical code.
  421. func (c *Client) DoRedirects(req *Request, resp *Response, maxRedirectsCount int) error {
  422. if c.DisablePathNormalizing {
  423. req.URI().DisablePathNormalizing = true
  424. }
  425. _, _, err := doRequestFollowRedirects(req, resp, req.URI().String(), maxRedirectsCount, c)
  426. return err
  427. }
  428. // Do performs the given http request and fills the given http response.
  429. //
  430. // Request must contain at least non-zero RequestURI with full url (including
  431. // scheme and host) or non-zero Host header + RequestURI.
  432. //
  433. // Client determines the server to be requested in the following order:
  434. //
  435. // - from RequestURI if it contains full url with scheme and host;
  436. // - from Host header otherwise.
  437. //
  438. // Response is ignored if resp is nil.
  439. //
  440. // The function doesn't follow redirects. Use Get* for following redirects.
  441. //
  442. // ErrNoFreeConns is returned if all Client.MaxConnsPerHost connections
  443. // to the requested host are busy.
  444. //
  445. // It is recommended obtaining req and resp via AcquireRequest
  446. // and AcquireResponse in performance-critical code.
  447. func (c *Client) Do(req *Request, resp *Response) error {
  448. uri := req.URI()
  449. if uri == nil {
  450. return ErrorInvalidURI
  451. }
  452. host := uri.Host()
  453. if bytes.ContainsRune(host, ',') {
  454. return fmt.Errorf("invalid host %q. Use HostClient for multiple hosts", host)
  455. }
  456. isTLS := false
  457. if uri.isHTTPS() {
  458. isTLS = true
  459. } else if !uri.isHTTP() {
  460. return fmt.Errorf("unsupported protocol %q. http and https are supported", uri.Scheme())
  461. }
  462. c.mOnce.Do(func() {
  463. c.m = make(map[string]*HostClient)
  464. c.ms = make(map[string]*HostClient)
  465. })
  466. hc, err := c.hostClient(host, isTLS)
  467. if err != nil {
  468. return err
  469. }
  470. atomic.AddInt32(&hc.pendingClientRequests, 1)
  471. defer atomic.AddInt32(&hc.pendingClientRequests, -1)
  472. return hc.Do(req, resp)
  473. }
  474. func (c *Client) hostClient(host []byte, isTLS bool) (*HostClient, error) {
  475. m := c.m
  476. if isTLS {
  477. m = c.ms
  478. }
  479. c.mLock.RLock()
  480. hc, exist := m[string(host)]
  481. c.mLock.RUnlock()
  482. if exist {
  483. return hc, nil
  484. }
  485. c.mLock.Lock()
  486. defer c.mLock.Unlock()
  487. hc, exist = m[string(host)]
  488. if exist {
  489. return hc, nil
  490. }
  491. hc = &HostClient{
  492. Addr: AddMissingPort(string(host), isTLS),
  493. Transport: c.Transport,
  494. Name: c.Name,
  495. NoDefaultUserAgentHeader: c.NoDefaultUserAgentHeader,
  496. Dial: c.Dial,
  497. DialTimeout: c.DialTimeout,
  498. DialDualStack: c.DialDualStack,
  499. IsTLS: isTLS,
  500. TLSConfig: c.TLSConfig,
  501. MaxConns: c.MaxConnsPerHost,
  502. MaxIdleConnDuration: c.MaxIdleConnDuration,
  503. MaxConnDuration: c.MaxConnDuration,
  504. MaxIdemponentCallAttempts: c.MaxIdemponentCallAttempts,
  505. ReadBufferSize: c.ReadBufferSize,
  506. WriteBufferSize: c.WriteBufferSize,
  507. ReadTimeout: c.ReadTimeout,
  508. WriteTimeout: c.WriteTimeout,
  509. MaxResponseBodySize: c.MaxResponseBodySize,
  510. DisableHeaderNamesNormalizing: c.DisableHeaderNamesNormalizing,
  511. DisablePathNormalizing: c.DisablePathNormalizing,
  512. MaxConnWaitTimeout: c.MaxConnWaitTimeout,
  513. RetryIf: c.RetryIf,
  514. RetryIfErr: c.RetryIfErr,
  515. ConnPoolStrategy: c.ConnPoolStrategy,
  516. StreamResponseBody: c.StreamResponseBody,
  517. clientReaderPool: &c.readerPool,
  518. clientWriterPool: &c.writerPool,
  519. }
  520. if c.ConfigureClient != nil {
  521. if err := c.ConfigureClient(hc); err != nil {
  522. return nil, err
  523. }
  524. }
  525. m[string(host)] = hc
  526. if len(m) == 1 {
  527. go c.mCleaner(m)
  528. }
  529. return hc, nil
  530. }
  531. // CloseIdleConnections closes any connections which were previously
  532. // connected from previous requests but are now sitting idle in a
  533. // "keep-alive" state. It does not interrupt any connections currently
  534. // in use.
  535. func (c *Client) CloseIdleConnections() {
  536. c.mLock.RLock()
  537. for _, v := range c.m {
  538. v.CloseIdleConnections()
  539. }
  540. for _, v := range c.ms {
  541. v.CloseIdleConnections()
  542. }
  543. c.mLock.RUnlock()
  544. }
  545. func (c *Client) mCleaner(m map[string]*HostClient) {
  546. mustStop := false
  547. sleep := c.MaxIdleConnDuration
  548. if sleep < time.Second {
  549. sleep = time.Second
  550. } else if sleep > 10*time.Second {
  551. sleep = 10 * time.Second
  552. }
  553. for {
  554. time.Sleep(sleep)
  555. c.mLock.Lock()
  556. for k, v := range m {
  557. v.connsLock.Lock()
  558. if v.connsCount == 0 && atomic.LoadInt32(&v.pendingClientRequests) == 0 {
  559. delete(m, k)
  560. }
  561. v.connsLock.Unlock()
  562. }
  563. if len(m) == 0 {
  564. mustStop = true
  565. }
  566. c.mLock.Unlock()
  567. if mustStop {
  568. break
  569. }
  570. }
  571. }
  572. // DefaultMaxConnsPerHost is the maximum number of concurrent connections
  573. // http client may establish per host by default (i.e. if
  574. // Client.MaxConnsPerHost isn't set).
  575. const DefaultMaxConnsPerHost = 512
  576. // DefaultMaxIdleConnDuration is the default duration before idle keep-alive
  577. // connection is closed.
  578. const DefaultMaxIdleConnDuration = 10 * time.Second
  579. // DefaultMaxIdemponentCallAttempts is the default idempotent calls attempts count.
  580. const DefaultMaxIdemponentCallAttempts = 5
  581. // DialFunc must establish connection to addr.
  582. //
  583. // There is no need in establishing TLS (SSL) connection for https.
  584. // The client automatically converts connection to TLS
  585. // if HostClient.IsTLS is set.
  586. //
  587. // TCP address passed to DialFunc always contains host and port.
  588. // Example TCP addr values:
  589. //
  590. // - foobar.com:80
  591. // - foobar.com:443
  592. // - foobar.com:8080
  593. type DialFunc func(addr string) (net.Conn, error)
  594. // DialFuncWithTimeout must establish connection to addr.
  595. // Unlike DialFunc, it also accepts a timeout.
  596. //
  597. // There is no need in establishing TLS (SSL) connection for https.
  598. // The client automatically converts connection to TLS
  599. // if HostClient.IsTLS is set.
  600. //
  601. // TCP address passed to DialFuncWithTimeout always contains host and port.
  602. // Example TCP addr values:
  603. //
  604. // - foobar.com:80
  605. // - foobar.com:443
  606. // - foobar.com:8080
  607. type DialFuncWithTimeout func(addr string, timeout time.Duration) (net.Conn, error)
  608. // RetryIfFunc defines the signature of the retry if function.
  609. // Request argument passed to RetryIfFunc, if there are any request errors.
  610. type RetryIfFunc func(request *Request) bool
  611. // RetryIfErrFunc defines an interface used for implementing the following functionality:
  612. // When the client encounters an error during a request, the behavior—whether to retry
  613. // and whether to reset the request timeout—should be determined
  614. // based on the return value of this interface.
  615. //
  616. // attempt indicates which attempt the current retry is due to a failure of.
  617. // The first request counts as the first attempt.
  618. //
  619. // err represents the error encountered while attempting the `attempts`-th request.
  620. //
  621. // resetTimeout indicates whether to reuse the `Request`'s timeout as the timeout interval,
  622. // rather than using the timeout after subtracting the time spent on previous failed requests.
  623. // This return value is meaningful only when you use `Request.SetTimeout`, `DoTimeout`, or `DoDeadline`.
  624. //
  625. // retry indicates whether to retry the current request. If it is false,
  626. // the request function will immediately return with the `err`.
  627. type RetryIfErrFunc func(request *Request, attempts int, err error) (resetTimeout bool, retry bool)
  628. // RoundTripper wraps every request/response.
  629. type RoundTripper interface {
  630. RoundTrip(hc *HostClient, req *Request, resp *Response) (retry bool, err error)
  631. }
  632. // ConnPoolStrategyType define strategy of connection pool enqueue/dequeue.
  633. type ConnPoolStrategyType int
  634. const (
  635. FIFO ConnPoolStrategyType = iota
  636. LIFO
  637. )
  638. // HostClient balances http requests among hosts listed in Addr.
  639. //
  640. // HostClient may be used for balancing load among multiple upstream hosts.
  641. // While multiple addresses passed to HostClient.Addr may be used for balancing
  642. // load among them, it would be better using LBClient instead, since HostClient
  643. // may unevenly balance load among upstream hosts.
  644. //
  645. // It is forbidden copying HostClient instances. Create new instances instead.
  646. //
  647. // It is safe calling HostClient methods from concurrently running goroutines.
  648. type HostClient struct {
  649. noCopy noCopy
  650. readerPool sync.Pool
  651. writerPool sync.Pool
  652. // Transport defines a transport-like mechanism that wraps every request/response.
  653. Transport RoundTripper
  654. // Callback for establishing new connections to hosts.
  655. //
  656. // Default DialTimeout is used if not set.
  657. DialTimeout DialFuncWithTimeout
  658. // Callback for establishing new connections to hosts.
  659. //
  660. // Note that if Dial is set instead of DialTimeout, Dial will ignore Request timeout.
  661. // If you want the tcp dial process to account for request timeouts, use DialTimeout instead.
  662. //
  663. // If not set, DialTimeout is used.
  664. Dial DialFunc
  665. // Optional TLS config.
  666. TLSConfig *tls.Config
  667. // RetryIf controls whether a retry should be attempted after an error.
  668. // By default, it uses the isIdempotent function.
  669. //
  670. // Deprecated: Use RetryIfErr instead.
  671. // This field is only effective when the `RetryIfErr` field is not set.
  672. RetryIf RetryIfFunc
  673. // When the client encounters an error during a request, the behavior—whether to retry
  674. // and whether to reset the request timeout—should be determined
  675. // based on the return value of this field.
  676. // This field is only effective within the range of MaxIdemponentCallAttempts.
  677. RetryIfErr RetryIfErrFunc
  678. connsWait *wantConnQueue
  679. tlsConfigMap map[string]*tls.Config
  680. clientReaderPool *sync.Pool
  681. clientWriterPool *sync.Pool
  682. // Comma-separated list of upstream HTTP server host addresses,
  683. // which are passed to Dial or DialTimeout in a round-robin manner.
  684. //
  685. // Each address may contain port if default dialer is used.
  686. // For example,
  687. //
  688. // - foobar.com:80
  689. // - foobar.com:443
  690. // - foobar.com:8080
  691. Addr string
  692. // Client name. Used in User-Agent request header.
  693. Name string
  694. conns []*clientConn
  695. addrs []string
  696. // Maximum number of connections which may be established to all hosts
  697. // listed in Addr.
  698. //
  699. // You can change this value while the HostClient is being used
  700. // with HostClient.SetMaxConns(value)
  701. //
  702. // DefaultMaxConnsPerHost is used if not set.
  703. MaxConns int
  704. // Keep-alive connections are closed after this duration.
  705. //
  706. // By default connection duration is unlimited.
  707. MaxConnDuration time.Duration
  708. // Idle keep-alive connections are closed after this duration.
  709. //
  710. // By default idle connections are closed
  711. // after DefaultMaxIdleConnDuration.
  712. MaxIdleConnDuration time.Duration
  713. // Maximum number of attempts for idempotent calls.
  714. //
  715. // A value of 0 or a negative value represents using DefaultMaxIdemponentCallAttempts.
  716. // For example, a value of 1 means the request will be executed only once,
  717. // while 2 means the request will be executed at most twice.
  718. // The RetryIfErr and RetryIf fields can invalidate remaining attempts.
  719. MaxIdemponentCallAttempts int
  720. // Per-connection buffer size for responses' reading.
  721. // This also limits the maximum header size.
  722. //
  723. // Default buffer size is used if 0.
  724. ReadBufferSize int
  725. // Per-connection buffer size for requests' writing.
  726. //
  727. // Default buffer size is used if 0.
  728. WriteBufferSize int
  729. // Maximum duration for full response reading (including body).
  730. //
  731. // By default response read timeout is unlimited.
  732. ReadTimeout time.Duration
  733. // Maximum duration for full request writing (including body).
  734. //
  735. // By default request write timeout is unlimited.
  736. WriteTimeout time.Duration
  737. // Maximum response body size.
  738. //
  739. // The client returns ErrBodyTooLarge if this limit is greater than 0
  740. // and response body is greater than the limit.
  741. //
  742. // By default response body size is unlimited.
  743. MaxResponseBodySize int
  744. // Maximum duration for waiting for a free connection.
  745. //
  746. // By default will not waiting, return ErrNoFreeConns immediately
  747. MaxConnWaitTimeout time.Duration
  748. // Connection pool strategy. Can be either LIFO or FIFO (default).
  749. ConnPoolStrategy ConnPoolStrategyType
  750. connsCount int
  751. connsLock sync.Mutex
  752. addrsLock sync.Mutex
  753. tlsConfigMapLock sync.Mutex
  754. addrIdx uint32
  755. lastUseTime uint32
  756. pendingRequests int32
  757. // pendingClientRequests counts the number of requests that a Client is currently running using this HostClient.
  758. // It will be incremented earlier than pendingRequests and will be used by Client to see if the HostClient is still in use.
  759. pendingClientRequests int32
  760. // NoDefaultUserAgentHeader when set to true, causes the default
  761. // User-Agent header to be excluded from the Request.
  762. NoDefaultUserAgentHeader bool
  763. // Attempt to connect to both ipv4 and ipv6 host addresses
  764. // if set to true.
  765. //
  766. // This option is used only if default TCP dialer is used,
  767. // i.e. if Dial and DialTimeout are blank.
  768. //
  769. // By default client connects only to ipv4 addresses,
  770. // since unfortunately ipv6 remains broken in many networks worldwide :)
  771. DialDualStack bool
  772. // Whether to use TLS (aka SSL or HTTPS) for host connections.
  773. IsTLS bool
  774. // Header names are passed as-is without normalization
  775. // if this option is set.
  776. //
  777. // Disabled header names' normalization may be useful only for proxying
  778. // responses to other clients expecting case-sensitive
  779. // header names. See https://github.com/valyala/fasthttp/issues/57
  780. // for details.
  781. //
  782. // By default request and response header names are normalized, i.e.
  783. // The first letter and the first letters following dashes
  784. // are uppercased, while all the other letters are lowercased.
  785. // Examples:
  786. //
  787. // * HOST -> Host
  788. // * content-type -> Content-Type
  789. // * cONTENT-lenGTH -> Content-Length
  790. DisableHeaderNamesNormalizing bool
  791. // Path values are sent as-is without normalization.
  792. //
  793. // Disabled path normalization may be useful for proxying incoming requests
  794. // to servers that are expecting paths to be forwarded as-is.
  795. //
  796. // By default path values are normalized, i.e.
  797. // extra slashes are removed, special characters are encoded.
  798. DisablePathNormalizing bool
  799. // Will not log potentially sensitive content in error logs.
  800. //
  801. // This option is useful for servers that handle sensitive data
  802. // in the request/response.
  803. //
  804. // Client logs full errors by default.
  805. SecureErrorLogMessage bool
  806. // StreamResponseBody enables response body streaming.
  807. StreamResponseBody bool
  808. connsCleanerRun bool
  809. }
  810. type clientConn struct {
  811. c net.Conn
  812. createdTime time.Time
  813. lastUseTime time.Time
  814. }
  815. // CreatedTime returns net.Conn the client.
  816. func (cc *clientConn) Conn() net.Conn {
  817. return cc.c
  818. }
  819. // CreatedTime returns time the client was created.
  820. func (cc *clientConn) CreatedTime() time.Time {
  821. return cc.createdTime
  822. }
  823. // LastUseTime returns time the client was last used.
  824. func (cc *clientConn) LastUseTime() time.Time {
  825. return cc.lastUseTime
  826. }
  827. var startTimeUnix = time.Now().Unix()
  828. // LastUseTime returns time the client was last used.
  829. func (c *HostClient) LastUseTime() time.Time {
  830. n := atomic.LoadUint32(&c.lastUseTime)
  831. return time.Unix(startTimeUnix+int64(n), 0)
  832. }
  833. // Get returns the status code and body of url.
  834. //
  835. // The contents of dst will be replaced by the body and returned, if the dst
  836. // is too small a new slice will be allocated.
  837. //
  838. // The function follows redirects. Use Do* for manually handling redirects.
  839. func (c *HostClient) Get(dst []byte, url string) (statusCode int, body []byte, err error) {
  840. return clientGetURL(dst, url, c)
  841. }
  842. // GetTimeout returns the status code and body of url.
  843. //
  844. // The contents of dst will be replaced by the body and returned, if the dst
  845. // is too small a new slice will be allocated.
  846. //
  847. // The function follows redirects. Use Do* for manually handling redirects.
  848. //
  849. // ErrTimeout error is returned if url contents couldn't be fetched
  850. // during the given timeout.
  851. func (c *HostClient) GetTimeout(dst []byte, url string, timeout time.Duration) (statusCode int, body []byte, err error) {
  852. return clientGetURLTimeout(dst, url, timeout, c)
  853. }
  854. // GetDeadline returns the status code and body of url.
  855. //
  856. // The contents of dst will be replaced by the body and returned, if the dst
  857. // is too small a new slice will be allocated.
  858. //
  859. // The function follows redirects. Use Do* for manually handling redirects.
  860. //
  861. // ErrTimeout error is returned if url contents couldn't be fetched
  862. // until the given deadline.
  863. func (c *HostClient) GetDeadline(dst []byte, url string, deadline time.Time) (statusCode int, body []byte, err error) {
  864. return clientGetURLDeadline(dst, url, deadline, c)
  865. }
  866. // Post sends POST request to the given url with the given POST arguments.
  867. //
  868. // The contents of dst will be replaced by the body and returned, if the dst
  869. // is too small a new slice will be allocated.
  870. //
  871. // The function follows redirects. Use Do* for manually handling redirects.
  872. //
  873. // Empty POST body is sent if postArgs is nil.
  874. func (c *HostClient) Post(dst []byte, url string, postArgs *Args) (statusCode int, body []byte, err error) {
  875. return clientPostURL(dst, url, postArgs, c)
  876. }
  877. type clientDoer interface {
  878. Do(req *Request, resp *Response) error
  879. }
  880. func clientGetURL(dst []byte, url string, c clientDoer) (statusCode int, body []byte, err error) {
  881. req := AcquireRequest()
  882. statusCode, body, err = doRequestFollowRedirectsBuffer(req, dst, url, c)
  883. ReleaseRequest(req)
  884. return statusCode, body, err
  885. }
  886. func clientGetURLTimeout(dst []byte, url string, timeout time.Duration, c clientDoer) (statusCode int, body []byte, err error) {
  887. deadline := time.Now().Add(timeout)
  888. return clientGetURLDeadline(dst, url, deadline, c)
  889. }
  890. type clientURLResponse struct {
  891. err error
  892. body []byte
  893. statusCode int
  894. }
  895. func clientGetURLDeadline(dst []byte, url string, deadline time.Time, c clientDoer) (statusCode int, body []byte, err error) {
  896. timeout := time.Until(deadline)
  897. if timeout <= 0 {
  898. return 0, dst, ErrTimeout
  899. }
  900. var ch chan clientURLResponse
  901. chv := clientURLResponseChPool.Get()
  902. if chv == nil {
  903. chv = make(chan clientURLResponse, 1)
  904. }
  905. ch = chv.(chan clientURLResponse)
  906. // Note that the request continues execution on ErrTimeout until
  907. // client-specific ReadTimeout exceeds. This helps limiting load
  908. // on slow hosts by MaxConns* concurrent requests.
  909. //
  910. // Without this 'hack' the load on slow host could exceed MaxConns*
  911. // concurrent requests, since timed out requests on client side
  912. // usually continue execution on the host.
  913. var mu sync.Mutex
  914. var timedout, responded bool
  915. go func() {
  916. req := AcquireRequest()
  917. statusCodeCopy, bodyCopy, errCopy := doRequestFollowRedirectsBuffer(req, dst, url, c)
  918. mu.Lock()
  919. if !timedout {
  920. ch <- clientURLResponse{
  921. statusCode: statusCodeCopy,
  922. body: bodyCopy,
  923. err: errCopy,
  924. }
  925. responded = true
  926. }
  927. mu.Unlock()
  928. ReleaseRequest(req)
  929. }()
  930. tc := AcquireTimer(timeout)
  931. select {
  932. case resp := <-ch:
  933. statusCode = resp.statusCode
  934. body = resp.body
  935. err = resp.err
  936. case <-tc.C:
  937. mu.Lock()
  938. if responded {
  939. resp := <-ch
  940. statusCode = resp.statusCode
  941. body = resp.body
  942. err = resp.err
  943. } else {
  944. timedout = true
  945. err = ErrTimeout
  946. body = dst
  947. }
  948. mu.Unlock()
  949. }
  950. ReleaseTimer(tc)
  951. clientURLResponseChPool.Put(chv)
  952. return statusCode, body, err
  953. }
  954. var clientURLResponseChPool sync.Pool
  955. func clientPostURL(dst []byte, url string, postArgs *Args, c clientDoer) (statusCode int, body []byte, err error) {
  956. req := AcquireRequest()
  957. defer ReleaseRequest(req)
  958. req.Header.SetMethod(MethodPost)
  959. req.Header.SetContentTypeBytes(strPostArgsContentType)
  960. if postArgs != nil {
  961. if _, err := postArgs.WriteTo(req.BodyWriter()); err != nil {
  962. return 0, nil, err
  963. }
  964. }
  965. statusCode, body, err = doRequestFollowRedirectsBuffer(req, dst, url, c)
  966. return statusCode, body, err
  967. }
  968. var (
  969. // ErrMissingLocation is returned by clients when the Location header is missing on
  970. // an HTTP response with a redirect status code.
  971. ErrMissingLocation = errors.New("missing Location header for http redirect")
  972. // ErrTooManyRedirects is returned by clients when the number of redirects followed
  973. // exceed the max count.
  974. ErrTooManyRedirects = errors.New("too many redirects detected when doing the request")
  975. // HostClients are only able to follow redirects to the same protocol.
  976. ErrHostClientRedirectToDifferentScheme = errors.New("HostClient can't follow redirects to a different protocol," +
  977. " please use Client instead")
  978. )
  979. const defaultMaxRedirectsCount = 16
  980. func doRequestFollowRedirectsBuffer(req *Request, dst []byte, url string, c clientDoer) (statusCode int, body []byte, err error) {
  981. resp := AcquireResponse()
  982. bodyBuf := resp.bodyBuffer()
  983. resp.keepBodyBuffer = true
  984. oldBody := bodyBuf.B
  985. bodyBuf.B = dst
  986. statusCode, _, err = doRequestFollowRedirects(req, resp, url, defaultMaxRedirectsCount, c)
  987. body = bodyBuf.B
  988. bodyBuf.B = oldBody
  989. resp.keepBodyBuffer = false
  990. ReleaseResponse(resp)
  991. return statusCode, body, err
  992. }
  993. func doRequestFollowRedirects(
  994. req *Request, resp *Response, url string, maxRedirectsCount int, c clientDoer,
  995. ) (statusCode int, body []byte, err error) {
  996. redirectsCount := 0
  997. for {
  998. req.SetRequestURI(url)
  999. if err := req.parseURI(); err != nil {
  1000. return 0, nil, err
  1001. }
  1002. if err = c.Do(req, resp); err != nil {
  1003. break
  1004. }
  1005. statusCode = resp.Header.StatusCode()
  1006. if !StatusCodeIsRedirect(statusCode) {
  1007. break
  1008. }
  1009. redirectsCount++
  1010. if redirectsCount > maxRedirectsCount {
  1011. err = ErrTooManyRedirects
  1012. break
  1013. }
  1014. location := resp.Header.peek(strLocation)
  1015. if len(location) == 0 {
  1016. err = ErrMissingLocation
  1017. break
  1018. }
  1019. url = getRedirectURL(url, location, req.DisableRedirectPathNormalizing)
  1020. if string(req.Header.Method()) == "POST" && (statusCode == 301 || statusCode == 302) {
  1021. req.Header.SetMethod(MethodGet)
  1022. }
  1023. }
  1024. return statusCode, body, err
  1025. }
  1026. func getRedirectURL(baseURL string, location []byte, disablePathNormalizing bool) string {
  1027. u := AcquireURI()
  1028. u.Update(baseURL)
  1029. u.UpdateBytes(location)
  1030. u.DisablePathNormalizing = disablePathNormalizing
  1031. redirectURL := u.String()
  1032. ReleaseURI(u)
  1033. return redirectURL
  1034. }
  1035. // StatusCodeIsRedirect returns true if the status code indicates a redirect.
  1036. func StatusCodeIsRedirect(statusCode int) bool {
  1037. return statusCode == StatusMovedPermanently ||
  1038. statusCode == StatusFound ||
  1039. statusCode == StatusSeeOther ||
  1040. statusCode == StatusTemporaryRedirect ||
  1041. statusCode == StatusPermanentRedirect
  1042. }
  1043. var (
  1044. requestPool sync.Pool
  1045. responsePool sync.Pool
  1046. )
  1047. // AcquireRequest returns an empty Request instance from request pool.
  1048. //
  1049. // The returned Request instance may be passed to ReleaseRequest when it is
  1050. // no longer needed. This allows Request recycling, reduces GC pressure
  1051. // and usually improves performance.
  1052. func AcquireRequest() *Request {
  1053. v := requestPool.Get()
  1054. if v == nil {
  1055. return &Request{}
  1056. }
  1057. return v.(*Request)
  1058. }
  1059. // ReleaseRequest returns req acquired via AcquireRequest to request pool.
  1060. //
  1061. // It is forbidden accessing req and/or its' members after returning
  1062. // it to request pool.
  1063. func ReleaseRequest(req *Request) {
  1064. req.Reset()
  1065. requestPool.Put(req)
  1066. }
  1067. // AcquireResponse returns an empty Response instance from response pool.
  1068. //
  1069. // The returned Response instance may be passed to ReleaseResponse when it is
  1070. // no longer needed. This allows Response recycling, reduces GC pressure
  1071. // and usually improves performance.
  1072. func AcquireResponse() *Response {
  1073. v := responsePool.Get()
  1074. if v == nil {
  1075. return &Response{}
  1076. }
  1077. return v.(*Response)
  1078. }
  1079. // ReleaseResponse return resp acquired via AcquireResponse to response pool.
  1080. //
  1081. // It is forbidden accessing resp and/or its' members after returning
  1082. // it to response pool.
  1083. func ReleaseResponse(resp *Response) {
  1084. resp.Reset()
  1085. responsePool.Put(resp)
  1086. }
  1087. // DoTimeout performs the given request and waits for response during
  1088. // the given timeout duration.
  1089. //
  1090. // Request must contain at least non-zero RequestURI with full url (including
  1091. // scheme and host) or non-zero Host header + RequestURI.
  1092. //
  1093. // The function doesn't follow redirects. Use Get* for following redirects.
  1094. //
  1095. // Response is ignored if resp is nil.
  1096. //
  1097. // ErrTimeout is returned if the response wasn't returned during
  1098. // the given timeout.
  1099. // Immediately returns ErrTimeout if timeout value is negative.
  1100. //
  1101. // ErrNoFreeConns is returned if all HostClient.MaxConns connections
  1102. // to the host are busy.
  1103. //
  1104. // It is recommended obtaining req and resp via AcquireRequest
  1105. // and AcquireResponse in performance-critical code.
  1106. func (c *HostClient) DoTimeout(req *Request, resp *Response, timeout time.Duration) error {
  1107. req.timeout = timeout
  1108. if req.timeout <= 0 {
  1109. return ErrTimeout
  1110. }
  1111. return c.Do(req, resp)
  1112. }
  1113. // DoDeadline performs the given request and waits for response until
  1114. // the given deadline.
  1115. //
  1116. // Request must contain at least non-zero RequestURI with full url (including
  1117. // scheme and host) or non-zero Host header + RequestURI.
  1118. //
  1119. // The function doesn't follow redirects. Use Get* for following redirects.
  1120. //
  1121. // Response is ignored if resp is nil.
  1122. //
  1123. // ErrTimeout is returned if the response wasn't returned until
  1124. // the given deadline.
  1125. // Immediately returns ErrTimeout if the deadline has already been reached.
  1126. //
  1127. // ErrNoFreeConns is returned if all HostClient.MaxConns connections
  1128. // to the host are busy.
  1129. //
  1130. // It is recommended obtaining req and resp via AcquireRequest
  1131. // and AcquireResponse in performance-critical code.
  1132. func (c *HostClient) DoDeadline(req *Request, resp *Response, deadline time.Time) error {
  1133. req.timeout = time.Until(deadline)
  1134. if req.timeout <= 0 {
  1135. return ErrTimeout
  1136. }
  1137. return c.Do(req, resp)
  1138. }
  1139. // DoRedirects performs the given http request and fills the given http response,
  1140. // following up to maxRedirectsCount redirects. When the redirect count exceeds
  1141. // maxRedirectsCount, ErrTooManyRedirects is returned.
  1142. //
  1143. // Request must contain at least non-zero RequestURI with full url (including
  1144. // scheme and host) or non-zero Host header + RequestURI.
  1145. //
  1146. // Client determines the server to be requested in the following order:
  1147. //
  1148. // - from RequestURI if it contains full url with scheme and host;
  1149. // - from Host header otherwise.
  1150. //
  1151. // Response is ignored if resp is nil.
  1152. //
  1153. // ErrNoFreeConns is returned if all DefaultMaxConnsPerHost connections
  1154. // to the requested host are busy.
  1155. //
  1156. // It is recommended obtaining req and resp via AcquireRequest
  1157. // and AcquireResponse in performance-critical code.
  1158. func (c *HostClient) DoRedirects(req *Request, resp *Response, maxRedirectsCount int) error {
  1159. if c.DisablePathNormalizing {
  1160. req.URI().DisablePathNormalizing = true
  1161. }
  1162. _, _, err := doRequestFollowRedirects(req, resp, req.URI().String(), maxRedirectsCount, c)
  1163. return err
  1164. }
  1165. // Do performs the given http request and sets the corresponding response.
  1166. //
  1167. // Request must contain at least non-zero RequestURI with full url (including
  1168. // scheme and host) or non-zero Host header + RequestURI.
  1169. //
  1170. // The function doesn't follow redirects. Use Get* for following redirects.
  1171. //
  1172. // Response is ignored if resp is nil.
  1173. //
  1174. // ErrNoFreeConns is returned if all HostClient.MaxConns connections
  1175. // to the host are busy.
  1176. //
  1177. // It is recommended obtaining req and resp via AcquireRequest
  1178. // and AcquireResponse in performance-critical code.
  1179. func (c *HostClient) Do(req *Request, resp *Response) error {
  1180. var (
  1181. err error
  1182. retry bool
  1183. resetTimeout bool
  1184. )
  1185. maxAttempts := c.MaxIdemponentCallAttempts
  1186. if maxAttempts <= 0 {
  1187. maxAttempts = DefaultMaxIdemponentCallAttempts
  1188. }
  1189. attempts := 0
  1190. hasBodyStream := req.IsBodyStream()
  1191. // If a request has a timeout we store the timeout
  1192. // and calculate a deadline so we can keep updating the
  1193. // timeout on each retry.
  1194. deadline := time.Time{}
  1195. timeout := req.timeout
  1196. if timeout > 0 {
  1197. deadline = time.Now().Add(timeout)
  1198. }
  1199. retryFunc := c.RetryIf
  1200. if retryFunc == nil {
  1201. retryFunc = isIdempotent
  1202. }
  1203. atomic.AddInt32(&c.pendingRequests, 1)
  1204. for {
  1205. // If the original timeout was set, we need to update
  1206. // the one set on the request to reflect the remaining time.
  1207. if timeout > 0 {
  1208. req.timeout = time.Until(deadline)
  1209. if req.timeout <= 0 {
  1210. err = ErrTimeout
  1211. break
  1212. }
  1213. }
  1214. retry, err = c.do(req, resp)
  1215. if err == nil || !retry {
  1216. break
  1217. }
  1218. if hasBodyStream {
  1219. break
  1220. }
  1221. // Path prioritization based on ease of computation
  1222. attempts++
  1223. if attempts >= maxAttempts {
  1224. break
  1225. }
  1226. if c.RetryIfErr != nil {
  1227. resetTimeout, retry = c.RetryIfErr(req, attempts, err)
  1228. } else {
  1229. retry = retryFunc(req)
  1230. }
  1231. if !retry {
  1232. break
  1233. }
  1234. if timeout > 0 && resetTimeout {
  1235. deadline = time.Now().Add(timeout)
  1236. }
  1237. }
  1238. atomic.AddInt32(&c.pendingRequests, -1)
  1239. // Restore the original timeout.
  1240. req.timeout = timeout
  1241. if err == io.EOF {
  1242. err = ErrConnectionClosed
  1243. }
  1244. return err
  1245. }
  1246. // PendingRequests returns the current number of requests the client
  1247. // is executing.
  1248. //
  1249. // This function may be used for balancing load among multiple HostClient
  1250. // instances.
  1251. func (c *HostClient) PendingRequests() int {
  1252. return int(atomic.LoadInt32(&c.pendingRequests))
  1253. }
  1254. func isIdempotent(req *Request) bool {
  1255. return req.Header.IsGet() || req.Header.IsHead() || req.Header.IsPut()
  1256. }
  1257. func (c *HostClient) do(req *Request, resp *Response) (bool, error) {
  1258. if resp == nil {
  1259. resp = AcquireResponse()
  1260. defer ReleaseResponse(resp)
  1261. }
  1262. return c.doNonNilReqResp(req, resp)
  1263. }
  1264. func (c *HostClient) doNonNilReqResp(req *Request, resp *Response) (bool, error) {
  1265. if req == nil {
  1266. // for debugging purposes
  1267. panic("BUG: req cannot be nil")
  1268. }
  1269. if resp == nil {
  1270. // for debugging purposes
  1271. panic("BUG: resp cannot be nil")
  1272. }
  1273. // Secure header error logs configuration
  1274. resp.secureErrorLogMessage = c.SecureErrorLogMessage
  1275. resp.Header.secureErrorLogMessage = c.SecureErrorLogMessage
  1276. req.secureErrorLogMessage = c.SecureErrorLogMessage
  1277. req.Header.secureErrorLogMessage = c.SecureErrorLogMessage
  1278. if c.IsTLS != req.URI().isHTTPS() {
  1279. return false, ErrHostClientRedirectToDifferentScheme
  1280. }
  1281. atomic.StoreUint32(&c.lastUseTime, uint32(time.Now().Unix()-startTimeUnix)) // #nosec G115
  1282. // Free up resources occupied by response before sending the request,
  1283. // so the GC may reclaim these resources (e.g. response body).
  1284. // backing up SkipBody in case it was set explicitly
  1285. customSkipBody := resp.SkipBody
  1286. customStreamBody := resp.StreamBody || c.StreamResponseBody
  1287. resp.Reset()
  1288. resp.SkipBody = customSkipBody
  1289. resp.StreamBody = customStreamBody
  1290. req.URI().DisablePathNormalizing = c.DisablePathNormalizing
  1291. userAgentOld := req.Header.UserAgent()
  1292. if len(userAgentOld) == 0 {
  1293. userAgent := c.Name
  1294. if userAgent == "" && !c.NoDefaultUserAgentHeader {
  1295. userAgent = defaultUserAgent
  1296. }
  1297. if userAgent != "" {
  1298. req.Header.userAgent = append(req.Header.userAgent[:0], userAgent...)
  1299. }
  1300. }
  1301. return c.transport().RoundTrip(c, req, resp)
  1302. }
  1303. func (c *HostClient) transport() RoundTripper {
  1304. if c.Transport == nil {
  1305. return DefaultTransport
  1306. }
  1307. return c.Transport
  1308. }
  1309. var (
  1310. // ErrNoFreeConns is returned when no free connections available
  1311. // to the given host.
  1312. //
  1313. // Increase the allowed number of connections per host if you
  1314. // see this error.
  1315. ErrNoFreeConns = errors.New("no free connections available to host")
  1316. // ErrConnectionClosed may be returned from client methods if the server
  1317. // closes connection before returning the first response byte.
  1318. //
  1319. // If you see this error, then either fix the server by returning
  1320. // 'Connection: close' response header before closing the connection
  1321. // or add 'Connection: close' request header before sending requests
  1322. // to broken server.
  1323. ErrConnectionClosed = errors.New("the server closed connection before returning the first response byte. " +
  1324. "Make sure the server returns 'Connection: close' response header before closing the connection")
  1325. // ErrConnPoolStrategyNotImpl is returned when HostClient.ConnPoolStrategy is not implement yet.
  1326. // If you see this error, then you need to check your HostClient configuration.
  1327. ErrConnPoolStrategyNotImpl = errors.New("connection pool strategy is not implement")
  1328. )
  1329. type timeoutError struct{}
  1330. func (e *timeoutError) Error() string {
  1331. return "timeout"
  1332. }
  1333. // Only implement the Timeout() function of the net.Error interface.
  1334. // This allows for checks like:
  1335. //
  1336. // if x, ok := err.(interface{ Timeout() bool }); ok && x.Timeout() {
  1337. func (e *timeoutError) Timeout() bool {
  1338. return true
  1339. }
  1340. // ErrTimeout is returned from timed out calls.
  1341. var ErrTimeout = &timeoutError{}
  1342. // SetMaxConns sets up the maximum number of connections which may be established to all hosts listed in Addr.
  1343. func (c *HostClient) SetMaxConns(newMaxConns int) {
  1344. c.connsLock.Lock()
  1345. c.MaxConns = newMaxConns
  1346. c.connsLock.Unlock()
  1347. }
  1348. func (c *HostClient) AcquireConn(reqTimeout time.Duration, connectionClose bool) (cc *clientConn, err error) {
  1349. createConn := false
  1350. startCleaner := false
  1351. var n int
  1352. c.connsLock.Lock()
  1353. n = len(c.conns)
  1354. if n == 0 {
  1355. maxConns := c.MaxConns
  1356. if maxConns <= 0 {
  1357. maxConns = DefaultMaxConnsPerHost
  1358. }
  1359. if c.connsCount < maxConns {
  1360. c.connsCount++
  1361. createConn = true
  1362. if !c.connsCleanerRun && !connectionClose {
  1363. startCleaner = true
  1364. c.connsCleanerRun = true
  1365. }
  1366. }
  1367. } else {
  1368. switch c.ConnPoolStrategy {
  1369. case LIFO:
  1370. n--
  1371. cc = c.conns[n]
  1372. c.conns[n] = nil
  1373. c.conns = c.conns[:n]
  1374. case FIFO:
  1375. cc = c.conns[0]
  1376. copy(c.conns, c.conns[1:])
  1377. c.conns[n-1] = nil
  1378. c.conns = c.conns[:n-1]
  1379. default:
  1380. c.connsLock.Unlock()
  1381. return nil, ErrConnPoolStrategyNotImpl
  1382. }
  1383. }
  1384. c.connsLock.Unlock()
  1385. if cc != nil {
  1386. return cc, nil
  1387. }
  1388. if !createConn {
  1389. if c.MaxConnWaitTimeout <= 0 {
  1390. return nil, ErrNoFreeConns
  1391. }
  1392. //nolint:dupword
  1393. // reqTimeout c.MaxConnWaitTimeout wait duration
  1394. // d1 d2 min(d1, d2)
  1395. // 0(not set) d2 d2
  1396. // d1 0(don't wait) 0(don't wait)
  1397. // 0(not set) d2 d2
  1398. timeout := c.MaxConnWaitTimeout
  1399. timeoutOverridden := false
  1400. // reqTimeout == 0 means not set
  1401. if reqTimeout > 0 && reqTimeout < timeout {
  1402. timeout = reqTimeout
  1403. timeoutOverridden = true
  1404. }
  1405. // wait for a free connection
  1406. tc := AcquireTimer(timeout)
  1407. defer ReleaseTimer(tc)
  1408. w := &wantConn{
  1409. ready: make(chan struct{}, 1),
  1410. }
  1411. defer func() {
  1412. if err != nil {
  1413. w.cancel(c, err)
  1414. }
  1415. }()
  1416. c.queueForIdle(w)
  1417. select {
  1418. case <-w.ready:
  1419. return w.conn, w.err
  1420. case <-tc.C:
  1421. c.connsWait.failedWaiters.Add(1)
  1422. if timeoutOverridden {
  1423. return nil, ErrTimeout
  1424. }
  1425. return nil, ErrNoFreeConns
  1426. }
  1427. }
  1428. if startCleaner {
  1429. go c.connsCleaner()
  1430. }
  1431. conn, err := c.dialHostHard(reqTimeout)
  1432. if err != nil {
  1433. c.decConnsCount()
  1434. return nil, err
  1435. }
  1436. cc = acquireClientConn(conn)
  1437. return cc, nil
  1438. }
  1439. func (c *HostClient) queueForIdle(w *wantConn) {
  1440. c.connsLock.Lock()
  1441. defer c.connsLock.Unlock()
  1442. if c.connsWait == nil {
  1443. c.connsWait = &wantConnQueue{}
  1444. }
  1445. c.connsWait.clearFront()
  1446. c.connsWait.pushBack(w)
  1447. }
  1448. func (c *HostClient) dialConnFor(w *wantConn) {
  1449. conn, err := c.dialHostHard(0)
  1450. if err != nil {
  1451. w.tryDeliver(nil, err)
  1452. c.decConnsCount()
  1453. return
  1454. }
  1455. cc := acquireClientConn(conn)
  1456. if !w.tryDeliver(cc, nil) {
  1457. // not delivered, return idle connection
  1458. c.ReleaseConn(cc)
  1459. }
  1460. }
  1461. // CloseIdleConnections closes any connections which were previously
  1462. // connected from previous requests but are now sitting idle in a
  1463. // "keep-alive" state. It does not interrupt any connections currently
  1464. // in use.
  1465. func (c *HostClient) CloseIdleConnections() {
  1466. c.connsLock.Lock()
  1467. scratch := append([]*clientConn{}, c.conns...)
  1468. for i := range c.conns {
  1469. c.conns[i] = nil
  1470. }
  1471. c.conns = c.conns[:0]
  1472. c.connsLock.Unlock()
  1473. for _, cc := range scratch {
  1474. c.CloseConn(cc)
  1475. }
  1476. }
  1477. func (c *HostClient) connsCleaner() {
  1478. var (
  1479. scratch []*clientConn
  1480. maxIdleConnDuration = c.MaxIdleConnDuration
  1481. )
  1482. if maxIdleConnDuration <= 0 {
  1483. maxIdleConnDuration = DefaultMaxIdleConnDuration
  1484. }
  1485. for {
  1486. currentTime := time.Now()
  1487. // Determine idle connections to be closed.
  1488. c.connsLock.Lock()
  1489. conns := c.conns
  1490. n := len(conns)
  1491. i := 0
  1492. for i < n && currentTime.Sub(conns[i].lastUseTime) > maxIdleConnDuration {
  1493. i++
  1494. }
  1495. sleepFor := maxIdleConnDuration
  1496. if i < n {
  1497. // + 1 so we actually sleep past the expiration time and not up to it.
  1498. // Otherwise the > check above would still fail.
  1499. sleepFor = maxIdleConnDuration - currentTime.Sub(conns[i].lastUseTime) + 1
  1500. }
  1501. scratch = append(scratch[:0], conns[:i]...)
  1502. if i > 0 {
  1503. m := copy(conns, conns[i:])
  1504. for i = m; i < n; i++ {
  1505. conns[i] = nil
  1506. }
  1507. c.conns = conns[:m]
  1508. }
  1509. c.connsLock.Unlock()
  1510. // Close idle connections.
  1511. for i, cc := range scratch {
  1512. c.CloseConn(cc)
  1513. scratch[i] = nil
  1514. }
  1515. // Determine whether to stop the connsCleaner.
  1516. c.connsLock.Lock()
  1517. mustStop := c.connsCount == 0
  1518. if mustStop {
  1519. c.connsCleanerRun = false
  1520. }
  1521. c.connsLock.Unlock()
  1522. if mustStop {
  1523. break
  1524. }
  1525. time.Sleep(sleepFor)
  1526. }
  1527. }
  1528. func (c *HostClient) CloseConn(cc *clientConn) {
  1529. c.decConnsCount()
  1530. cc.c.Close()
  1531. releaseClientConn(cc)
  1532. }
  1533. func (c *HostClient) decConnsCount() {
  1534. if c.MaxConnWaitTimeout <= 0 {
  1535. c.connsLock.Lock()
  1536. c.connsCount--
  1537. c.connsLock.Unlock()
  1538. return
  1539. }
  1540. c.connsLock.Lock()
  1541. defer c.connsLock.Unlock()
  1542. dialed := false
  1543. if q := c.connsWait; q != nil && q.len() > 0 {
  1544. for q.len() > 0 {
  1545. w := q.popFront()
  1546. if w.waiting() {
  1547. go c.dialConnFor(w)
  1548. dialed = true
  1549. break
  1550. }
  1551. c.connsWait.failedWaiters.Add(-1)
  1552. }
  1553. }
  1554. if !dialed {
  1555. c.connsCount--
  1556. }
  1557. }
  1558. // ConnsCount returns connection count of HostClient.
  1559. func (c *HostClient) ConnsCount() int {
  1560. c.connsLock.Lock()
  1561. defer c.connsLock.Unlock()
  1562. return c.connsCount
  1563. }
  1564. func acquireClientConn(conn net.Conn) *clientConn {
  1565. v := clientConnPool.Get()
  1566. if v == nil {
  1567. v = &clientConn{}
  1568. }
  1569. cc := v.(*clientConn)
  1570. cc.c = conn
  1571. cc.createdTime = time.Now()
  1572. return cc
  1573. }
  1574. func releaseClientConn(cc *clientConn) {
  1575. // Reset all fields.
  1576. *cc = clientConn{}
  1577. clientConnPool.Put(cc)
  1578. }
  1579. var clientConnPool sync.Pool
  1580. func (c *HostClient) ReleaseConn(cc *clientConn) {
  1581. cc.lastUseTime = time.Now()
  1582. if c.MaxConnWaitTimeout <= 0 {
  1583. c.connsLock.Lock()
  1584. c.conns = append(c.conns, cc)
  1585. c.connsLock.Unlock()
  1586. return
  1587. }
  1588. // try to deliver an idle connection to a *wantConn
  1589. c.connsLock.Lock()
  1590. defer c.connsLock.Unlock()
  1591. delivered := false
  1592. if q := c.connsWait; q != nil && q.len() > 0 {
  1593. for q.len() > 0 {
  1594. w := q.popFront()
  1595. if w.waiting() {
  1596. delivered = w.tryDeliver(cc, nil)
  1597. // This is the last resort to hand over conCount sema.
  1598. // We must ensure that there are no valid waiters in connsWait
  1599. // when we exit this loop.
  1600. //
  1601. // We did not apply the same looping pattern in the decConnsCount
  1602. // method because it needs to create a new time-spent connection,
  1603. // and the decConnsCount call chain will inevitably reach this point.
  1604. // When MaxConnWaitTimeout>0.
  1605. if delivered {
  1606. break
  1607. }
  1608. }
  1609. c.connsWait.failedWaiters.Add(-1)
  1610. }
  1611. }
  1612. if !delivered {
  1613. c.conns = append(c.conns, cc)
  1614. }
  1615. }
  1616. func (c *HostClient) AcquireWriter(conn net.Conn) *bufio.Writer {
  1617. var v any
  1618. if c.clientWriterPool != nil {
  1619. v = c.clientWriterPool.Get()
  1620. } else {
  1621. v = c.writerPool.Get()
  1622. }
  1623. if v == nil {
  1624. n := c.WriteBufferSize
  1625. if n <= 0 {
  1626. n = defaultWriteBufferSize
  1627. }
  1628. return bufio.NewWriterSize(conn, n)
  1629. }
  1630. bw := v.(*bufio.Writer)
  1631. bw.Reset(conn)
  1632. return bw
  1633. }
  1634. func (c *HostClient) ReleaseWriter(bw *bufio.Writer) {
  1635. if c.clientWriterPool != nil {
  1636. c.clientWriterPool.Put(bw)
  1637. } else {
  1638. c.writerPool.Put(bw)
  1639. }
  1640. }
  1641. func (c *HostClient) AcquireReader(conn net.Conn) *bufio.Reader {
  1642. var v any
  1643. if c.clientReaderPool != nil {
  1644. v = c.clientReaderPool.Get()
  1645. } else {
  1646. v = c.readerPool.Get()
  1647. }
  1648. if v == nil {
  1649. n := c.ReadBufferSize
  1650. if n <= 0 {
  1651. n = defaultReadBufferSize
  1652. }
  1653. return bufio.NewReaderSize(conn, n)
  1654. }
  1655. br := v.(*bufio.Reader)
  1656. br.Reset(conn)
  1657. return br
  1658. }
  1659. func (c *HostClient) ReleaseReader(br *bufio.Reader) {
  1660. if c.clientReaderPool != nil {
  1661. c.clientReaderPool.Put(br)
  1662. } else {
  1663. c.readerPool.Put(br)
  1664. }
  1665. }
  1666. func newClientTLSConfig(c *tls.Config, addr string) *tls.Config {
  1667. if c == nil {
  1668. c = &tls.Config{}
  1669. } else {
  1670. c = c.Clone()
  1671. }
  1672. if c.ServerName == "" {
  1673. serverName := tlsServerName(addr)
  1674. if serverName == "*" {
  1675. c.InsecureSkipVerify = true
  1676. } else {
  1677. c.ServerName = serverName
  1678. }
  1679. }
  1680. return c
  1681. }
  1682. func tlsServerName(addr string) string {
  1683. if !strings.Contains(addr, ":") {
  1684. return addr
  1685. }
  1686. host, _, err := net.SplitHostPort(addr)
  1687. if err != nil {
  1688. return "*"
  1689. }
  1690. return host
  1691. }
  1692. func (c *HostClient) nextAddr() string {
  1693. c.addrsLock.Lock()
  1694. if c.addrs == nil {
  1695. c.addrs = strings.Split(c.Addr, ",")
  1696. }
  1697. addr := c.addrs[0]
  1698. if len(c.addrs) > 1 {
  1699. addr = c.addrs[c.addrIdx%uint32(len(c.addrs))] // #nosec G115
  1700. c.addrIdx++
  1701. }
  1702. c.addrsLock.Unlock()
  1703. return addr
  1704. }
  1705. func (c *HostClient) dialHostHard(dialTimeout time.Duration) (conn net.Conn, err error) {
  1706. // use dialTimeout to control the timeout of each dial. It does not work if dialTimeout is 0 or if
  1707. // c.DialTimeout has not been set and c.Dial has been set.
  1708. // attempt to dial all the available hosts before giving up.
  1709. c.addrsLock.Lock()
  1710. n := len(c.addrs)
  1711. c.addrsLock.Unlock()
  1712. if n == 0 {
  1713. // It looks like c.addrs isn't initialized yet.
  1714. n = 1
  1715. }
  1716. timeout := c.ReadTimeout + c.WriteTimeout
  1717. if timeout <= 0 {
  1718. timeout = DefaultDialTimeout
  1719. }
  1720. deadline := time.Now().Add(timeout)
  1721. for n > 0 {
  1722. addr := c.nextAddr()
  1723. tlsConfig := c.cachedTLSConfig(addr)
  1724. conn, err = dialAddr(addr, c.Dial, c.DialTimeout, c.DialDualStack, c.IsTLS, tlsConfig, dialTimeout, c.WriteTimeout)
  1725. if err == nil {
  1726. return conn, nil
  1727. }
  1728. if time.Since(deadline) >= 0 {
  1729. break
  1730. }
  1731. n--
  1732. }
  1733. return nil, err
  1734. }
  1735. func (c *HostClient) cachedTLSConfig(addr string) *tls.Config {
  1736. if !c.IsTLS {
  1737. return nil
  1738. }
  1739. c.tlsConfigMapLock.Lock()
  1740. if c.tlsConfigMap == nil {
  1741. c.tlsConfigMap = make(map[string]*tls.Config)
  1742. }
  1743. cfg := c.tlsConfigMap[addr]
  1744. if cfg == nil {
  1745. cfg = newClientTLSConfig(c.TLSConfig, addr)
  1746. c.tlsConfigMap[addr] = cfg
  1747. }
  1748. c.tlsConfigMapLock.Unlock()
  1749. return cfg
  1750. }
  1751. // ErrTLSHandshakeTimeout indicates there is a timeout from tls handshake.
  1752. var ErrTLSHandshakeTimeout = errors.New("tls handshake timed out")
  1753. func tlsClientHandshake(rawConn net.Conn, tlsConfig *tls.Config, deadline time.Time) (_ net.Conn, retErr error) {
  1754. defer func() {
  1755. if retErr != nil {
  1756. rawConn.Close()
  1757. }
  1758. }()
  1759. conn := tls.Client(rawConn, tlsConfig)
  1760. err := conn.SetDeadline(deadline)
  1761. if err != nil {
  1762. return nil, err
  1763. }
  1764. err = conn.Handshake()
  1765. if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
  1766. return nil, ErrTLSHandshakeTimeout
  1767. }
  1768. if err != nil {
  1769. return nil, err
  1770. }
  1771. err = conn.SetDeadline(time.Time{})
  1772. if err != nil {
  1773. return nil, err
  1774. }
  1775. return conn, nil
  1776. }
  1777. func dialAddr(
  1778. addr string, dial DialFunc, dialWithTimeout DialFuncWithTimeout, dialDualStack, isTLS bool,
  1779. tlsConfig *tls.Config, dialTimeout, writeTimeout time.Duration,
  1780. ) (net.Conn, error) {
  1781. deadline := time.Now().Add(writeTimeout)
  1782. conn, err := callDialFunc(addr, dial, dialWithTimeout, dialDualStack, isTLS, dialTimeout)
  1783. if err != nil {
  1784. return nil, err
  1785. }
  1786. if conn == nil {
  1787. return nil, errors.New("dialling unsuccessful. Please report this bug")
  1788. }
  1789. // We assume that any conn that has the Handshake() method is a TLS conn already.
  1790. // This doesn't cover just tls.Conn but also other TLS implementations.
  1791. _, isTLSAlready := conn.(interface{ Handshake() error })
  1792. if isTLS && !isTLSAlready {
  1793. if writeTimeout == 0 {
  1794. return tls.Client(conn, tlsConfig), nil
  1795. }
  1796. return tlsClientHandshake(conn, tlsConfig, deadline)
  1797. }
  1798. return conn, nil
  1799. }
  1800. func callDialFunc(
  1801. addr string, dial DialFunc, dialWithTimeout DialFuncWithTimeout, dialDualStack, isTLS bool, timeout time.Duration,
  1802. ) (net.Conn, error) {
  1803. if dialWithTimeout != nil {
  1804. return dialWithTimeout(addr, timeout)
  1805. }
  1806. if dial != nil {
  1807. return dial(addr)
  1808. }
  1809. addr = AddMissingPort(addr, isTLS)
  1810. if timeout > 0 {
  1811. if dialDualStack {
  1812. return DialDualStackTimeout(addr, timeout)
  1813. }
  1814. return DialTimeout(addr, timeout)
  1815. }
  1816. if dialDualStack {
  1817. return DialDualStack(addr)
  1818. }
  1819. return Dial(addr)
  1820. }
  1821. // AddMissingPort adds a port to a host if it is missing.
  1822. // A literal IPv6 address in hostport must be enclosed in square
  1823. // brackets, as in "[::1]:80", "[::1%lo0]:80".
  1824. func AddMissingPort(addr string, isTLS bool) string {
  1825. addrLen := len(addr)
  1826. if addrLen == 0 {
  1827. return addr
  1828. }
  1829. isIP6 := addr[0] == '['
  1830. if isIP6 {
  1831. // if the IPv6 has opening bracket but closing bracket is the last char then it doesn't have a port
  1832. isIP6WithoutPort := addr[addrLen-1] == ']'
  1833. if !isIP6WithoutPort {
  1834. return addr
  1835. }
  1836. } else { // IPv4
  1837. columnPos := strings.LastIndexByte(addr, ':')
  1838. if columnPos > 0 {
  1839. return addr
  1840. }
  1841. }
  1842. port := ":80"
  1843. if isTLS {
  1844. port = ":443"
  1845. }
  1846. return addr + port
  1847. }
  1848. // A wantConn records state about a wanted connection
  1849. // (that is, an active call to getConn).
  1850. // The conn may be gotten by dialing or by finding an idle connection,
  1851. // or a cancellation may make the conn no longer wanted.
  1852. // These three options are racing against each other and use
  1853. // wantConn to coordinate and agree about the winning outcome.
  1854. //
  1855. // Inspired by net/http/transport.go.
  1856. type wantConn struct {
  1857. err error
  1858. ready chan struct{}
  1859. conn *clientConn
  1860. mu sync.Mutex // protects conn, err, close(ready)
  1861. }
  1862. // waiting reports whether w is still waiting for an answer (connection or error).
  1863. func (w *wantConn) waiting() bool {
  1864. select {
  1865. case <-w.ready:
  1866. return false
  1867. default:
  1868. return true
  1869. }
  1870. }
  1871. // tryDeliver attempts to deliver conn, err to w and reports whether it succeeded.
  1872. func (w *wantConn) tryDeliver(conn *clientConn, err error) bool {
  1873. w.mu.Lock()
  1874. defer w.mu.Unlock()
  1875. if w.conn != nil || w.err != nil {
  1876. return false
  1877. }
  1878. w.conn = conn
  1879. w.err = err
  1880. if w.conn == nil && w.err == nil {
  1881. panic("fasthttp: internal error: misuse of tryDeliver")
  1882. }
  1883. close(w.ready)
  1884. return true
  1885. }
  1886. // cancel marks w as no longer wanting a result (for example, due to cancellation).
  1887. // If a connection has been delivered already, cancel returns it with c.releaseConn.
  1888. func (w *wantConn) cancel(c *HostClient, err error) {
  1889. w.mu.Lock()
  1890. if w.conn == nil && w.err == nil {
  1891. close(w.ready) // catch misbehavior in future delivery
  1892. }
  1893. conn := w.conn
  1894. w.conn = nil
  1895. w.err = err
  1896. w.mu.Unlock()
  1897. if conn != nil {
  1898. c.ReleaseConn(conn)
  1899. }
  1900. }
  1901. // A wantConnQueue is a queue of wantConns.
  1902. //
  1903. // Inspired by net/http/transport.go.
  1904. type wantConnQueue struct {
  1905. // This is a queue, not a dequeue.
  1906. // It is split into two stages - head[headPos:] and tail.
  1907. // popFront is trivial (headPos++) on the first stage, and
  1908. // pushBack is trivial (append) on the second stage.
  1909. // If the first stage is empty, popFront can swap the
  1910. // first and second stages to remedy the situation.
  1911. //
  1912. // This two-stage split is analogous to the use of two lists
  1913. // in Okasaki's purely functional queue but without the
  1914. // overhead of reversing the list when swapping stages.
  1915. head []*wantConn
  1916. tail []*wantConn
  1917. headPos int
  1918. // failedWaiters is the number of waiters in the head or tail queue,
  1919. // but is invalid.
  1920. // These state waiters cannot truly be considered as waiters; the current
  1921. // implementation does not immediately remove them when they become
  1922. // invalid but instead only marks them.
  1923. failedWaiters atomic.Int64
  1924. }
  1925. // len returns the number of items in the queue.
  1926. func (q *wantConnQueue) len() int {
  1927. return len(q.head) - q.headPos + len(q.tail) - int(q.failedWaiters.Load())
  1928. }
  1929. // pushBack adds w to the back of the queue.
  1930. func (q *wantConnQueue) pushBack(w *wantConn) {
  1931. q.tail = append(q.tail, w)
  1932. }
  1933. // popFront removes and returns the wantConn at the front of the queue.
  1934. func (q *wantConnQueue) popFront() *wantConn {
  1935. if q.headPos >= len(q.head) {
  1936. if len(q.tail) == 0 {
  1937. return nil
  1938. }
  1939. // Pick up tail as new head, clear tail.
  1940. q.head, q.headPos, q.tail = q.tail, 0, q.head[:0]
  1941. }
  1942. w := q.head[q.headPos]
  1943. q.head[q.headPos] = nil
  1944. q.headPos++
  1945. return w
  1946. }
  1947. // peekFront returns the wantConn at the front of the queue without removing it.
  1948. func (q *wantConnQueue) peekFront() *wantConn {
  1949. if q.headPos < len(q.head) {
  1950. return q.head[q.headPos]
  1951. }
  1952. if len(q.tail) > 0 {
  1953. return q.tail[0]
  1954. }
  1955. return nil
  1956. }
  1957. // clearFront pops any wantConns that are no longer waiting from the head of the
  1958. // queue, reporting whether any were popped.
  1959. func (q *wantConnQueue) clearFront() (cleaned bool) {
  1960. for {
  1961. w := q.peekFront()
  1962. if w == nil || w.waiting() {
  1963. return cleaned
  1964. }
  1965. q.popFront()
  1966. q.failedWaiters.Add(-1)
  1967. cleaned = true
  1968. }
  1969. }
  1970. // PipelineClient pipelines requests over a limited set of concurrent
  1971. // connections to the given Addr.
  1972. //
  1973. // This client may be used in highly loaded HTTP-based RPC systems for reducing
  1974. // context switches and network level overhead.
  1975. // See https://en.wikipedia.org/wiki/HTTP_pipelining for details.
  1976. //
  1977. // It is forbidden copying PipelineClient instances. Create new instances
  1978. // instead.
  1979. //
  1980. // It is safe calling PipelineClient methods from concurrently running
  1981. // goroutines.
  1982. type PipelineClient struct {
  1983. noCopy noCopy
  1984. // Logger for logging client errors.
  1985. //
  1986. // By default standard logger from log package is used.
  1987. Logger Logger
  1988. // Callback for connection establishing to the host.
  1989. //
  1990. // Default Dial is used if not set.
  1991. Dial DialFunc
  1992. // Optional TLS config.
  1993. TLSConfig *tls.Config
  1994. // Address of the host to connect to.
  1995. Addr string
  1996. // PipelineClient name. Used in User-Agent request header.
  1997. Name string
  1998. connClients []*pipelineConnClient
  1999. // The maximum number of concurrent connections to the Addr.
  2000. //
  2001. // A single connection is used by default.
  2002. MaxConns int
  2003. // The maximum number of pending pipelined requests over
  2004. // a single connection to Addr.
  2005. //
  2006. // DefaultMaxPendingRequests is used by default.
  2007. MaxPendingRequests int
  2008. // The maximum delay before sending pipelined requests as a batch
  2009. // to the server.
  2010. //
  2011. // By default requests are sent immediately to the server.
  2012. MaxBatchDelay time.Duration
  2013. // Idle connection to the host is closed after this duration.
  2014. //
  2015. // By default idle connection is closed after
  2016. // DefaultMaxIdleConnDuration.
  2017. MaxIdleConnDuration time.Duration
  2018. // Buffer size for responses' reading.
  2019. // This also limits the maximum header size.
  2020. //
  2021. // Default buffer size is used if 0.
  2022. ReadBufferSize int
  2023. // Buffer size for requests' writing.
  2024. //
  2025. // Default buffer size is used if 0.
  2026. WriteBufferSize int
  2027. // Maximum duration for full response reading (including body).
  2028. //
  2029. // By default response read timeout is unlimited.
  2030. ReadTimeout time.Duration
  2031. // Maximum duration for full request writing (including body).
  2032. //
  2033. // By default request write timeout is unlimited.
  2034. WriteTimeout time.Duration
  2035. connClientsLock sync.Mutex
  2036. // NoDefaultUserAgentHeader when set to true, causes the default
  2037. // User-Agent header to be excluded from the Request.
  2038. NoDefaultUserAgentHeader bool
  2039. // Attempt to connect to both ipv4 and ipv6 host addresses
  2040. // if set to true.
  2041. //
  2042. // This option is used only if default TCP dialer is used,
  2043. // i.e. if Dial is blank.
  2044. //
  2045. // By default client connects only to ipv4 addresses,
  2046. // since unfortunately ipv6 remains broken in many networks worldwide :)
  2047. DialDualStack bool
  2048. // Response header names are passed as-is without normalization
  2049. // if this option is set.
  2050. //
  2051. // Disabled header names' normalization may be useful only for proxying
  2052. // responses to other clients expecting case-sensitive
  2053. // header names. See https://github.com/valyala/fasthttp/issues/57
  2054. // for details.
  2055. //
  2056. // By default request and response header names are normalized, i.e.
  2057. // The first letter and the first letters following dashes
  2058. // are uppercased, while all the other letters are lowercased.
  2059. // Examples:
  2060. //
  2061. // * HOST -> Host
  2062. // * content-type -> Content-Type
  2063. // * cONTENT-lenGTH -> Content-Length
  2064. DisableHeaderNamesNormalizing bool
  2065. // Path values are sent as-is without normalization
  2066. //
  2067. // Disabled path normalization may be useful for proxying incoming requests
  2068. // to servers that are expecting paths to be forwarded as-is.
  2069. //
  2070. // By default path values are normalized, i.e.
  2071. // extra slashes are removed, special characters are encoded.
  2072. DisablePathNormalizing bool
  2073. // Whether to use TLS (aka SSL or HTTPS) for host connections.
  2074. IsTLS bool
  2075. }
  2076. type pipelineConnClient struct {
  2077. noCopy noCopy
  2078. workPool sync.Pool
  2079. Logger Logger
  2080. Dial DialFunc
  2081. TLSConfig *tls.Config
  2082. chW chan *pipelineWork
  2083. chR chan *pipelineWork
  2084. tlsConfig *tls.Config
  2085. Addr string
  2086. Name string
  2087. MaxPendingRequests int
  2088. MaxBatchDelay time.Duration
  2089. MaxIdleConnDuration time.Duration
  2090. ReadBufferSize int
  2091. WriteBufferSize int
  2092. ReadTimeout time.Duration
  2093. WriteTimeout time.Duration
  2094. chLock sync.Mutex
  2095. tlsConfigLock sync.Mutex
  2096. NoDefaultUserAgentHeader bool
  2097. DialDualStack bool
  2098. DisableHeaderNamesNormalizing bool
  2099. DisablePathNormalizing bool
  2100. IsTLS bool
  2101. }
  2102. type pipelineWork struct {
  2103. respCopy Response
  2104. deadline time.Time
  2105. err error
  2106. req *Request
  2107. resp *Response
  2108. t *time.Timer
  2109. done chan struct{}
  2110. reqCopy Request
  2111. }
  2112. // DoTimeout performs the given request and waits for response during
  2113. // the given timeout duration.
  2114. //
  2115. // Request must contain at least non-zero RequestURI with full url (including
  2116. // scheme and host) or non-zero Host header + RequestURI.
  2117. //
  2118. // The function doesn't follow redirects.
  2119. //
  2120. // Response is ignored if resp is nil.
  2121. //
  2122. // ErrTimeout is returned if the response wasn't returned during
  2123. // the given timeout.
  2124. //
  2125. // It is recommended obtaining req and resp via AcquireRequest
  2126. // and AcquireResponse in performance-critical code.
  2127. func (c *PipelineClient) DoTimeout(req *Request, resp *Response, timeout time.Duration) error {
  2128. return c.DoDeadline(req, resp, time.Now().Add(timeout))
  2129. }
  2130. // DoDeadline performs the given request and waits for response until
  2131. // the given deadline.
  2132. //
  2133. // Request must contain at least non-zero RequestURI with full url (including
  2134. // scheme and host) or non-zero Host header + RequestURI.
  2135. //
  2136. // The function doesn't follow redirects.
  2137. //
  2138. // Response is ignored if resp is nil.
  2139. //
  2140. // ErrTimeout is returned if the response wasn't returned until
  2141. // the given deadline.
  2142. //
  2143. // It is recommended obtaining req and resp via AcquireRequest
  2144. // and AcquireResponse in performance-critical code.
  2145. func (c *PipelineClient) DoDeadline(req *Request, resp *Response, deadline time.Time) error {
  2146. return c.getConnClient().DoDeadline(req, resp, deadline)
  2147. }
  2148. func (c *pipelineConnClient) DoDeadline(req *Request, resp *Response, deadline time.Time) error {
  2149. c.init()
  2150. timeout := time.Until(deadline)
  2151. if timeout <= 0 {
  2152. return ErrTimeout
  2153. }
  2154. if c.DisablePathNormalizing {
  2155. req.URI().DisablePathNormalizing = true
  2156. }
  2157. userAgentOld := req.Header.UserAgent()
  2158. if len(userAgentOld) == 0 {
  2159. userAgent := c.Name
  2160. if userAgent == "" && !c.NoDefaultUserAgentHeader {
  2161. userAgent = defaultUserAgent
  2162. }
  2163. if userAgent != "" {
  2164. req.Header.userAgent = append(req.Header.userAgent[:0], userAgent...)
  2165. }
  2166. }
  2167. w := c.acquirePipelineWork(timeout)
  2168. w.respCopy.Header.disableNormalizing = c.DisableHeaderNamesNormalizing
  2169. w.req = &w.reqCopy
  2170. w.resp = &w.respCopy
  2171. // Make a copy of the request in order to avoid data races on timeouts
  2172. req.copyToSkipBody(&w.reqCopy)
  2173. swapRequestBody(req, &w.reqCopy)
  2174. // Put the request to outgoing queue
  2175. select {
  2176. case c.chW <- w:
  2177. // Fast path: len(c.ch) < cap(c.ch)
  2178. default:
  2179. // Slow path
  2180. select {
  2181. case c.chW <- w:
  2182. case <-w.t.C:
  2183. c.releasePipelineWork(w)
  2184. return ErrTimeout
  2185. }
  2186. }
  2187. // Wait for the response
  2188. var err error
  2189. select {
  2190. case <-w.done:
  2191. if resp != nil {
  2192. w.respCopy.copyToSkipBody(resp)
  2193. swapResponseBody(resp, &w.respCopy)
  2194. }
  2195. err = w.err
  2196. c.releasePipelineWork(w)
  2197. case <-w.t.C:
  2198. err = ErrTimeout
  2199. }
  2200. return err
  2201. }
  2202. func (c *pipelineConnClient) acquirePipelineWork(timeout time.Duration) (w *pipelineWork) {
  2203. v := c.workPool.Get()
  2204. if v != nil {
  2205. w = v.(*pipelineWork)
  2206. } else {
  2207. w = &pipelineWork{
  2208. done: make(chan struct{}, 1),
  2209. }
  2210. }
  2211. if timeout > 0 {
  2212. if w.t == nil {
  2213. w.t = time.NewTimer(timeout)
  2214. } else {
  2215. w.t.Reset(timeout)
  2216. }
  2217. w.deadline = time.Now().Add(timeout)
  2218. } else {
  2219. w.deadline = zeroTime
  2220. }
  2221. return w
  2222. }
  2223. func (c *pipelineConnClient) releasePipelineWork(w *pipelineWork) {
  2224. if w.t != nil {
  2225. w.t.Stop()
  2226. }
  2227. w.reqCopy.Reset()
  2228. w.respCopy.Reset()
  2229. w.req = nil
  2230. w.resp = nil
  2231. w.err = nil
  2232. c.workPool.Put(w)
  2233. }
  2234. // Do performs the given http request and sets the corresponding response.
  2235. //
  2236. // Request must contain at least non-zero RequestURI with full url (including
  2237. // scheme and host) or non-zero Host header + RequestURI.
  2238. //
  2239. // The function doesn't follow redirects. Use Get* for following redirects.
  2240. //
  2241. // Response is ignored if resp is nil.
  2242. //
  2243. // It is recommended obtaining req and resp via AcquireRequest
  2244. // and AcquireResponse in performance-critical code.
  2245. func (c *PipelineClient) Do(req *Request, resp *Response) error {
  2246. return c.getConnClient().Do(req, resp)
  2247. }
  2248. func (c *pipelineConnClient) Do(req *Request, resp *Response) error {
  2249. c.init()
  2250. if c.DisablePathNormalizing {
  2251. req.URI().DisablePathNormalizing = true
  2252. }
  2253. userAgentOld := req.Header.UserAgent()
  2254. if len(userAgentOld) == 0 {
  2255. userAgent := c.Name
  2256. if userAgent == "" && !c.NoDefaultUserAgentHeader {
  2257. userAgent = defaultUserAgent
  2258. }
  2259. if userAgent != "" {
  2260. req.Header.userAgent = append(req.Header.userAgent[:0], userAgent...)
  2261. }
  2262. }
  2263. w := c.acquirePipelineWork(0)
  2264. w.req = req
  2265. if resp != nil {
  2266. resp.Header.disableNormalizing = c.DisableHeaderNamesNormalizing
  2267. w.resp = resp
  2268. } else {
  2269. w.resp = &w.respCopy
  2270. }
  2271. // Put the request to outgoing queue
  2272. select {
  2273. case c.chW <- w:
  2274. default:
  2275. // Try substituting the oldest w with the current one.
  2276. select {
  2277. case wOld := <-c.chW:
  2278. wOld.err = ErrPipelineOverflow
  2279. wOld.done <- struct{}{}
  2280. default:
  2281. }
  2282. select {
  2283. case c.chW <- w:
  2284. default:
  2285. c.releasePipelineWork(w)
  2286. return ErrPipelineOverflow
  2287. }
  2288. }
  2289. // Wait for the response
  2290. <-w.done
  2291. err := w.err
  2292. c.releasePipelineWork(w)
  2293. return err
  2294. }
  2295. func (c *PipelineClient) getConnClient() *pipelineConnClient {
  2296. c.connClientsLock.Lock()
  2297. cc := c.getConnClientUnlocked()
  2298. c.connClientsLock.Unlock()
  2299. return cc
  2300. }
  2301. func (c *PipelineClient) getConnClientUnlocked() *pipelineConnClient {
  2302. if len(c.connClients) == 0 {
  2303. return c.newConnClient()
  2304. }
  2305. // Return the client with the minimum number of pending requests.
  2306. minCC := c.connClients[0]
  2307. minReqs := minCC.PendingRequests()
  2308. if minReqs == 0 {
  2309. return minCC
  2310. }
  2311. for i := 1; i < len(c.connClients); i++ {
  2312. cc := c.connClients[i]
  2313. reqs := cc.PendingRequests()
  2314. if reqs == 0 {
  2315. return cc
  2316. }
  2317. if reqs < minReqs {
  2318. minCC = cc
  2319. minReqs = reqs
  2320. }
  2321. }
  2322. maxConns := c.MaxConns
  2323. if maxConns <= 0 {
  2324. maxConns = 1
  2325. }
  2326. if len(c.connClients) < maxConns {
  2327. return c.newConnClient()
  2328. }
  2329. return minCC
  2330. }
  2331. func (c *PipelineClient) newConnClient() *pipelineConnClient {
  2332. cc := &pipelineConnClient{
  2333. Addr: c.Addr,
  2334. Name: c.Name,
  2335. NoDefaultUserAgentHeader: c.NoDefaultUserAgentHeader,
  2336. MaxPendingRequests: c.MaxPendingRequests,
  2337. MaxBatchDelay: c.MaxBatchDelay,
  2338. Dial: c.Dial,
  2339. DialDualStack: c.DialDualStack,
  2340. DisableHeaderNamesNormalizing: c.DisableHeaderNamesNormalizing,
  2341. DisablePathNormalizing: c.DisablePathNormalizing,
  2342. IsTLS: c.IsTLS,
  2343. TLSConfig: c.TLSConfig,
  2344. MaxIdleConnDuration: c.MaxIdleConnDuration,
  2345. ReadBufferSize: c.ReadBufferSize,
  2346. WriteBufferSize: c.WriteBufferSize,
  2347. ReadTimeout: c.ReadTimeout,
  2348. WriteTimeout: c.WriteTimeout,
  2349. Logger: c.Logger,
  2350. }
  2351. c.connClients = append(c.connClients, cc)
  2352. return cc
  2353. }
  2354. // ErrPipelineOverflow may be returned from PipelineClient.Do*
  2355. // if the requests' queue is overflowed.
  2356. var ErrPipelineOverflow = errors.New("pipelined requests' queue has been overflowed. Increase MaxConns and/or MaxPendingRequests")
  2357. // DefaultMaxPendingRequests is the default value
  2358. // for PipelineClient.MaxPendingRequests.
  2359. const DefaultMaxPendingRequests = 1024
  2360. func (c *pipelineConnClient) init() {
  2361. c.chLock.Lock()
  2362. if c.chR == nil {
  2363. maxPendingRequests := c.MaxPendingRequests
  2364. if maxPendingRequests <= 0 {
  2365. maxPendingRequests = DefaultMaxPendingRequests
  2366. }
  2367. c.chR = make(chan *pipelineWork, maxPendingRequests)
  2368. if c.chW == nil {
  2369. c.chW = make(chan *pipelineWork, maxPendingRequests)
  2370. }
  2371. go func() {
  2372. // Keep restarting the worker if it fails (connection errors for example).
  2373. for {
  2374. if err := c.worker(); err != nil {
  2375. c.logger().Printf("error in PipelineClient(%q): %v", c.Addr, err)
  2376. if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
  2377. // Throttle client reconnections on timeout errors
  2378. time.Sleep(time.Second)
  2379. }
  2380. } else {
  2381. c.chLock.Lock()
  2382. stop := len(c.chR) == 0 && len(c.chW) == 0
  2383. if !stop {
  2384. c.chR = nil
  2385. c.chW = nil
  2386. }
  2387. c.chLock.Unlock()
  2388. if stop {
  2389. break
  2390. }
  2391. }
  2392. }
  2393. }()
  2394. }
  2395. c.chLock.Unlock()
  2396. }
  2397. func (c *pipelineConnClient) worker() error {
  2398. tlsConfig := c.cachedTLSConfig()
  2399. conn, err := dialAddr(c.Addr, c.Dial, nil, c.DialDualStack, c.IsTLS, tlsConfig, 0, c.WriteTimeout)
  2400. if err != nil {
  2401. return err
  2402. }
  2403. // Start reader and writer
  2404. stopW := make(chan struct{})
  2405. doneW := make(chan error)
  2406. go func() {
  2407. doneW <- c.writer(conn, stopW)
  2408. }()
  2409. stopR := make(chan struct{})
  2410. doneR := make(chan error)
  2411. go func() {
  2412. doneR <- c.reader(conn, stopR)
  2413. }()
  2414. // Wait until reader and writer are stopped
  2415. select {
  2416. case err = <-doneW:
  2417. conn.Close()
  2418. close(stopR)
  2419. <-doneR
  2420. case err = <-doneR:
  2421. conn.Close()
  2422. close(stopW)
  2423. <-doneW
  2424. }
  2425. // Notify pending readers
  2426. for len(c.chR) > 0 {
  2427. w := <-c.chR
  2428. w.err = errPipelineConnStopped
  2429. w.done <- struct{}{}
  2430. }
  2431. return err
  2432. }
  2433. func (c *pipelineConnClient) cachedTLSConfig() *tls.Config {
  2434. if !c.IsTLS {
  2435. return nil
  2436. }
  2437. c.tlsConfigLock.Lock()
  2438. cfg := c.tlsConfig
  2439. if cfg == nil {
  2440. cfg = newClientTLSConfig(c.TLSConfig, c.Addr)
  2441. c.tlsConfig = cfg
  2442. }
  2443. c.tlsConfigLock.Unlock()
  2444. return cfg
  2445. }
  2446. func (c *pipelineConnClient) writer(conn net.Conn, stopCh <-chan struct{}) error {
  2447. writeBufferSize := c.WriteBufferSize
  2448. if writeBufferSize <= 0 {
  2449. writeBufferSize = defaultWriteBufferSize
  2450. }
  2451. bw := bufio.NewWriterSize(conn, writeBufferSize)
  2452. defer bw.Flush()
  2453. chR := c.chR
  2454. chW := c.chW
  2455. writeTimeout := c.WriteTimeout
  2456. maxIdleConnDuration := c.MaxIdleConnDuration
  2457. if maxIdleConnDuration <= 0 {
  2458. maxIdleConnDuration = DefaultMaxIdleConnDuration
  2459. }
  2460. maxBatchDelay := c.MaxBatchDelay
  2461. var (
  2462. stopTimer = time.NewTimer(time.Hour)
  2463. flushTimer = time.NewTimer(time.Hour)
  2464. flushTimerCh <-chan time.Time
  2465. instantTimerCh = make(chan time.Time)
  2466. w *pipelineWork
  2467. err error
  2468. )
  2469. close(instantTimerCh)
  2470. for {
  2471. againChW:
  2472. select {
  2473. case w = <-chW:
  2474. // Fast path: len(chW) > 0
  2475. default:
  2476. // Slow path
  2477. stopTimer.Reset(maxIdleConnDuration)
  2478. select {
  2479. case w = <-chW:
  2480. case <-stopTimer.C:
  2481. return nil
  2482. case <-stopCh:
  2483. return nil
  2484. case <-flushTimerCh:
  2485. if err = bw.Flush(); err != nil {
  2486. return err
  2487. }
  2488. flushTimerCh = nil
  2489. goto againChW
  2490. }
  2491. }
  2492. if !w.deadline.IsZero() && time.Since(w.deadline) >= 0 {
  2493. w.err = ErrTimeout
  2494. w.done <- struct{}{}
  2495. continue
  2496. }
  2497. w.resp.ParseNetConn(conn)
  2498. if writeTimeout > 0 {
  2499. // Set Deadline every time, since golang has fixed the performance issue
  2500. // See https://github.com/golang/go/issues/15133#issuecomment-271571395 for details
  2501. currentTime := time.Now()
  2502. if err = conn.SetWriteDeadline(currentTime.Add(writeTimeout)); err != nil {
  2503. w.err = err
  2504. w.done <- struct{}{}
  2505. return err
  2506. }
  2507. }
  2508. if err = w.req.Write(bw); err != nil {
  2509. w.err = err
  2510. w.done <- struct{}{}
  2511. return err
  2512. }
  2513. if flushTimerCh == nil && (len(chW) == 0 || len(chR) == cap(chR)) {
  2514. if maxBatchDelay > 0 {
  2515. flushTimer.Reset(maxBatchDelay)
  2516. flushTimerCh = flushTimer.C
  2517. } else {
  2518. flushTimerCh = instantTimerCh
  2519. }
  2520. }
  2521. againChR:
  2522. select {
  2523. case chR <- w:
  2524. // Fast path: len(chR) < cap(chR)
  2525. default:
  2526. // Slow path
  2527. select {
  2528. case chR <- w:
  2529. case <-stopCh:
  2530. w.err = errPipelineConnStopped
  2531. w.done <- struct{}{}
  2532. return nil
  2533. case <-flushTimerCh:
  2534. if err = bw.Flush(); err != nil {
  2535. w.err = err
  2536. w.done <- struct{}{}
  2537. return err
  2538. }
  2539. flushTimerCh = nil
  2540. goto againChR
  2541. }
  2542. }
  2543. }
  2544. }
  2545. func (c *pipelineConnClient) reader(conn net.Conn, stopCh <-chan struct{}) error {
  2546. readBufferSize := c.ReadBufferSize
  2547. if readBufferSize <= 0 {
  2548. readBufferSize = defaultReadBufferSize
  2549. }
  2550. br := bufio.NewReaderSize(conn, readBufferSize)
  2551. chR := c.chR
  2552. readTimeout := c.ReadTimeout
  2553. var (
  2554. w *pipelineWork
  2555. err error
  2556. )
  2557. for {
  2558. select {
  2559. case w = <-chR:
  2560. // Fast path: len(chR) > 0
  2561. default:
  2562. // Slow path
  2563. select {
  2564. case w = <-chR:
  2565. case <-stopCh:
  2566. return nil
  2567. }
  2568. }
  2569. if readTimeout > 0 {
  2570. // Set Deadline every time, since golang has fixed the performance issue
  2571. // See https://github.com/golang/go/issues/15133#issuecomment-271571395 for details
  2572. currentTime := time.Now()
  2573. if err = conn.SetReadDeadline(currentTime.Add(readTimeout)); err != nil {
  2574. w.err = err
  2575. w.done <- struct{}{}
  2576. return err
  2577. }
  2578. }
  2579. if err = w.resp.Read(br); err != nil {
  2580. w.err = err
  2581. w.done <- struct{}{}
  2582. return err
  2583. }
  2584. w.done <- struct{}{}
  2585. }
  2586. }
  2587. func (c *pipelineConnClient) logger() Logger {
  2588. if c.Logger != nil {
  2589. return c.Logger
  2590. }
  2591. return defaultLogger
  2592. }
  2593. // PendingRequests returns the current number of pending requests pipelined
  2594. // to the server.
  2595. //
  2596. // This number may exceed MaxPendingRequests*MaxConns by up to two times, since
  2597. // each connection to the server may keep up to MaxPendingRequests requests
  2598. // in the queue before sending them to the server.
  2599. //
  2600. // This function may be used for balancing load among multiple PipelineClient
  2601. // instances.
  2602. func (c *PipelineClient) PendingRequests() int {
  2603. c.connClientsLock.Lock()
  2604. n := 0
  2605. for _, cc := range c.connClients {
  2606. n += cc.PendingRequests()
  2607. }
  2608. c.connClientsLock.Unlock()
  2609. return n
  2610. }
  2611. func (c *pipelineConnClient) PendingRequests() int {
  2612. c.init()
  2613. c.chLock.Lock()
  2614. n := len(c.chR) + len(c.chW)
  2615. c.chLock.Unlock()
  2616. return n
  2617. }
  2618. var errPipelineConnStopped = errors.New("pipeline connection has been stopped")
  2619. var DefaultTransport RoundTripper = &transport{}
  2620. type transport struct{}
  2621. func (t *transport) RoundTrip(hc *HostClient, req *Request, resp *Response) (retry bool, err error) {
  2622. customSkipBody := resp.SkipBody
  2623. customStreamBody := resp.StreamBody
  2624. var deadline time.Time
  2625. if req.timeout > 0 {
  2626. deadline = time.Now().Add(req.timeout)
  2627. }
  2628. cc, err := hc.AcquireConn(req.timeout, req.ConnectionClose())
  2629. if err != nil {
  2630. return false, err
  2631. }
  2632. conn := cc.c
  2633. resp.ParseNetConn(conn)
  2634. writeDeadline := deadline
  2635. if hc.WriteTimeout > 0 {
  2636. tmpWriteDeadline := time.Now().Add(hc.WriteTimeout)
  2637. if writeDeadline.IsZero() || tmpWriteDeadline.Before(writeDeadline) {
  2638. writeDeadline = tmpWriteDeadline
  2639. }
  2640. }
  2641. if err = conn.SetWriteDeadline(writeDeadline); err != nil {
  2642. hc.CloseConn(cc)
  2643. return true, err
  2644. }
  2645. resetConnection := false
  2646. if hc.MaxConnDuration > 0 && time.Since(cc.createdTime) > hc.MaxConnDuration && !req.ConnectionClose() {
  2647. req.SetConnectionClose()
  2648. resetConnection = true
  2649. }
  2650. bw := hc.AcquireWriter(conn)
  2651. err = req.Write(bw)
  2652. if resetConnection {
  2653. req.Header.ResetConnectionClose()
  2654. }
  2655. if err == nil {
  2656. err = bw.Flush()
  2657. }
  2658. hc.ReleaseWriter(bw)
  2659. // Return ErrTimeout on any timeout.
  2660. if x, ok := err.(interface{ Timeout() bool }); ok && x.Timeout() {
  2661. err = ErrTimeout
  2662. }
  2663. if err != nil {
  2664. hc.CloseConn(cc)
  2665. return true, err
  2666. }
  2667. readDeadline := deadline
  2668. if hc.ReadTimeout > 0 {
  2669. tmpReadDeadline := time.Now().Add(hc.ReadTimeout)
  2670. if readDeadline.IsZero() || tmpReadDeadline.Before(readDeadline) {
  2671. readDeadline = tmpReadDeadline
  2672. }
  2673. }
  2674. if err = conn.SetReadDeadline(readDeadline); err != nil {
  2675. hc.CloseConn(cc)
  2676. return true, err
  2677. }
  2678. if customSkipBody || req.Header.IsHead() {
  2679. resp.SkipBody = true
  2680. }
  2681. if hc.DisableHeaderNamesNormalizing {
  2682. resp.Header.DisableNormalizing()
  2683. }
  2684. br := hc.AcquireReader(conn)
  2685. err = resp.ReadLimitBody(br, hc.MaxResponseBodySize)
  2686. if err != nil {
  2687. hc.ReleaseReader(br)
  2688. hc.CloseConn(cc)
  2689. // Don't retry in case of ErrBodyTooLarge since we will just get the same again.
  2690. needRetry := err != ErrBodyTooLarge
  2691. return needRetry, err
  2692. }
  2693. closeConn := resetConnection || req.ConnectionClose() || resp.ConnectionClose()
  2694. if customStreamBody && resp.bodyStream != nil {
  2695. rbs := resp.bodyStream
  2696. resp.bodyStream = newCloseReaderWithError(rbs, func(wErr error) error {
  2697. hc.ReleaseReader(br)
  2698. if r, ok := rbs.(*requestStream); ok {
  2699. releaseRequestStream(r)
  2700. }
  2701. if closeConn || resp.ConnectionClose() || wErr != nil {
  2702. hc.CloseConn(cc)
  2703. } else {
  2704. hc.ReleaseConn(cc)
  2705. }
  2706. return nil
  2707. })
  2708. return false, nil
  2709. }
  2710. hc.ReleaseReader(br)
  2711. if closeConn {
  2712. hc.CloseConn(cc)
  2713. } else {
  2714. hc.ReleaseConn(cc)
  2715. }
  2716. return false, nil
  2717. }