http.go 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358
  1. package fasthttp
  2. import (
  3. "bufio"
  4. "bytes"
  5. "compress/gzip"
  6. "encoding/base64"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "mime/multipart"
  11. "net"
  12. "os"
  13. "sync"
  14. "time"
  15. "github.com/valyala/bytebufferpool"
  16. )
  17. var (
  18. requestBodyPoolSizeLimit = -1
  19. responseBodyPoolSizeLimit = -1
  20. )
  21. // SetBodySizePoolLimit set the max body size for bodies to be returned to the pool.
  22. // If the body size is larger it will be released instead of put back into the pool for reuse.
  23. func SetBodySizePoolLimit(reqBodyLimit, respBodyLimit int) {
  24. requestBodyPoolSizeLimit = reqBodyLimit
  25. responseBodyPoolSizeLimit = respBodyLimit
  26. }
  27. // Request represents HTTP request.
  28. //
  29. // It is forbidden copying Request instances. Create new instances
  30. // and use CopyTo instead.
  31. //
  32. // Request instance MUST NOT be used from concurrently running goroutines.
  33. type Request struct {
  34. noCopy noCopy
  35. // Request header
  36. //
  37. // Copying Header by value is forbidden. Use pointer to Header instead.
  38. Header RequestHeader
  39. uri URI
  40. postArgs Args
  41. bodyStream io.Reader
  42. w requestBodyWriter
  43. body *bytebufferpool.ByteBuffer
  44. bodyRaw []byte
  45. multipartForm *multipart.Form
  46. multipartFormBoundary string
  47. secureErrorLogMessage bool
  48. // Group bool members in order to reduce Request object size.
  49. parsedURI bool
  50. parsedPostArgs bool
  51. keepBodyBuffer bool
  52. // Used by Server to indicate the request was received on a HTTPS endpoint.
  53. // Client/HostClient shouldn't use this field but should depend on the uri.scheme instead.
  54. isTLS bool
  55. // Request timeout. Usually set by DoDeadline or DoTimeout
  56. // if <= 0, means not set
  57. timeout time.Duration
  58. // Use Host header (request.Header.SetHost) instead of the host from SetRequestURI, SetHost, or URI().SetHost
  59. UseHostHeader bool
  60. // DisableRedirectPathNormalizing disables redirect path normalization when used with DoRedirects.
  61. //
  62. // By default redirect path values are normalized, i.e.
  63. // extra slashes are removed, special characters are encoded.
  64. DisableRedirectPathNormalizing bool
  65. }
  66. // Response represents HTTP response.
  67. //
  68. // It is forbidden copying Response instances. Create new instances
  69. // and use CopyTo instead.
  70. //
  71. // Response instance MUST NOT be used from concurrently running goroutines.
  72. type Response struct {
  73. noCopy noCopy
  74. // Response header
  75. //
  76. // Copying Header by value is forbidden. Use pointer to Header instead.
  77. Header ResponseHeader
  78. // Flush headers as soon as possible without waiting for first body bytes.
  79. // Relevant for bodyStream only.
  80. ImmediateHeaderFlush bool
  81. // StreamBody enables response body streaming.
  82. // Use SetBodyStream to set the body stream.
  83. StreamBody bool
  84. bodyStream io.Reader
  85. w responseBodyWriter
  86. body *bytebufferpool.ByteBuffer
  87. bodyRaw []byte
  88. // Response.Read() skips reading body if set to true.
  89. // Use it for reading HEAD responses.
  90. //
  91. // Response.Write() skips writing body if set to true.
  92. // Use it for writing HEAD responses.
  93. SkipBody bool
  94. keepBodyBuffer bool
  95. secureErrorLogMessage bool
  96. // Remote TCPAddr from concurrently net.Conn
  97. raddr net.Addr
  98. // Local TCPAddr from concurrently net.Conn
  99. laddr net.Addr
  100. }
  101. // SetHost sets host for the request.
  102. func (req *Request) SetHost(host string) {
  103. req.URI().SetHost(host)
  104. }
  105. // SetHostBytes sets host for the request.
  106. func (req *Request) SetHostBytes(host []byte) {
  107. req.URI().SetHostBytes(host)
  108. }
  109. // Host returns the host for the given request.
  110. func (req *Request) Host() []byte {
  111. return req.URI().Host()
  112. }
  113. // SetRequestURI sets RequestURI.
  114. func (req *Request) SetRequestURI(requestURI string) {
  115. req.Header.SetRequestURI(requestURI)
  116. req.parsedURI = false
  117. }
  118. // SetRequestURIBytes sets RequestURI.
  119. func (req *Request) SetRequestURIBytes(requestURI []byte) {
  120. req.Header.SetRequestURIBytes(requestURI)
  121. req.parsedURI = false
  122. }
  123. // RequestURI returns request's URI.
  124. func (req *Request) RequestURI() []byte {
  125. if req.parsedURI {
  126. requestURI := req.uri.RequestURI()
  127. req.SetRequestURIBytes(requestURI)
  128. }
  129. return req.Header.RequestURI()
  130. }
  131. // StatusCode returns response status code.
  132. func (resp *Response) StatusCode() int {
  133. return resp.Header.StatusCode()
  134. }
  135. // SetStatusCode sets response status code.
  136. func (resp *Response) SetStatusCode(statusCode int) {
  137. resp.Header.SetStatusCode(statusCode)
  138. }
  139. // ConnectionClose returns true if 'Connection: close' header is set.
  140. func (resp *Response) ConnectionClose() bool {
  141. return resp.Header.ConnectionClose()
  142. }
  143. // SetConnectionClose sets 'Connection: close' header.
  144. func (resp *Response) SetConnectionClose() {
  145. resp.Header.SetConnectionClose()
  146. }
  147. // ConnectionClose returns true if 'Connection: close' header is set.
  148. func (req *Request) ConnectionClose() bool {
  149. return req.Header.ConnectionClose()
  150. }
  151. // SetConnectionClose sets 'Connection: close' header.
  152. func (req *Request) SetConnectionClose() {
  153. req.Header.SetConnectionClose()
  154. }
  155. // SendFile registers file on the given path to be used as response body
  156. // when Write is called.
  157. //
  158. // Note that SendFile doesn't set Content-Type, so set it yourself
  159. // with Header.SetContentType.
  160. func (resp *Response) SendFile(path string) error {
  161. f, err := os.Open(path)
  162. if err != nil {
  163. return err
  164. }
  165. fileInfo, err := f.Stat()
  166. if err != nil {
  167. f.Close()
  168. return err
  169. }
  170. size64 := fileInfo.Size()
  171. size := int(size64)
  172. if int64(size) != size64 {
  173. size = -1
  174. }
  175. resp.Header.SetLastModified(fileInfo.ModTime())
  176. resp.SetBodyStream(f, size)
  177. return nil
  178. }
  179. // SetBodyStream sets request body stream and, optionally body size.
  180. //
  181. // If bodySize is >= 0, then the bodyStream must provide exactly bodySize bytes
  182. // before returning io.EOF.
  183. //
  184. // If bodySize < 0, then bodyStream is read until io.EOF.
  185. //
  186. // bodyStream.Close() is called after finishing reading all body data
  187. // if it implements io.Closer.
  188. //
  189. // Note that GET and HEAD requests cannot have body.
  190. //
  191. // See also SetBodyStreamWriter.
  192. func (req *Request) SetBodyStream(bodyStream io.Reader, bodySize int) {
  193. req.ResetBody()
  194. req.bodyStream = bodyStream
  195. req.Header.SetContentLength(bodySize)
  196. }
  197. // SetBodyStream sets response body stream and, optionally body size.
  198. //
  199. // If bodySize is >= 0, then the bodyStream must provide exactly bodySize bytes
  200. // before returning io.EOF.
  201. //
  202. // If bodySize < 0, then bodyStream is read until io.EOF.
  203. //
  204. // bodyStream.Close() is called after finishing reading all body data
  205. // if it implements io.Closer.
  206. //
  207. // See also SetBodyStreamWriter.
  208. func (resp *Response) SetBodyStream(bodyStream io.Reader, bodySize int) {
  209. resp.ResetBody()
  210. resp.bodyStream = bodyStream
  211. resp.Header.SetContentLength(bodySize)
  212. }
  213. // IsBodyStream returns true if body is set via SetBodyStream*
  214. func (req *Request) IsBodyStream() bool {
  215. return req.bodyStream != nil
  216. }
  217. // IsBodyStream returns true if body is set via SetBodyStream*
  218. func (resp *Response) IsBodyStream() bool {
  219. return resp.bodyStream != nil
  220. }
  221. // SetBodyStreamWriter registers the given sw for populating request body.
  222. //
  223. // This function may be used in the following cases:
  224. //
  225. // - if request body is too big (more than 10MB).
  226. // - if request body is streamed from slow external sources.
  227. // - if request body must be streamed to the server in chunks
  228. // (aka `http client push` or `chunked transfer-encoding`).
  229. //
  230. // Note that GET and HEAD requests cannot have body.
  231. //
  232. // See also SetBodyStream.
  233. func (req *Request) SetBodyStreamWriter(sw StreamWriter) {
  234. sr := NewStreamReader(sw)
  235. req.SetBodyStream(sr, -1)
  236. }
  237. // SetBodyStreamWriter registers the given sw for populating response body.
  238. //
  239. // This function may be used in the following cases:
  240. //
  241. // - if response body is too big (more than 10MB).
  242. // - if response body is streamed from slow external sources.
  243. // - if response body must be streamed to the client in chunks
  244. // (aka `http server push` or `chunked transfer-encoding`).
  245. //
  246. // See also SetBodyStream.
  247. func (resp *Response) SetBodyStreamWriter(sw StreamWriter) {
  248. sr := NewStreamReader(sw)
  249. resp.SetBodyStream(sr, -1)
  250. }
  251. // BodyWriter returns writer for populating response body.
  252. //
  253. // If used inside RequestHandler, the returned writer must not be used
  254. // after returning from RequestHandler. Use RequestCtx.Write
  255. // or SetBodyStreamWriter in this case.
  256. func (resp *Response) BodyWriter() io.Writer {
  257. resp.w.r = resp
  258. return &resp.w
  259. }
  260. // BodyStream returns io.Reader
  261. //
  262. // You must CloseBodyStream or ReleaseRequest after you use it.
  263. func (req *Request) BodyStream() io.Reader {
  264. return req.bodyStream
  265. }
  266. func (req *Request) CloseBodyStream() error {
  267. return req.closeBodyStream()
  268. }
  269. // BodyStream returns io.Reader
  270. //
  271. // You must CloseBodyStream or ReleaseResponse after you use it.
  272. func (resp *Response) BodyStream() io.Reader {
  273. return resp.bodyStream
  274. }
  275. func (resp *Response) CloseBodyStream() error {
  276. return resp.closeBodyStream()
  277. }
  278. type closeReader struct {
  279. io.Reader
  280. closeFunc func() error
  281. }
  282. func newCloseReader(r io.Reader, closeFunc func() error) io.ReadCloser {
  283. if r == nil {
  284. panic(`BUG: reader is nil`)
  285. }
  286. return &closeReader{Reader: r, closeFunc: closeFunc}
  287. }
  288. func (c *closeReader) Close() error {
  289. if c.closeFunc == nil {
  290. return nil
  291. }
  292. return c.closeFunc()
  293. }
  294. // BodyWriter returns writer for populating request body.
  295. func (req *Request) BodyWriter() io.Writer {
  296. req.w.r = req
  297. return &req.w
  298. }
  299. type responseBodyWriter struct {
  300. r *Response
  301. }
  302. func (w *responseBodyWriter) Write(p []byte) (int, error) {
  303. w.r.AppendBody(p)
  304. return len(p), nil
  305. }
  306. type requestBodyWriter struct {
  307. r *Request
  308. }
  309. func (w *requestBodyWriter) Write(p []byte) (int, error) {
  310. w.r.AppendBody(p)
  311. return len(p), nil
  312. }
  313. func (resp *Response) parseNetConn(conn net.Conn) {
  314. resp.raddr = conn.RemoteAddr()
  315. resp.laddr = conn.LocalAddr()
  316. }
  317. // RemoteAddr returns the remote network address. The Addr returned is shared
  318. // by all invocations of RemoteAddr, so do not modify it.
  319. func (resp *Response) RemoteAddr() net.Addr {
  320. return resp.raddr
  321. }
  322. // LocalAddr returns the local network address. The Addr returned is shared
  323. // by all invocations of LocalAddr, so do not modify it.
  324. func (resp *Response) LocalAddr() net.Addr {
  325. return resp.laddr
  326. }
  327. // Body returns response body.
  328. //
  329. // The returned value is valid until the response is released,
  330. // either though ReleaseResponse or your request handler returning.
  331. // Do not store references to returned value. Make copies instead.
  332. func (resp *Response) Body() []byte {
  333. if resp.bodyStream != nil {
  334. bodyBuf := resp.bodyBuffer()
  335. bodyBuf.Reset()
  336. _, err := copyZeroAlloc(bodyBuf, resp.bodyStream)
  337. resp.closeBodyStream() //nolint:errcheck
  338. if err != nil {
  339. bodyBuf.SetString(err.Error())
  340. }
  341. }
  342. return resp.bodyBytes()
  343. }
  344. func (resp *Response) bodyBytes() []byte {
  345. if resp.bodyRaw != nil {
  346. return resp.bodyRaw
  347. }
  348. if resp.body == nil {
  349. return nil
  350. }
  351. return resp.body.B
  352. }
  353. func (req *Request) bodyBytes() []byte {
  354. if req.bodyRaw != nil {
  355. return req.bodyRaw
  356. }
  357. if req.bodyStream != nil {
  358. bodyBuf := req.bodyBuffer()
  359. bodyBuf.Reset()
  360. _, err := copyZeroAlloc(bodyBuf, req.bodyStream)
  361. req.closeBodyStream() //nolint:errcheck
  362. if err != nil {
  363. bodyBuf.SetString(err.Error())
  364. }
  365. }
  366. if req.body == nil {
  367. return nil
  368. }
  369. return req.body.B
  370. }
  371. func (resp *Response) bodyBuffer() *bytebufferpool.ByteBuffer {
  372. if resp.body == nil {
  373. resp.body = responseBodyPool.Get()
  374. }
  375. resp.bodyRaw = nil
  376. return resp.body
  377. }
  378. func (req *Request) bodyBuffer() *bytebufferpool.ByteBuffer {
  379. if req.body == nil {
  380. req.body = requestBodyPool.Get()
  381. }
  382. req.bodyRaw = nil
  383. return req.body
  384. }
  385. var (
  386. responseBodyPool bytebufferpool.Pool
  387. requestBodyPool bytebufferpool.Pool
  388. )
  389. // BodyGunzip returns un-gzipped body data.
  390. //
  391. // This method may be used if the request header contains
  392. // 'Content-Encoding: gzip' for reading un-gzipped body.
  393. // Use Body for reading gzipped request body.
  394. func (req *Request) BodyGunzip() ([]byte, error) {
  395. return gunzipData(req.Body())
  396. }
  397. // BodyGunzip returns un-gzipped body data.
  398. //
  399. // This method may be used if the response header contains
  400. // 'Content-Encoding: gzip' for reading un-gzipped body.
  401. // Use Body for reading gzipped response body.
  402. func (resp *Response) BodyGunzip() ([]byte, error) {
  403. return gunzipData(resp.Body())
  404. }
  405. func gunzipData(p []byte) ([]byte, error) {
  406. var bb bytebufferpool.ByteBuffer
  407. _, err := WriteGunzip(&bb, p)
  408. if err != nil {
  409. return nil, err
  410. }
  411. return bb.B, nil
  412. }
  413. // BodyUnbrotli returns un-brotlied body data.
  414. //
  415. // This method may be used if the request header contains
  416. // 'Content-Encoding: br' for reading un-brotlied body.
  417. // Use Body for reading brotlied request body.
  418. func (req *Request) BodyUnbrotli() ([]byte, error) {
  419. return unBrotliData(req.Body())
  420. }
  421. // BodyUnbrotli returns un-brotlied body data.
  422. //
  423. // This method may be used if the response header contains
  424. // 'Content-Encoding: br' for reading un-brotlied body.
  425. // Use Body for reading brotlied response body.
  426. func (resp *Response) BodyUnbrotli() ([]byte, error) {
  427. return unBrotliData(resp.Body())
  428. }
  429. func unBrotliData(p []byte) ([]byte, error) {
  430. var bb bytebufferpool.ByteBuffer
  431. _, err := WriteUnbrotli(&bb, p)
  432. if err != nil {
  433. return nil, err
  434. }
  435. return bb.B, nil
  436. }
  437. // BodyInflate returns inflated body data.
  438. //
  439. // This method may be used if the response header contains
  440. // 'Content-Encoding: deflate' for reading inflated request body.
  441. // Use Body for reading deflated request body.
  442. func (req *Request) BodyInflate() ([]byte, error) {
  443. return inflateData(req.Body())
  444. }
  445. // BodyInflate returns inflated body data.
  446. //
  447. // This method may be used if the response header contains
  448. // 'Content-Encoding: deflate' for reading inflated response body.
  449. // Use Body for reading deflated response body.
  450. func (resp *Response) BodyInflate() ([]byte, error) {
  451. return inflateData(resp.Body())
  452. }
  453. func (ctx *RequestCtx) RequestBodyStream() io.Reader {
  454. return ctx.Request.bodyStream
  455. }
  456. func inflateData(p []byte) ([]byte, error) {
  457. var bb bytebufferpool.ByteBuffer
  458. _, err := WriteInflate(&bb, p)
  459. if err != nil {
  460. return nil, err
  461. }
  462. return bb.B, nil
  463. }
  464. var ErrContentEncodingUnsupported = errors.New("unsupported Content-Encoding")
  465. // BodyUncompressed returns body data and if needed decompress it from gzip, deflate or Brotli.
  466. //
  467. // This method may be used if the response header contains
  468. // 'Content-Encoding' for reading uncompressed request body.
  469. // Use Body for reading the raw request body.
  470. func (req *Request) BodyUncompressed() ([]byte, error) {
  471. switch string(req.Header.ContentEncoding()) {
  472. case "":
  473. return req.Body(), nil
  474. case "deflate":
  475. return req.BodyInflate()
  476. case "gzip":
  477. return req.BodyGunzip()
  478. case "br":
  479. return req.BodyUnbrotli()
  480. default:
  481. return nil, ErrContentEncodingUnsupported
  482. }
  483. }
  484. // BodyUncompressed returns body data and if needed decompress it from gzip, deflate or Brotli.
  485. //
  486. // This method may be used if the response header contains
  487. // 'Content-Encoding' for reading uncompressed response body.
  488. // Use Body for reading the raw response body.
  489. func (resp *Response) BodyUncompressed() ([]byte, error) {
  490. switch string(resp.Header.ContentEncoding()) {
  491. case "":
  492. return resp.Body(), nil
  493. case "deflate":
  494. return resp.BodyInflate()
  495. case "gzip":
  496. return resp.BodyGunzip()
  497. case "br":
  498. return resp.BodyUnbrotli()
  499. default:
  500. return nil, ErrContentEncodingUnsupported
  501. }
  502. }
  503. // BodyWriteTo writes request body to w.
  504. func (req *Request) BodyWriteTo(w io.Writer) error {
  505. if req.bodyStream != nil {
  506. _, err := copyZeroAlloc(w, req.bodyStream)
  507. req.closeBodyStream() //nolint:errcheck
  508. return err
  509. }
  510. if req.onlyMultipartForm() {
  511. return WriteMultipartForm(w, req.multipartForm, req.multipartFormBoundary)
  512. }
  513. _, err := w.Write(req.bodyBytes())
  514. return err
  515. }
  516. // BodyWriteTo writes response body to w.
  517. func (resp *Response) BodyWriteTo(w io.Writer) error {
  518. if resp.bodyStream != nil {
  519. _, err := copyZeroAlloc(w, resp.bodyStream)
  520. resp.closeBodyStream() //nolint:errcheck
  521. return err
  522. }
  523. _, err := w.Write(resp.bodyBytes())
  524. return err
  525. }
  526. // AppendBody appends p to response body.
  527. //
  528. // It is safe re-using p after the function returns.
  529. func (resp *Response) AppendBody(p []byte) {
  530. resp.closeBodyStream() //nolint:errcheck
  531. resp.bodyBuffer().Write(p) //nolint:errcheck
  532. }
  533. // AppendBodyString appends s to response body.
  534. func (resp *Response) AppendBodyString(s string) {
  535. resp.closeBodyStream() //nolint:errcheck
  536. resp.bodyBuffer().WriteString(s) //nolint:errcheck
  537. }
  538. // SetBody sets response body.
  539. //
  540. // It is safe re-using body argument after the function returns.
  541. func (resp *Response) SetBody(body []byte) {
  542. resp.closeBodyStream() //nolint:errcheck
  543. bodyBuf := resp.bodyBuffer()
  544. bodyBuf.Reset()
  545. bodyBuf.Write(body) //nolint:errcheck
  546. }
  547. // SetBodyString sets response body.
  548. func (resp *Response) SetBodyString(body string) {
  549. resp.closeBodyStream() //nolint:errcheck
  550. bodyBuf := resp.bodyBuffer()
  551. bodyBuf.Reset()
  552. bodyBuf.WriteString(body) //nolint:errcheck
  553. }
  554. // ResetBody resets response body.
  555. func (resp *Response) ResetBody() {
  556. resp.bodyRaw = nil
  557. resp.closeBodyStream() //nolint:errcheck
  558. if resp.body != nil {
  559. if resp.keepBodyBuffer {
  560. resp.body.Reset()
  561. } else {
  562. responseBodyPool.Put(resp.body)
  563. resp.body = nil
  564. }
  565. }
  566. }
  567. // SetBodyRaw sets response body, but without copying it.
  568. //
  569. // From this point onward the body argument must not be changed.
  570. func (resp *Response) SetBodyRaw(body []byte) {
  571. resp.ResetBody()
  572. resp.bodyRaw = body
  573. }
  574. // SetBodyRaw sets response body, but without copying it.
  575. //
  576. // From this point onward the body argument must not be changed.
  577. func (req *Request) SetBodyRaw(body []byte) {
  578. req.ResetBody()
  579. req.bodyRaw = body
  580. }
  581. // ReleaseBody retires the response body if it is greater than "size" bytes.
  582. //
  583. // This permits GC to reclaim the large buffer. If used, must be before
  584. // ReleaseResponse.
  585. //
  586. // Use this method only if you really understand how it works.
  587. // The majority of workloads don't need this method.
  588. func (resp *Response) ReleaseBody(size int) {
  589. resp.bodyRaw = nil
  590. if resp.body == nil {
  591. return
  592. }
  593. if cap(resp.body.B) > size {
  594. resp.closeBodyStream() //nolint:errcheck
  595. resp.body = nil
  596. }
  597. }
  598. // ReleaseBody retires the request body if it is greater than "size" bytes.
  599. //
  600. // This permits GC to reclaim the large buffer. If used, must be before
  601. // ReleaseRequest.
  602. //
  603. // Use this method only if you really understand how it works.
  604. // The majority of workloads don't need this method.
  605. func (req *Request) ReleaseBody(size int) {
  606. req.bodyRaw = nil
  607. if req.body == nil {
  608. return
  609. }
  610. if cap(req.body.B) > size {
  611. req.closeBodyStream() //nolint:errcheck
  612. req.body = nil
  613. }
  614. }
  615. // SwapBody swaps response body with the given body and returns
  616. // the previous response body.
  617. //
  618. // It is forbidden to use the body passed to SwapBody after
  619. // the function returns.
  620. func (resp *Response) SwapBody(body []byte) []byte {
  621. bb := resp.bodyBuffer()
  622. if resp.bodyStream != nil {
  623. bb.Reset()
  624. _, err := copyZeroAlloc(bb, resp.bodyStream)
  625. resp.closeBodyStream() //nolint:errcheck
  626. if err != nil {
  627. bb.Reset()
  628. bb.SetString(err.Error())
  629. }
  630. }
  631. resp.bodyRaw = nil
  632. oldBody := bb.B
  633. bb.B = body
  634. return oldBody
  635. }
  636. // SwapBody swaps request body with the given body and returns
  637. // the previous request body.
  638. //
  639. // It is forbidden to use the body passed to SwapBody after
  640. // the function returns.
  641. func (req *Request) SwapBody(body []byte) []byte {
  642. bb := req.bodyBuffer()
  643. if req.bodyStream != nil {
  644. bb.Reset()
  645. _, err := copyZeroAlloc(bb, req.bodyStream)
  646. req.closeBodyStream() //nolint:errcheck
  647. if err != nil {
  648. bb.Reset()
  649. bb.SetString(err.Error())
  650. }
  651. }
  652. req.bodyRaw = nil
  653. oldBody := bb.B
  654. bb.B = body
  655. return oldBody
  656. }
  657. // Body returns request body.
  658. //
  659. // The returned value is valid until the request is released,
  660. // either though ReleaseRequest or your request handler returning.
  661. // Do not store references to returned value. Make copies instead.
  662. func (req *Request) Body() []byte {
  663. if req.bodyRaw != nil {
  664. return req.bodyRaw
  665. } else if req.onlyMultipartForm() {
  666. body, err := marshalMultipartForm(req.multipartForm, req.multipartFormBoundary)
  667. if err != nil {
  668. return []byte(err.Error())
  669. }
  670. return body
  671. }
  672. return req.bodyBytes()
  673. }
  674. // AppendBody appends p to request body.
  675. //
  676. // It is safe re-using p after the function returns.
  677. func (req *Request) AppendBody(p []byte) {
  678. req.RemoveMultipartFormFiles()
  679. req.closeBodyStream() //nolint:errcheck
  680. req.bodyBuffer().Write(p) //nolint:errcheck
  681. }
  682. // AppendBodyString appends s to request body.
  683. func (req *Request) AppendBodyString(s string) {
  684. req.RemoveMultipartFormFiles()
  685. req.closeBodyStream() //nolint:errcheck
  686. req.bodyBuffer().WriteString(s) //nolint:errcheck
  687. }
  688. // SetBody sets request body.
  689. //
  690. // It is safe re-using body argument after the function returns.
  691. func (req *Request) SetBody(body []byte) {
  692. req.RemoveMultipartFormFiles()
  693. req.closeBodyStream() //nolint:errcheck
  694. req.bodyBuffer().Set(body)
  695. }
  696. // SetBodyString sets request body.
  697. func (req *Request) SetBodyString(body string) {
  698. req.RemoveMultipartFormFiles()
  699. req.closeBodyStream() //nolint:errcheck
  700. req.bodyBuffer().SetString(body)
  701. }
  702. // ResetBody resets request body.
  703. func (req *Request) ResetBody() {
  704. req.bodyRaw = nil
  705. req.RemoveMultipartFormFiles()
  706. req.closeBodyStream() //nolint:errcheck
  707. if req.body != nil {
  708. if req.keepBodyBuffer {
  709. req.body.Reset()
  710. } else {
  711. requestBodyPool.Put(req.body)
  712. req.body = nil
  713. }
  714. }
  715. }
  716. // CopyTo copies req contents to dst except of body stream.
  717. func (req *Request) CopyTo(dst *Request) {
  718. req.copyToSkipBody(dst)
  719. switch {
  720. case req.bodyRaw != nil:
  721. dst.bodyRaw = append(dst.bodyRaw[:0], req.bodyRaw...)
  722. if dst.body != nil {
  723. dst.body.Reset()
  724. }
  725. case req.body != nil:
  726. dst.bodyBuffer().Set(req.body.B)
  727. case dst.body != nil:
  728. dst.body.Reset()
  729. }
  730. }
  731. func (req *Request) copyToSkipBody(dst *Request) {
  732. dst.Reset()
  733. req.Header.CopyTo(&dst.Header)
  734. req.uri.CopyTo(&dst.uri)
  735. dst.parsedURI = req.parsedURI
  736. req.postArgs.CopyTo(&dst.postArgs)
  737. dst.parsedPostArgs = req.parsedPostArgs
  738. dst.isTLS = req.isTLS
  739. dst.UseHostHeader = req.UseHostHeader
  740. // do not copy multipartForm - it will be automatically
  741. // re-created on the first call to MultipartForm.
  742. }
  743. // CopyTo copies resp contents to dst except of body stream.
  744. func (resp *Response) CopyTo(dst *Response) {
  745. resp.copyToSkipBody(dst)
  746. switch {
  747. case resp.bodyRaw != nil:
  748. dst.bodyRaw = append(dst.bodyRaw, resp.bodyRaw...)
  749. if dst.body != nil {
  750. dst.body.Reset()
  751. }
  752. case resp.body != nil:
  753. dst.bodyBuffer().Set(resp.body.B)
  754. case dst.body != nil:
  755. dst.body.Reset()
  756. }
  757. }
  758. func (resp *Response) copyToSkipBody(dst *Response) {
  759. dst.Reset()
  760. resp.Header.CopyTo(&dst.Header)
  761. dst.SkipBody = resp.SkipBody
  762. dst.raddr = resp.raddr
  763. dst.laddr = resp.laddr
  764. }
  765. func swapRequestBody(a, b *Request) {
  766. a.body, b.body = b.body, a.body
  767. a.bodyRaw, b.bodyRaw = b.bodyRaw, a.bodyRaw
  768. a.bodyStream, b.bodyStream = b.bodyStream, a.bodyStream
  769. // This code assumes that if a requestStream was swapped the headers are also swapped or copied.
  770. if rs, ok := a.bodyStream.(*requestStream); ok {
  771. rs.header = &a.Header
  772. }
  773. if rs, ok := b.bodyStream.(*requestStream); ok {
  774. rs.header = &b.Header
  775. }
  776. }
  777. func swapResponseBody(a, b *Response) {
  778. a.body, b.body = b.body, a.body
  779. a.bodyRaw, b.bodyRaw = b.bodyRaw, a.bodyRaw
  780. a.bodyStream, b.bodyStream = b.bodyStream, a.bodyStream
  781. }
  782. // URI returns request URI
  783. func (req *Request) URI() *URI {
  784. req.parseURI() //nolint:errcheck
  785. return &req.uri
  786. }
  787. // SetURI initializes request URI
  788. // Use this method if a single URI may be reused across multiple requests.
  789. // Otherwise, you can just use SetRequestURI() and it will be parsed as new URI.
  790. // The URI is copied and can be safely modified later.
  791. func (req *Request) SetURI(newURI *URI) {
  792. if newURI != nil {
  793. newURI.CopyTo(&req.uri)
  794. req.parsedURI = true
  795. return
  796. }
  797. req.uri.Reset()
  798. req.parsedURI = false
  799. }
  800. func (req *Request) parseURI() error {
  801. if req.parsedURI {
  802. return nil
  803. }
  804. req.parsedURI = true
  805. return req.uri.parse(req.Header.Host(), req.Header.RequestURI(), req.isTLS)
  806. }
  807. // PostArgs returns POST arguments.
  808. func (req *Request) PostArgs() *Args {
  809. req.parsePostArgs()
  810. return &req.postArgs
  811. }
  812. func (req *Request) parsePostArgs() {
  813. if req.parsedPostArgs {
  814. return
  815. }
  816. req.parsedPostArgs = true
  817. if !bytes.HasPrefix(req.Header.ContentType(), strPostArgsContentType) {
  818. return
  819. }
  820. req.postArgs.ParseBytes(req.bodyBytes())
  821. }
  822. // ErrNoMultipartForm means that the request's Content-Type
  823. // isn't 'multipart/form-data'.
  824. var ErrNoMultipartForm = errors.New("request Content-Type has bad boundary or is not multipart/form-data")
  825. // MultipartForm returns request's multipart form.
  826. //
  827. // Returns ErrNoMultipartForm if request's Content-Type
  828. // isn't 'multipart/form-data'.
  829. //
  830. // RemoveMultipartFormFiles must be called after returned multipart form
  831. // is processed.
  832. func (req *Request) MultipartForm() (*multipart.Form, error) {
  833. if req.multipartForm != nil {
  834. return req.multipartForm, nil
  835. }
  836. req.multipartFormBoundary = string(req.Header.MultipartFormBoundary())
  837. if len(req.multipartFormBoundary) == 0 {
  838. return nil, ErrNoMultipartForm
  839. }
  840. var err error
  841. ce := req.Header.peek(strContentEncoding)
  842. if req.bodyStream != nil {
  843. bodyStream := req.bodyStream
  844. if bytes.Equal(ce, strGzip) {
  845. // Do not care about memory usage here.
  846. if bodyStream, err = gzip.NewReader(bodyStream); err != nil {
  847. return nil, fmt.Errorf("cannot gunzip request body: %w", err)
  848. }
  849. } else if len(ce) > 0 {
  850. return nil, fmt.Errorf("unsupported Content-Encoding: %q", ce)
  851. }
  852. mr := multipart.NewReader(bodyStream, req.multipartFormBoundary)
  853. req.multipartForm, err = mr.ReadForm(8 * 1024)
  854. if err != nil {
  855. return nil, fmt.Errorf("cannot read multipart/form-data body: %w", err)
  856. }
  857. } else {
  858. body := req.bodyBytes()
  859. if bytes.Equal(ce, strGzip) {
  860. // Do not care about memory usage here.
  861. if body, err = AppendGunzipBytes(nil, body); err != nil {
  862. return nil, fmt.Errorf("cannot gunzip request body: %w", err)
  863. }
  864. } else if len(ce) > 0 {
  865. return nil, fmt.Errorf("unsupported Content-Encoding: %q", ce)
  866. }
  867. req.multipartForm, err = readMultipartForm(bytes.NewReader(body), req.multipartFormBoundary, len(body), len(body))
  868. if err != nil {
  869. return nil, err
  870. }
  871. }
  872. return req.multipartForm, nil
  873. }
  874. func marshalMultipartForm(f *multipart.Form, boundary string) ([]byte, error) {
  875. var buf bytebufferpool.ByteBuffer
  876. if err := WriteMultipartForm(&buf, f, boundary); err != nil {
  877. return nil, err
  878. }
  879. return buf.B, nil
  880. }
  881. // WriteMultipartForm writes the given multipart form f with the given
  882. // boundary to w.
  883. func WriteMultipartForm(w io.Writer, f *multipart.Form, boundary string) error {
  884. // Do not care about memory allocations here, since multipart
  885. // form processing is slow.
  886. if len(boundary) == 0 {
  887. return errors.New("form boundary cannot be empty")
  888. }
  889. mw := multipart.NewWriter(w)
  890. if err := mw.SetBoundary(boundary); err != nil {
  891. return fmt.Errorf("cannot use form boundary %q: %w", boundary, err)
  892. }
  893. // marshal values
  894. for k, vv := range f.Value {
  895. for _, v := range vv {
  896. if err := mw.WriteField(k, v); err != nil {
  897. return fmt.Errorf("cannot write form field %q value %q: %w", k, v, err)
  898. }
  899. }
  900. }
  901. // marshal files
  902. for k, fvv := range f.File {
  903. for _, fv := range fvv {
  904. vw, err := mw.CreatePart(fv.Header)
  905. if err != nil {
  906. return fmt.Errorf("cannot create form file %q (%q): %w", k, fv.Filename, err)
  907. }
  908. fh, err := fv.Open()
  909. if err != nil {
  910. return fmt.Errorf("cannot open form file %q (%q): %w", k, fv.Filename, err)
  911. }
  912. if _, err = copyZeroAlloc(vw, fh); err != nil {
  913. _ = fh.Close()
  914. return fmt.Errorf("error when copying form file %q (%q): %w", k, fv.Filename, err)
  915. }
  916. if err = fh.Close(); err != nil {
  917. return fmt.Errorf("cannot close form file %q (%q): %w", k, fv.Filename, err)
  918. }
  919. }
  920. }
  921. if err := mw.Close(); err != nil {
  922. return fmt.Errorf("error when closing multipart form writer: %w", err)
  923. }
  924. return nil
  925. }
  926. func readMultipartForm(r io.Reader, boundary string, size, maxInMemoryFileSize int) (*multipart.Form, error) {
  927. // Do not care about memory allocations here, since they are tiny
  928. // compared to multipart data (aka multi-MB files) usually sent
  929. // in multipart/form-data requests.
  930. if size <= 0 {
  931. return nil, fmt.Errorf("form size must be greater than 0. Given %d", size)
  932. }
  933. lr := io.LimitReader(r, int64(size))
  934. mr := multipart.NewReader(lr, boundary)
  935. f, err := mr.ReadForm(int64(maxInMemoryFileSize))
  936. if err != nil {
  937. return nil, fmt.Errorf("cannot read multipart/form-data body: %w", err)
  938. }
  939. return f, nil
  940. }
  941. // Reset clears request contents.
  942. func (req *Request) Reset() {
  943. if requestBodyPoolSizeLimit >= 0 && req.body != nil {
  944. req.ReleaseBody(requestBodyPoolSizeLimit)
  945. }
  946. req.Header.Reset()
  947. req.resetSkipHeader()
  948. req.timeout = 0
  949. req.UseHostHeader = false
  950. req.DisableRedirectPathNormalizing = false
  951. }
  952. func (req *Request) resetSkipHeader() {
  953. req.ResetBody()
  954. req.uri.Reset()
  955. req.parsedURI = false
  956. req.postArgs.Reset()
  957. req.parsedPostArgs = false
  958. req.isTLS = false
  959. }
  960. // RemoveMultipartFormFiles removes multipart/form-data temporary files
  961. // associated with the request.
  962. func (req *Request) RemoveMultipartFormFiles() {
  963. if req.multipartForm != nil {
  964. // Do not check for error, since these files may be deleted or moved
  965. // to new places by user code.
  966. req.multipartForm.RemoveAll() //nolint:errcheck
  967. req.multipartForm = nil
  968. }
  969. req.multipartFormBoundary = ""
  970. }
  971. // Reset clears response contents.
  972. func (resp *Response) Reset() {
  973. if responseBodyPoolSizeLimit >= 0 && resp.body != nil {
  974. resp.ReleaseBody(responseBodyPoolSizeLimit)
  975. }
  976. resp.resetSkipHeader()
  977. resp.Header.Reset()
  978. resp.SkipBody = false
  979. resp.raddr = nil
  980. resp.laddr = nil
  981. resp.ImmediateHeaderFlush = false
  982. resp.StreamBody = false
  983. }
  984. func (resp *Response) resetSkipHeader() {
  985. resp.ResetBody()
  986. }
  987. // Read reads request (including body) from the given r.
  988. //
  989. // RemoveMultipartFormFiles or Reset must be called after
  990. // reading multipart/form-data request in order to delete temporarily
  991. // uploaded files.
  992. //
  993. // If MayContinue returns true, the caller must:
  994. //
  995. // - Either send StatusExpectationFailed response if request headers don't
  996. // satisfy the caller.
  997. // - Or send StatusContinue response before reading request body
  998. // with ContinueReadBody.
  999. // - Or close the connection.
  1000. //
  1001. // io.EOF is returned if r is closed before reading the first header byte.
  1002. func (req *Request) Read(r *bufio.Reader) error {
  1003. return req.ReadLimitBody(r, 0)
  1004. }
  1005. const defaultMaxInMemoryFileSize = 16 * 1024 * 1024
  1006. // ErrGetOnly is returned when server expects only GET requests,
  1007. // but some other type of request came (Server.GetOnly option is true).
  1008. var ErrGetOnly = errors.New("non-GET request received")
  1009. // ReadLimitBody reads request from the given r, limiting the body size.
  1010. //
  1011. // If maxBodySize > 0 and the body size exceeds maxBodySize,
  1012. // then ErrBodyTooLarge is returned.
  1013. //
  1014. // RemoveMultipartFormFiles or Reset must be called after
  1015. // reading multipart/form-data request in order to delete temporarily
  1016. // uploaded files.
  1017. //
  1018. // If MayContinue returns true, the caller must:
  1019. //
  1020. // - Either send StatusExpectationFailed response if request headers don't
  1021. // satisfy the caller.
  1022. // - Or send StatusContinue response before reading request body
  1023. // with ContinueReadBody.
  1024. // - Or close the connection.
  1025. //
  1026. // io.EOF is returned if r is closed before reading the first header byte.
  1027. func (req *Request) ReadLimitBody(r *bufio.Reader, maxBodySize int) error {
  1028. req.resetSkipHeader()
  1029. if err := req.Header.Read(r); err != nil {
  1030. return err
  1031. }
  1032. return req.readLimitBody(r, maxBodySize, false, true)
  1033. }
  1034. func (req *Request) readLimitBody(r *bufio.Reader, maxBodySize int, getOnly bool, preParseMultipartForm bool) error {
  1035. // Do not reset the request here - the caller must reset it before
  1036. // calling this method.
  1037. if getOnly && !req.Header.IsGet() && !req.Header.IsHead() {
  1038. return ErrGetOnly
  1039. }
  1040. if req.MayContinue() {
  1041. // 'Expect: 100-continue' header found. Let the caller deciding
  1042. // whether to read request body or
  1043. // to return StatusExpectationFailed.
  1044. return nil
  1045. }
  1046. return req.ContinueReadBody(r, maxBodySize, preParseMultipartForm)
  1047. }
  1048. func (req *Request) readBodyStream(r *bufio.Reader, maxBodySize int, getOnly bool, preParseMultipartForm bool) error {
  1049. // Do not reset the request here - the caller must reset it before
  1050. // calling this method.
  1051. if getOnly && !req.Header.IsGet() && !req.Header.IsHead() {
  1052. return ErrGetOnly
  1053. }
  1054. if req.MayContinue() {
  1055. // 'Expect: 100-continue' header found. Let the caller deciding
  1056. // whether to read request body or
  1057. // to return StatusExpectationFailed.
  1058. return nil
  1059. }
  1060. return req.ContinueReadBodyStream(r, maxBodySize, preParseMultipartForm)
  1061. }
  1062. // MayContinue returns true if the request contains
  1063. // 'Expect: 100-continue' header.
  1064. //
  1065. // The caller must do one of the following actions if MayContinue returns true:
  1066. //
  1067. // - Either send StatusExpectationFailed response if request headers don't
  1068. // satisfy the caller.
  1069. // - Or send StatusContinue response before reading request body
  1070. // with ContinueReadBody.
  1071. // - Or close the connection.
  1072. func (req *Request) MayContinue() bool {
  1073. return bytes.Equal(req.Header.peek(strExpect), str100Continue)
  1074. }
  1075. // ContinueReadBody reads request body if request header contains
  1076. // 'Expect: 100-continue'.
  1077. //
  1078. // The caller must send StatusContinue response before calling this method.
  1079. //
  1080. // If maxBodySize > 0 and the body size exceeds maxBodySize,
  1081. // then ErrBodyTooLarge is returned.
  1082. func (req *Request) ContinueReadBody(r *bufio.Reader, maxBodySize int, preParseMultipartForm ...bool) error {
  1083. var err error
  1084. contentLength := req.Header.realContentLength()
  1085. if contentLength > 0 {
  1086. if maxBodySize > 0 && contentLength > maxBodySize {
  1087. return ErrBodyTooLarge
  1088. }
  1089. if len(preParseMultipartForm) == 0 || preParseMultipartForm[0] {
  1090. // Pre-read multipart form data of known length.
  1091. // This way we limit memory usage for large file uploads, since their contents
  1092. // is streamed into temporary files if file size exceeds defaultMaxInMemoryFileSize.
  1093. req.multipartFormBoundary = string(req.Header.MultipartFormBoundary())
  1094. if len(req.multipartFormBoundary) > 0 && len(req.Header.peek(strContentEncoding)) == 0 {
  1095. req.multipartForm, err = readMultipartForm(r, req.multipartFormBoundary, contentLength, defaultMaxInMemoryFileSize)
  1096. if err != nil {
  1097. req.Reset()
  1098. }
  1099. return err
  1100. }
  1101. }
  1102. }
  1103. if contentLength == -2 {
  1104. // identity body has no sense for http requests, since
  1105. // the end of body is determined by connection close.
  1106. // So just ignore request body for requests without
  1107. // 'Content-Length' and 'Transfer-Encoding' headers.
  1108. // refer to https://tools.ietf.org/html/rfc7230#section-3.3.2
  1109. if !req.Header.ignoreBody() {
  1110. req.Header.SetContentLength(0)
  1111. }
  1112. return nil
  1113. }
  1114. if err = req.ReadBody(r, contentLength, maxBodySize); err != nil {
  1115. return err
  1116. }
  1117. if contentLength == -1 {
  1118. err = req.Header.ReadTrailer(r)
  1119. if err != nil && err != io.EOF {
  1120. return err
  1121. }
  1122. }
  1123. return nil
  1124. }
  1125. // ReadBody reads request body from the given r, limiting the body size.
  1126. //
  1127. // If maxBodySize > 0 and the body size exceeds maxBodySize,
  1128. // then ErrBodyTooLarge is returned.
  1129. func (req *Request) ReadBody(r *bufio.Reader, contentLength int, maxBodySize int) (err error) {
  1130. bodyBuf := req.bodyBuffer()
  1131. bodyBuf.Reset()
  1132. switch {
  1133. case contentLength >= 0:
  1134. bodyBuf.B, err = readBody(r, contentLength, maxBodySize, bodyBuf.B)
  1135. case contentLength == -1:
  1136. bodyBuf.B, err = readBodyChunked(r, maxBodySize, bodyBuf.B)
  1137. if err == nil && len(bodyBuf.B) == 0 {
  1138. req.Header.SetContentLength(0)
  1139. }
  1140. default:
  1141. bodyBuf.B, err = readBodyIdentity(r, maxBodySize, bodyBuf.B)
  1142. req.Header.SetContentLength(len(bodyBuf.B))
  1143. }
  1144. if err != nil {
  1145. req.Reset()
  1146. return err
  1147. }
  1148. return nil
  1149. }
  1150. // ContinueReadBodyStream reads request body if request header contains
  1151. // 'Expect: 100-continue'.
  1152. //
  1153. // The caller must send StatusContinue response before calling this method.
  1154. //
  1155. // If maxBodySize > 0 and the body size exceeds maxBodySize,
  1156. // then ErrBodyTooLarge is returned.
  1157. func (req *Request) ContinueReadBodyStream(r *bufio.Reader, maxBodySize int, preParseMultipartForm ...bool) error {
  1158. var err error
  1159. contentLength := req.Header.realContentLength()
  1160. if contentLength > 0 {
  1161. if len(preParseMultipartForm) == 0 || preParseMultipartForm[0] {
  1162. // Pre-read multipart form data of known length.
  1163. // This way we limit memory usage for large file uploads, since their contents
  1164. // is streamed into temporary files if file size exceeds defaultMaxInMemoryFileSize.
  1165. req.multipartFormBoundary = b2s(req.Header.MultipartFormBoundary())
  1166. if len(req.multipartFormBoundary) > 0 && len(req.Header.peek(strContentEncoding)) == 0 {
  1167. req.multipartForm, err = readMultipartForm(r, req.multipartFormBoundary, contentLength, defaultMaxInMemoryFileSize)
  1168. if err != nil {
  1169. req.Reset()
  1170. }
  1171. return err
  1172. }
  1173. }
  1174. }
  1175. if contentLength == -2 {
  1176. // identity body has no sense for http requests, since
  1177. // the end of body is determined by connection close.
  1178. // So just ignore request body for requests without
  1179. // 'Content-Length' and 'Transfer-Encoding' headers.
  1180. // refer to https://tools.ietf.org/html/rfc7230#section-3.3.2
  1181. if !req.Header.ignoreBody() {
  1182. req.Header.SetContentLength(0)
  1183. }
  1184. return nil
  1185. }
  1186. bodyBuf := req.bodyBuffer()
  1187. bodyBuf.Reset()
  1188. bodyBuf.B, err = readBodyWithStreaming(r, contentLength, maxBodySize, bodyBuf.B)
  1189. if err != nil {
  1190. if err == ErrBodyTooLarge {
  1191. req.Header.SetContentLength(contentLength)
  1192. req.body = bodyBuf
  1193. req.bodyStream = acquireRequestStream(bodyBuf, r, &req.Header)
  1194. return nil
  1195. }
  1196. if err == errChunkedStream {
  1197. req.body = bodyBuf
  1198. req.bodyStream = acquireRequestStream(bodyBuf, r, &req.Header)
  1199. return nil
  1200. }
  1201. req.Reset()
  1202. return err
  1203. }
  1204. req.body = bodyBuf
  1205. req.bodyStream = acquireRequestStream(bodyBuf, r, &req.Header)
  1206. req.Header.SetContentLength(contentLength)
  1207. return nil
  1208. }
  1209. // Read reads response (including body) from the given r.
  1210. //
  1211. // io.EOF is returned if r is closed before reading the first header byte.
  1212. func (resp *Response) Read(r *bufio.Reader) error {
  1213. return resp.ReadLimitBody(r, 0)
  1214. }
  1215. // ReadLimitBody reads response headers from the given r,
  1216. // then reads the body using the ReadBody function and limiting the body size.
  1217. //
  1218. // If resp.SkipBody is true then it skips reading the response body.
  1219. //
  1220. // If maxBodySize > 0 and the body size exceeds maxBodySize,
  1221. // then ErrBodyTooLarge is returned.
  1222. //
  1223. // io.EOF is returned if r is closed before reading the first header byte.
  1224. func (resp *Response) ReadLimitBody(r *bufio.Reader, maxBodySize int) error {
  1225. resp.resetSkipHeader()
  1226. err := resp.Header.Read(r)
  1227. if err != nil {
  1228. return err
  1229. }
  1230. if resp.Header.StatusCode() == StatusContinue {
  1231. // Read the next response according to http://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html .
  1232. if err = resp.Header.Read(r); err != nil {
  1233. return err
  1234. }
  1235. }
  1236. if !resp.mustSkipBody() {
  1237. err = resp.ReadBody(r, maxBodySize)
  1238. if err != nil {
  1239. if isConnectionReset(err) {
  1240. return nil
  1241. }
  1242. return err
  1243. }
  1244. }
  1245. if resp.Header.ContentLength() == -1 && !resp.StreamBody {
  1246. err = resp.Header.ReadTrailer(r)
  1247. if err != nil && err != io.EOF {
  1248. if isConnectionReset(err) {
  1249. return nil
  1250. }
  1251. return err
  1252. }
  1253. }
  1254. return nil
  1255. }
  1256. // ReadBody reads response body from the given r, limiting the body size.
  1257. //
  1258. // If maxBodySize > 0 and the body size exceeds maxBodySize,
  1259. // then ErrBodyTooLarge is returned.
  1260. func (resp *Response) ReadBody(r *bufio.Reader, maxBodySize int) (err error) {
  1261. bodyBuf := resp.bodyBuffer()
  1262. bodyBuf.Reset()
  1263. contentLength := resp.Header.ContentLength()
  1264. switch {
  1265. case contentLength >= 0:
  1266. bodyBuf.B, err = readBody(r, contentLength, maxBodySize, bodyBuf.B)
  1267. if err == ErrBodyTooLarge && resp.StreamBody {
  1268. resp.bodyStream = acquireRequestStream(bodyBuf, r, &resp.Header)
  1269. err = nil
  1270. }
  1271. case contentLength == -1:
  1272. if resp.StreamBody {
  1273. resp.bodyStream = acquireRequestStream(bodyBuf, r, &resp.Header)
  1274. } else {
  1275. bodyBuf.B, err = readBodyChunked(r, maxBodySize, bodyBuf.B)
  1276. }
  1277. default:
  1278. bodyBuf.B, err = readBodyIdentity(r, maxBodySize, bodyBuf.B)
  1279. resp.Header.SetContentLength(len(bodyBuf.B))
  1280. }
  1281. if err == nil && resp.StreamBody && resp.bodyStream == nil {
  1282. resp.bodyStream = bytes.NewReader(bodyBuf.B)
  1283. }
  1284. return err
  1285. }
  1286. func (resp *Response) mustSkipBody() bool {
  1287. return resp.SkipBody || resp.Header.mustSkipContentLength()
  1288. }
  1289. var errRequestHostRequired = errors.New("missing required Host header in request")
  1290. // WriteTo writes request to w. It implements io.WriterTo.
  1291. func (req *Request) WriteTo(w io.Writer) (int64, error) {
  1292. return writeBufio(req, w)
  1293. }
  1294. // WriteTo writes response to w. It implements io.WriterTo.
  1295. func (resp *Response) WriteTo(w io.Writer) (int64, error) {
  1296. return writeBufio(resp, w)
  1297. }
  1298. func writeBufio(hw httpWriter, w io.Writer) (int64, error) {
  1299. sw := acquireStatsWriter(w)
  1300. bw := acquireBufioWriter(sw)
  1301. err1 := hw.Write(bw)
  1302. err2 := bw.Flush()
  1303. releaseBufioWriter(bw)
  1304. n := sw.bytesWritten
  1305. releaseStatsWriter(sw)
  1306. err := err1
  1307. if err == nil {
  1308. err = err2
  1309. }
  1310. return n, err
  1311. }
  1312. type statsWriter struct {
  1313. w io.Writer
  1314. bytesWritten int64
  1315. }
  1316. func (w *statsWriter) Write(p []byte) (int, error) {
  1317. n, err := w.w.Write(p)
  1318. w.bytesWritten += int64(n)
  1319. return n, err
  1320. }
  1321. func acquireStatsWriter(w io.Writer) *statsWriter {
  1322. v := statsWriterPool.Get()
  1323. if v == nil {
  1324. return &statsWriter{
  1325. w: w,
  1326. }
  1327. }
  1328. sw := v.(*statsWriter)
  1329. sw.w = w
  1330. return sw
  1331. }
  1332. func releaseStatsWriter(sw *statsWriter) {
  1333. sw.w = nil
  1334. sw.bytesWritten = 0
  1335. statsWriterPool.Put(sw)
  1336. }
  1337. var statsWriterPool sync.Pool
  1338. func acquireBufioWriter(w io.Writer) *bufio.Writer {
  1339. v := bufioWriterPool.Get()
  1340. if v == nil {
  1341. return bufio.NewWriter(w)
  1342. }
  1343. bw := v.(*bufio.Writer)
  1344. bw.Reset(w)
  1345. return bw
  1346. }
  1347. func releaseBufioWriter(bw *bufio.Writer) {
  1348. bufioWriterPool.Put(bw)
  1349. }
  1350. var bufioWriterPool sync.Pool
  1351. func (req *Request) onlyMultipartForm() bool {
  1352. return req.multipartForm != nil && (req.body == nil || len(req.body.B) == 0)
  1353. }
  1354. // Write writes request to w.
  1355. //
  1356. // Write doesn't flush request to w for performance reasons.
  1357. //
  1358. // See also WriteTo.
  1359. func (req *Request) Write(w *bufio.Writer) error {
  1360. if len(req.Header.Host()) == 0 || req.parsedURI {
  1361. uri := req.URI()
  1362. host := uri.Host()
  1363. if len(req.Header.Host()) == 0 {
  1364. if len(host) == 0 {
  1365. return errRequestHostRequired
  1366. } else {
  1367. req.Header.SetHostBytes(host)
  1368. }
  1369. } else if !req.UseHostHeader {
  1370. req.Header.SetHostBytes(host)
  1371. }
  1372. req.Header.SetRequestURIBytes(uri.RequestURI())
  1373. if len(uri.username) > 0 {
  1374. // RequestHeader.SetBytesKV only uses RequestHeader.bufKV.key
  1375. // So we are free to use RequestHeader.bufKV.value as a scratch pad for
  1376. // the base64 encoding.
  1377. nl := len(uri.username) + len(uri.password) + 1
  1378. nb := nl + len(strBasicSpace)
  1379. tl := nb + base64.StdEncoding.EncodedLen(nl)
  1380. if tl > cap(req.Header.bufKV.value) {
  1381. req.Header.bufKV.value = make([]byte, 0, tl)
  1382. }
  1383. buf := req.Header.bufKV.value[:0]
  1384. buf = append(buf, uri.username...)
  1385. buf = append(buf, strColon...)
  1386. buf = append(buf, uri.password...)
  1387. buf = append(buf, strBasicSpace...)
  1388. base64.StdEncoding.Encode(buf[nb:tl], buf[:nl])
  1389. req.Header.SetBytesKV(strAuthorization, buf[nl:tl])
  1390. }
  1391. }
  1392. if req.bodyStream != nil {
  1393. return req.writeBodyStream(w)
  1394. }
  1395. body := req.bodyBytes()
  1396. var err error
  1397. if req.onlyMultipartForm() {
  1398. body, err = marshalMultipartForm(req.multipartForm, req.multipartFormBoundary)
  1399. if err != nil {
  1400. return fmt.Errorf("error when marshaling multipart form: %w", err)
  1401. }
  1402. req.Header.SetMultipartFormBoundary(req.multipartFormBoundary)
  1403. }
  1404. hasBody := false
  1405. if len(body) == 0 {
  1406. body = req.postArgs.QueryString()
  1407. }
  1408. if len(body) != 0 || !req.Header.ignoreBody() {
  1409. hasBody = true
  1410. req.Header.SetContentLength(len(body))
  1411. }
  1412. if err = req.Header.Write(w); err != nil {
  1413. return err
  1414. }
  1415. if hasBody {
  1416. _, err = w.Write(body)
  1417. } else if len(body) > 0 {
  1418. if req.secureErrorLogMessage {
  1419. return fmt.Errorf("non-zero body for non-POST request")
  1420. }
  1421. return fmt.Errorf("non-zero body for non-POST request. body=%q", body)
  1422. }
  1423. return err
  1424. }
  1425. // WriteGzip writes response with gzipped body to w.
  1426. //
  1427. // The method gzips response body and sets 'Content-Encoding: gzip'
  1428. // header before writing response to w.
  1429. //
  1430. // WriteGzip doesn't flush response to w for performance reasons.
  1431. func (resp *Response) WriteGzip(w *bufio.Writer) error {
  1432. return resp.WriteGzipLevel(w, CompressDefaultCompression)
  1433. }
  1434. // WriteGzipLevel writes response with gzipped body to w.
  1435. //
  1436. // Level is the desired compression level:
  1437. //
  1438. // - CompressNoCompression
  1439. // - CompressBestSpeed
  1440. // - CompressBestCompression
  1441. // - CompressDefaultCompression
  1442. // - CompressHuffmanOnly
  1443. //
  1444. // The method gzips response body and sets 'Content-Encoding: gzip'
  1445. // header before writing response to w.
  1446. //
  1447. // WriteGzipLevel doesn't flush response to w for performance reasons.
  1448. func (resp *Response) WriteGzipLevel(w *bufio.Writer, level int) error {
  1449. if err := resp.gzipBody(level); err != nil {
  1450. return err
  1451. }
  1452. return resp.Write(w)
  1453. }
  1454. // WriteDeflate writes response with deflated body to w.
  1455. //
  1456. // The method deflates response body and sets 'Content-Encoding: deflate'
  1457. // header before writing response to w.
  1458. //
  1459. // WriteDeflate doesn't flush response to w for performance reasons.
  1460. func (resp *Response) WriteDeflate(w *bufio.Writer) error {
  1461. return resp.WriteDeflateLevel(w, CompressDefaultCompression)
  1462. }
  1463. // WriteDeflateLevel writes response with deflated body to w.
  1464. //
  1465. // Level is the desired compression level:
  1466. //
  1467. // - CompressNoCompression
  1468. // - CompressBestSpeed
  1469. // - CompressBestCompression
  1470. // - CompressDefaultCompression
  1471. // - CompressHuffmanOnly
  1472. //
  1473. // The method deflates response body and sets 'Content-Encoding: deflate'
  1474. // header before writing response to w.
  1475. //
  1476. // WriteDeflateLevel doesn't flush response to w for performance reasons.
  1477. func (resp *Response) WriteDeflateLevel(w *bufio.Writer, level int) error {
  1478. if err := resp.deflateBody(level); err != nil {
  1479. return err
  1480. }
  1481. return resp.Write(w)
  1482. }
  1483. func (resp *Response) brotliBody(level int) error {
  1484. if len(resp.Header.ContentEncoding()) > 0 {
  1485. // It looks like the body is already compressed.
  1486. // Do not compress it again.
  1487. return nil
  1488. }
  1489. if !resp.Header.isCompressibleContentType() {
  1490. // The content-type cannot be compressed.
  1491. return nil
  1492. }
  1493. if resp.bodyStream != nil {
  1494. // Reset Content-Length to -1, since it is impossible
  1495. // to determine body size beforehand of streamed compression.
  1496. // For https://github.com/valyala/fasthttp/issues/176 .
  1497. resp.Header.SetContentLength(-1)
  1498. // Do not care about memory allocations here, since brotli is slow
  1499. // and allocates a lot of memory by itself.
  1500. bs := resp.bodyStream
  1501. resp.bodyStream = NewStreamReader(func(sw *bufio.Writer) {
  1502. zw := acquireStacklessBrotliWriter(sw, level)
  1503. fw := &flushWriter{
  1504. wf: zw,
  1505. bw: sw,
  1506. }
  1507. copyZeroAlloc(fw, bs) //nolint:errcheck
  1508. releaseStacklessBrotliWriter(zw, level)
  1509. if bsc, ok := bs.(io.Closer); ok {
  1510. bsc.Close()
  1511. }
  1512. })
  1513. } else {
  1514. bodyBytes := resp.bodyBytes()
  1515. if len(bodyBytes) < minCompressLen {
  1516. // There is no sense in spending CPU time on small body compression,
  1517. // since there is a very high probability that the compressed
  1518. // body size will be bigger than the original body size.
  1519. return nil
  1520. }
  1521. w := responseBodyPool.Get()
  1522. w.B = AppendBrotliBytesLevel(w.B, bodyBytes, level)
  1523. // Hack: swap resp.body with w.
  1524. if resp.body != nil {
  1525. responseBodyPool.Put(resp.body)
  1526. }
  1527. resp.body = w
  1528. resp.bodyRaw = nil
  1529. }
  1530. resp.Header.SetContentEncodingBytes(strBr)
  1531. resp.Header.addVaryBytes(strAcceptEncoding)
  1532. return nil
  1533. }
  1534. func (resp *Response) gzipBody(level int) error {
  1535. if len(resp.Header.ContentEncoding()) > 0 {
  1536. // It looks like the body is already compressed.
  1537. // Do not compress it again.
  1538. return nil
  1539. }
  1540. if !resp.Header.isCompressibleContentType() {
  1541. // The content-type cannot be compressed.
  1542. return nil
  1543. }
  1544. if resp.bodyStream != nil {
  1545. // Reset Content-Length to -1, since it is impossible
  1546. // to determine body size beforehand of streamed compression.
  1547. // For https://github.com/valyala/fasthttp/issues/176 .
  1548. resp.Header.SetContentLength(-1)
  1549. // Do not care about memory allocations here, since gzip is slow
  1550. // and allocates a lot of memory by itself.
  1551. bs := resp.bodyStream
  1552. resp.bodyStream = NewStreamReader(func(sw *bufio.Writer) {
  1553. zw := acquireStacklessGzipWriter(sw, level)
  1554. fw := &flushWriter{
  1555. wf: zw,
  1556. bw: sw,
  1557. }
  1558. copyZeroAlloc(fw, bs) //nolint:errcheck
  1559. releaseStacklessGzipWriter(zw, level)
  1560. if bsc, ok := bs.(io.Closer); ok {
  1561. bsc.Close()
  1562. }
  1563. })
  1564. } else {
  1565. bodyBytes := resp.bodyBytes()
  1566. if len(bodyBytes) < minCompressLen {
  1567. // There is no sense in spending CPU time on small body compression,
  1568. // since there is a very high probability that the compressed
  1569. // body size will be bigger than the original body size.
  1570. return nil
  1571. }
  1572. w := responseBodyPool.Get()
  1573. w.B = AppendGzipBytesLevel(w.B, bodyBytes, level)
  1574. // Hack: swap resp.body with w.
  1575. if resp.body != nil {
  1576. responseBodyPool.Put(resp.body)
  1577. }
  1578. resp.body = w
  1579. resp.bodyRaw = nil
  1580. }
  1581. resp.Header.SetContentEncodingBytes(strGzip)
  1582. resp.Header.addVaryBytes(strAcceptEncoding)
  1583. return nil
  1584. }
  1585. func (resp *Response) deflateBody(level int) error {
  1586. if len(resp.Header.ContentEncoding()) > 0 {
  1587. // It looks like the body is already compressed.
  1588. // Do not compress it again.
  1589. return nil
  1590. }
  1591. if !resp.Header.isCompressibleContentType() {
  1592. // The content-type cannot be compressed.
  1593. return nil
  1594. }
  1595. if resp.bodyStream != nil {
  1596. // Reset Content-Length to -1, since it is impossible
  1597. // to determine body size beforehand of streamed compression.
  1598. // For https://github.com/valyala/fasthttp/issues/176 .
  1599. resp.Header.SetContentLength(-1)
  1600. // Do not care about memory allocations here, since flate is slow
  1601. // and allocates a lot of memory by itself.
  1602. bs := resp.bodyStream
  1603. resp.bodyStream = NewStreamReader(func(sw *bufio.Writer) {
  1604. zw := acquireStacklessDeflateWriter(sw, level)
  1605. fw := &flushWriter{
  1606. wf: zw,
  1607. bw: sw,
  1608. }
  1609. copyZeroAlloc(fw, bs) //nolint:errcheck
  1610. releaseStacklessDeflateWriter(zw, level)
  1611. if bsc, ok := bs.(io.Closer); ok {
  1612. bsc.Close()
  1613. }
  1614. })
  1615. } else {
  1616. bodyBytes := resp.bodyBytes()
  1617. if len(bodyBytes) < minCompressLen {
  1618. // There is no sense in spending CPU time on small body compression,
  1619. // since there is a very high probability that the compressed
  1620. // body size will be bigger than the original body size.
  1621. return nil
  1622. }
  1623. w := responseBodyPool.Get()
  1624. w.B = AppendDeflateBytesLevel(w.B, bodyBytes, level)
  1625. // Hack: swap resp.body with w.
  1626. if resp.body != nil {
  1627. responseBodyPool.Put(resp.body)
  1628. }
  1629. resp.body = w
  1630. resp.bodyRaw = nil
  1631. }
  1632. resp.Header.SetContentEncodingBytes(strDeflate)
  1633. resp.Header.addVaryBytes(strAcceptEncoding)
  1634. return nil
  1635. }
  1636. // Bodies with sizes smaller than minCompressLen aren't compressed at all
  1637. const minCompressLen = 200
  1638. type writeFlusher interface {
  1639. io.Writer
  1640. Flush() error
  1641. }
  1642. type flushWriter struct {
  1643. wf writeFlusher
  1644. bw *bufio.Writer
  1645. }
  1646. func (w *flushWriter) Write(p []byte) (int, error) {
  1647. n, err := w.wf.Write(p)
  1648. if err != nil {
  1649. return 0, err
  1650. }
  1651. if err = w.wf.Flush(); err != nil {
  1652. return 0, err
  1653. }
  1654. if err = w.bw.Flush(); err != nil {
  1655. return 0, err
  1656. }
  1657. return n, nil
  1658. }
  1659. // Write writes response to w.
  1660. //
  1661. // Write doesn't flush response to w for performance reasons.
  1662. //
  1663. // See also WriteTo.
  1664. func (resp *Response) Write(w *bufio.Writer) error {
  1665. sendBody := !resp.mustSkipBody()
  1666. if resp.bodyStream != nil {
  1667. return resp.writeBodyStream(w, sendBody)
  1668. }
  1669. body := resp.bodyBytes()
  1670. bodyLen := len(body)
  1671. if sendBody || bodyLen > 0 {
  1672. resp.Header.SetContentLength(bodyLen)
  1673. }
  1674. if err := resp.Header.Write(w); err != nil {
  1675. return err
  1676. }
  1677. if sendBody {
  1678. if _, err := w.Write(body); err != nil {
  1679. return err
  1680. }
  1681. }
  1682. return nil
  1683. }
  1684. func (req *Request) writeBodyStream(w *bufio.Writer) error {
  1685. var err error
  1686. contentLength := req.Header.ContentLength()
  1687. if contentLength < 0 {
  1688. lrSize := limitedReaderSize(req.bodyStream)
  1689. if lrSize >= 0 {
  1690. contentLength = int(lrSize)
  1691. if int64(contentLength) != lrSize {
  1692. contentLength = -1
  1693. }
  1694. if contentLength >= 0 {
  1695. req.Header.SetContentLength(contentLength)
  1696. }
  1697. }
  1698. }
  1699. if contentLength >= 0 {
  1700. if err = req.Header.Write(w); err == nil {
  1701. err = writeBodyFixedSize(w, req.bodyStream, int64(contentLength))
  1702. }
  1703. } else {
  1704. req.Header.SetContentLength(-1)
  1705. err = req.Header.Write(w)
  1706. if err == nil {
  1707. err = writeBodyChunked(w, req.bodyStream)
  1708. }
  1709. if err == nil {
  1710. err = req.Header.writeTrailer(w)
  1711. }
  1712. }
  1713. err1 := req.closeBodyStream()
  1714. if err == nil {
  1715. err = err1
  1716. }
  1717. return err
  1718. }
  1719. // ErrBodyStreamWritePanic is returned when panic happens during writing body stream.
  1720. type ErrBodyStreamWritePanic struct {
  1721. error
  1722. }
  1723. func (resp *Response) writeBodyStream(w *bufio.Writer, sendBody bool) (err error) {
  1724. defer func() {
  1725. if r := recover(); r != nil {
  1726. err = &ErrBodyStreamWritePanic{
  1727. error: fmt.Errorf("panic while writing body stream: %+v", r),
  1728. }
  1729. }
  1730. }()
  1731. contentLength := resp.Header.ContentLength()
  1732. if contentLength < 0 {
  1733. lrSize := limitedReaderSize(resp.bodyStream)
  1734. if lrSize >= 0 {
  1735. contentLength = int(lrSize)
  1736. if int64(contentLength) != lrSize {
  1737. contentLength = -1
  1738. }
  1739. if contentLength >= 0 {
  1740. resp.Header.SetContentLength(contentLength)
  1741. }
  1742. }
  1743. }
  1744. if contentLength >= 0 {
  1745. if err = resp.Header.Write(w); err == nil {
  1746. if resp.ImmediateHeaderFlush {
  1747. err = w.Flush()
  1748. }
  1749. if err == nil && sendBody {
  1750. err = writeBodyFixedSize(w, resp.bodyStream, int64(contentLength))
  1751. }
  1752. }
  1753. } else {
  1754. resp.Header.SetContentLength(-1)
  1755. if err = resp.Header.Write(w); err == nil {
  1756. if resp.ImmediateHeaderFlush {
  1757. err = w.Flush()
  1758. }
  1759. if err == nil && sendBody {
  1760. err = writeBodyChunked(w, resp.bodyStream)
  1761. }
  1762. if err == nil {
  1763. err = resp.Header.writeTrailer(w)
  1764. }
  1765. }
  1766. }
  1767. err1 := resp.closeBodyStream()
  1768. if err == nil {
  1769. err = err1
  1770. }
  1771. return err
  1772. }
  1773. func (req *Request) closeBodyStream() error {
  1774. if req.bodyStream == nil {
  1775. return nil
  1776. }
  1777. var err error
  1778. if bsc, ok := req.bodyStream.(io.Closer); ok {
  1779. err = bsc.Close()
  1780. }
  1781. if rs, ok := req.bodyStream.(*requestStream); ok {
  1782. releaseRequestStream(rs)
  1783. }
  1784. req.bodyStream = nil
  1785. return err
  1786. }
  1787. func (resp *Response) closeBodyStream() error {
  1788. if resp.bodyStream == nil {
  1789. return nil
  1790. }
  1791. var err error
  1792. if bsc, ok := resp.bodyStream.(io.Closer); ok {
  1793. err = bsc.Close()
  1794. }
  1795. if bsr, ok := resp.bodyStream.(*requestStream); ok {
  1796. releaseRequestStream(bsr)
  1797. }
  1798. resp.bodyStream = nil
  1799. return err
  1800. }
  1801. // String returns request representation.
  1802. //
  1803. // Returns error message instead of request representation on error.
  1804. //
  1805. // Use Write instead of String for performance-critical code.
  1806. func (req *Request) String() string {
  1807. return getHTTPString(req)
  1808. }
  1809. // String returns response representation.
  1810. //
  1811. // Returns error message instead of response representation on error.
  1812. //
  1813. // Use Write instead of String for performance-critical code.
  1814. func (resp *Response) String() string {
  1815. return getHTTPString(resp)
  1816. }
  1817. func getHTTPString(hw httpWriter) string {
  1818. w := bytebufferpool.Get()
  1819. defer bytebufferpool.Put(w)
  1820. bw := bufio.NewWriter(w)
  1821. if err := hw.Write(bw); err != nil {
  1822. return err.Error()
  1823. }
  1824. if err := bw.Flush(); err != nil {
  1825. return err.Error()
  1826. }
  1827. s := string(w.B)
  1828. return s
  1829. }
  1830. type httpWriter interface {
  1831. Write(w *bufio.Writer) error
  1832. }
  1833. func writeBodyChunked(w *bufio.Writer, r io.Reader) error {
  1834. vbuf := copyBufPool.Get()
  1835. buf := vbuf.([]byte)
  1836. var err error
  1837. var n int
  1838. for {
  1839. n, err = r.Read(buf)
  1840. if n == 0 {
  1841. if err == nil {
  1842. continue
  1843. }
  1844. if err == io.EOF {
  1845. if err = writeChunk(w, buf[:0]); err != nil {
  1846. break
  1847. }
  1848. err = nil
  1849. }
  1850. break
  1851. }
  1852. if err = writeChunk(w, buf[:n]); err != nil {
  1853. break
  1854. }
  1855. }
  1856. copyBufPool.Put(vbuf)
  1857. return err
  1858. }
  1859. func limitedReaderSize(r io.Reader) int64 {
  1860. lr, ok := r.(*io.LimitedReader)
  1861. if !ok {
  1862. return -1
  1863. }
  1864. return lr.N
  1865. }
  1866. func writeBodyFixedSize(w *bufio.Writer, r io.Reader, size int64) error {
  1867. if size > maxSmallFileSize {
  1868. // w buffer must be empty for triggering
  1869. // sendfile path in bufio.Writer.ReadFrom.
  1870. if err := w.Flush(); err != nil {
  1871. return err
  1872. }
  1873. }
  1874. n, err := copyZeroAlloc(w, r)
  1875. if n != size && err == nil {
  1876. err = fmt.Errorf("copied %d bytes from body stream instead of %d bytes", n, size)
  1877. }
  1878. return err
  1879. }
  1880. func copyZeroAlloc(w io.Writer, r io.Reader) (int64, error) {
  1881. vbuf := copyBufPool.Get()
  1882. buf := vbuf.([]byte)
  1883. n, err := io.CopyBuffer(w, r, buf)
  1884. copyBufPool.Put(vbuf)
  1885. return n, err
  1886. }
  1887. var copyBufPool = sync.Pool{
  1888. New: func() interface{} {
  1889. return make([]byte, 4096)
  1890. },
  1891. }
  1892. func writeChunk(w *bufio.Writer, b []byte) error {
  1893. n := len(b)
  1894. if err := writeHexInt(w, n); err != nil {
  1895. return err
  1896. }
  1897. if _, err := w.Write(strCRLF); err != nil {
  1898. return err
  1899. }
  1900. if _, err := w.Write(b); err != nil {
  1901. return err
  1902. }
  1903. // If is end chunk, write CRLF after writing trailer
  1904. if n > 0 {
  1905. if _, err := w.Write(strCRLF); err != nil {
  1906. return err
  1907. }
  1908. }
  1909. return w.Flush()
  1910. }
  1911. // ErrBodyTooLarge is returned if either request or response body exceeds
  1912. // the given limit.
  1913. var ErrBodyTooLarge = errors.New("body size exceeds the given limit")
  1914. func readBody(r *bufio.Reader, contentLength int, maxBodySize int, dst []byte) ([]byte, error) {
  1915. if maxBodySize > 0 && contentLength > maxBodySize {
  1916. return dst, ErrBodyTooLarge
  1917. }
  1918. return appendBodyFixedSize(r, dst, contentLength)
  1919. }
  1920. var errChunkedStream = errors.New("chunked stream")
  1921. func readBodyWithStreaming(r *bufio.Reader, contentLength int, maxBodySize int, dst []byte) (b []byte, err error) {
  1922. if contentLength == -1 {
  1923. // handled in requestStream.Read()
  1924. return b, errChunkedStream
  1925. }
  1926. dst = dst[:0]
  1927. readN := maxBodySize
  1928. if readN > contentLength {
  1929. readN = contentLength
  1930. }
  1931. if readN > 8*1024 {
  1932. readN = 8 * 1024
  1933. }
  1934. if contentLength >= 0 && maxBodySize >= contentLength {
  1935. b, err = appendBodyFixedSize(r, dst, readN)
  1936. } else {
  1937. b, err = readBodyIdentity(r, readN, dst)
  1938. }
  1939. if err != nil {
  1940. return b, err
  1941. }
  1942. if contentLength > maxBodySize {
  1943. return b, ErrBodyTooLarge
  1944. }
  1945. return b, nil
  1946. }
  1947. func readBodyIdentity(r *bufio.Reader, maxBodySize int, dst []byte) ([]byte, error) {
  1948. dst = dst[:cap(dst)]
  1949. if len(dst) == 0 {
  1950. dst = make([]byte, 1024)
  1951. }
  1952. offset := 0
  1953. for {
  1954. nn, err := r.Read(dst[offset:])
  1955. if nn <= 0 {
  1956. switch {
  1957. case errors.Is(err, io.EOF):
  1958. return dst[:offset], nil
  1959. case err != nil:
  1960. return dst[:offset], err
  1961. default:
  1962. return dst[:offset], fmt.Errorf("bufio.Read() returned (%d, nil)", nn)
  1963. }
  1964. }
  1965. offset += nn
  1966. if maxBodySize > 0 && offset > maxBodySize {
  1967. return dst[:offset], ErrBodyTooLarge
  1968. }
  1969. if len(dst) == offset {
  1970. n := roundUpForSliceCap(2 * offset)
  1971. if maxBodySize > 0 && n > maxBodySize {
  1972. n = maxBodySize + 1
  1973. }
  1974. b := make([]byte, n)
  1975. copy(b, dst)
  1976. dst = b
  1977. }
  1978. }
  1979. }
  1980. func appendBodyFixedSize(r *bufio.Reader, dst []byte, n int) ([]byte, error) {
  1981. if n == 0 {
  1982. return dst, nil
  1983. }
  1984. offset := len(dst)
  1985. dstLen := offset + n
  1986. if cap(dst) < dstLen {
  1987. b := make([]byte, roundUpForSliceCap(dstLen))
  1988. copy(b, dst)
  1989. dst = b
  1990. }
  1991. dst = dst[:dstLen]
  1992. for {
  1993. nn, err := r.Read(dst[offset:])
  1994. if nn <= 0 {
  1995. switch {
  1996. case errors.Is(err, io.EOF):
  1997. return dst[:offset], io.ErrUnexpectedEOF
  1998. case err != nil:
  1999. return dst[:offset], err
  2000. default:
  2001. return dst[:offset], fmt.Errorf("bufio.Read() returned (%d, nil)", nn)
  2002. }
  2003. }
  2004. offset += nn
  2005. if offset == dstLen {
  2006. return dst, nil
  2007. }
  2008. }
  2009. }
  2010. // ErrBrokenChunk is returned when server receives a broken chunked body (Transfer-Encoding: chunked).
  2011. type ErrBrokenChunk struct {
  2012. error
  2013. }
  2014. func readBodyChunked(r *bufio.Reader, maxBodySize int, dst []byte) ([]byte, error) {
  2015. if len(dst) > 0 {
  2016. // data integrity might be in danger. No idea what we received,
  2017. // but nothing we should write to.
  2018. panic("BUG: expected zero-length buffer")
  2019. }
  2020. strCRLFLen := len(strCRLF)
  2021. for {
  2022. chunkSize, err := parseChunkSize(r)
  2023. if err != nil {
  2024. return dst, err
  2025. }
  2026. if chunkSize == 0 {
  2027. return dst, err
  2028. }
  2029. if maxBodySize > 0 && len(dst)+chunkSize > maxBodySize {
  2030. return dst, ErrBodyTooLarge
  2031. }
  2032. dst, err = appendBodyFixedSize(r, dst, chunkSize+strCRLFLen)
  2033. if err != nil {
  2034. return dst, err
  2035. }
  2036. if !bytes.Equal(dst[len(dst)-strCRLFLen:], strCRLF) {
  2037. return dst, ErrBrokenChunk{
  2038. error: fmt.Errorf("cannot find crlf at the end of chunk"),
  2039. }
  2040. }
  2041. dst = dst[:len(dst)-strCRLFLen]
  2042. }
  2043. }
  2044. func parseChunkSize(r *bufio.Reader) (int, error) {
  2045. n, err := readHexInt(r)
  2046. if err != nil {
  2047. return -1, err
  2048. }
  2049. for {
  2050. c, err := r.ReadByte()
  2051. if err != nil {
  2052. return -1, ErrBrokenChunk{
  2053. error: fmt.Errorf("cannot read '\r' char at the end of chunk size: %w", err),
  2054. }
  2055. }
  2056. // Skip chunk extension after chunk size.
  2057. // Add support later if anyone needs it.
  2058. if c != '\r' {
  2059. continue
  2060. }
  2061. if err := r.UnreadByte(); err != nil {
  2062. return -1, ErrBrokenChunk{
  2063. error: fmt.Errorf("cannot unread '\r' char at the end of chunk size: %w", err),
  2064. }
  2065. }
  2066. break
  2067. }
  2068. err = readCrLf(r)
  2069. if err != nil {
  2070. return -1, err
  2071. }
  2072. return n, nil
  2073. }
  2074. func readCrLf(r *bufio.Reader) error {
  2075. for _, exp := range []byte{'\r', '\n'} {
  2076. c, err := r.ReadByte()
  2077. if err != nil {
  2078. return ErrBrokenChunk{
  2079. error: fmt.Errorf("cannot read %q char at the end of chunk size: %w", exp, err),
  2080. }
  2081. }
  2082. if c != exp {
  2083. return ErrBrokenChunk{
  2084. error: fmt.Errorf("unexpected char %q at the end of chunk size. Expected %q", c, exp),
  2085. }
  2086. }
  2087. }
  2088. return nil
  2089. }
  2090. // SetTimeout sets timeout for the request.
  2091. //
  2092. // req.SetTimeout(t); c.Do(&req, &resp) is equivalent to
  2093. // c.DoTimeout(&req, &resp, t)
  2094. func (req *Request) SetTimeout(t time.Duration) {
  2095. req.timeout = t
  2096. }