http.go 75 KB

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