http.go 58 KB

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