header.go 102 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625
  1. package fasthttp
  2. import (
  3. "bufio"
  4. "bytes"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "sync"
  9. "sync/atomic"
  10. "time"
  11. )
  12. const (
  13. rChar = byte('\r')
  14. nChar = byte('\n')
  15. )
  16. // ResponseHeader represents HTTP response header.
  17. //
  18. // It is forbidden copying ResponseHeader instances.
  19. // Create new instances instead and use CopyTo.
  20. //
  21. // ResponseHeader instance MUST NOT be used from concurrently running
  22. // goroutines.
  23. type ResponseHeader struct {
  24. noCopy noCopy
  25. statusMessage []byte
  26. protocol []byte
  27. contentLengthBytes []byte
  28. contentType []byte
  29. contentEncoding []byte
  30. server []byte
  31. mulHeader [][]byte
  32. trailer [][]byte
  33. h []argsKV
  34. cookies []argsKV
  35. bufK []byte
  36. bufV []byte
  37. statusCode int
  38. contentLength int
  39. disableNormalizing bool
  40. noHTTP11 bool
  41. connectionClose bool
  42. noDefaultContentType bool
  43. noDefaultDate bool
  44. secureErrorLogMessage bool
  45. }
  46. // RequestHeader represents HTTP request header.
  47. //
  48. // It is forbidden copying RequestHeader instances.
  49. // Create new instances instead and use CopyTo.
  50. //
  51. // RequestHeader instance MUST NOT be used from concurrently running
  52. // goroutines.
  53. type RequestHeader struct {
  54. noCopy noCopy
  55. contentLengthBytes []byte
  56. method []byte
  57. requestURI []byte
  58. proto []byte
  59. host []byte
  60. contentType []byte
  61. userAgent []byte
  62. mulHeader [][]byte
  63. trailer [][]byte
  64. h []argsKV
  65. cookies []argsKV
  66. // stores an immutable copy of headers as they were received from the
  67. // wire.
  68. rawHeaders []byte
  69. bufK []byte
  70. bufV []byte
  71. contentLength int
  72. disableNormalizing bool
  73. noHTTP11 bool
  74. connectionClose bool
  75. noDefaultContentType bool
  76. disableSpecialHeader bool
  77. // These two fields have been moved close to other bool fields
  78. // for reducing RequestHeader object size.
  79. cookiesCollected bool
  80. secureErrorLogMessage bool
  81. }
  82. // SetContentRange sets 'Content-Range: bytes startPos-endPos/contentLength'
  83. // header.
  84. func (h *ResponseHeader) SetContentRange(startPos, endPos, contentLength int) {
  85. b := h.bufV[:0]
  86. b = append(b, strBytes...)
  87. b = append(b, ' ')
  88. b = AppendUint(b, startPos)
  89. b = append(b, '-')
  90. b = AppendUint(b, endPos)
  91. b = append(b, '/')
  92. b = AppendUint(b, contentLength)
  93. h.bufV = b
  94. h.setNonSpecial(strContentRange, h.bufV)
  95. }
  96. // SetByteRange sets 'Range: bytes=startPos-endPos' header.
  97. //
  98. // - If startPos is negative, then 'bytes=-startPos' value is set.
  99. // - If endPos is negative, then 'bytes=startPos-' value is set.
  100. func (h *RequestHeader) SetByteRange(startPos, endPos int) {
  101. b := h.bufV[:0]
  102. b = append(b, strBytes...)
  103. b = append(b, '=')
  104. if startPos >= 0 {
  105. b = AppendUint(b, startPos)
  106. } else {
  107. endPos = -startPos
  108. }
  109. b = append(b, '-')
  110. if endPos >= 0 {
  111. b = AppendUint(b, endPos)
  112. }
  113. h.bufV = b
  114. h.setNonSpecial(strRange, h.bufV)
  115. }
  116. // StatusCode returns response status code.
  117. func (h *ResponseHeader) StatusCode() int {
  118. if h.statusCode == 0 {
  119. return StatusOK
  120. }
  121. return h.statusCode
  122. }
  123. // SetStatusCode sets response status code.
  124. func (h *ResponseHeader) SetStatusCode(statusCode int) {
  125. h.statusCode = statusCode
  126. }
  127. // StatusMessage returns response status message.
  128. func (h *ResponseHeader) StatusMessage() []byte {
  129. return h.statusMessage
  130. }
  131. // SetStatusMessage sets response status message bytes.
  132. func (h *ResponseHeader) SetStatusMessage(statusMessage []byte) {
  133. h.statusMessage = append(h.statusMessage[:0], statusMessage...)
  134. }
  135. // Protocol returns response protocol bytes.
  136. func (h *ResponseHeader) Protocol() []byte {
  137. if len(h.protocol) > 0 {
  138. return h.protocol
  139. }
  140. return strHTTP11
  141. }
  142. // SetProtocol sets response protocol bytes.
  143. func (h *ResponseHeader) SetProtocol(protocol []byte) {
  144. h.protocol = append(h.protocol[:0], protocol...)
  145. }
  146. // SetLastModified sets 'Last-Modified' header to the given value.
  147. func (h *ResponseHeader) SetLastModified(t time.Time) {
  148. h.bufV = AppendHTTPDate(h.bufV[:0], t)
  149. h.setNonSpecial(strLastModified, h.bufV)
  150. }
  151. // ConnectionClose returns true if 'Connection: close' header is set.
  152. func (h *ResponseHeader) ConnectionClose() bool {
  153. return h.connectionClose
  154. }
  155. // SetConnectionClose sets 'Connection: close' header.
  156. func (h *ResponseHeader) SetConnectionClose() {
  157. h.connectionClose = true
  158. }
  159. // ResetConnectionClose clears 'Connection: close' header if it exists.
  160. func (h *ResponseHeader) ResetConnectionClose() {
  161. if h.connectionClose {
  162. h.connectionClose = false
  163. h.h = delAllArgs(h.h, HeaderConnection)
  164. }
  165. }
  166. // ConnectionClose returns true if 'Connection: close' header is set.
  167. func (h *RequestHeader) ConnectionClose() bool {
  168. return h.connectionClose
  169. }
  170. // SetConnectionClose sets 'Connection: close' header.
  171. func (h *RequestHeader) SetConnectionClose() {
  172. h.connectionClose = true
  173. }
  174. // ResetConnectionClose clears 'Connection: close' header if it exists.
  175. func (h *RequestHeader) ResetConnectionClose() {
  176. if h.connectionClose {
  177. h.connectionClose = false
  178. h.h = delAllArgs(h.h, HeaderConnection)
  179. }
  180. }
  181. // ConnectionUpgrade returns true if 'Connection: Upgrade' header is set.
  182. func (h *ResponseHeader) ConnectionUpgrade() bool {
  183. return hasHeaderValue(h.Peek(HeaderConnection), strUpgrade)
  184. }
  185. // ConnectionUpgrade returns true if 'Connection: Upgrade' header is set.
  186. func (h *RequestHeader) ConnectionUpgrade() bool {
  187. return hasHeaderValue(h.Peek(HeaderConnection), strUpgrade)
  188. }
  189. // PeekCookie is able to returns cookie by a given key from response.
  190. func (h *ResponseHeader) PeekCookie(key string) []byte {
  191. return peekArgStr(h.cookies, key)
  192. }
  193. // ContentLength returns Content-Length header value.
  194. //
  195. // It may be negative:
  196. // -1 means Transfer-Encoding: chunked.
  197. // -2 means Transfer-Encoding: identity.
  198. func (h *ResponseHeader) ContentLength() int {
  199. return h.contentLength
  200. }
  201. // SetContentLength sets Content-Length header value.
  202. //
  203. // Content-Length may be negative:
  204. // -1 means Transfer-Encoding: chunked.
  205. // -2 means Transfer-Encoding: identity.
  206. func (h *ResponseHeader) SetContentLength(contentLength int) {
  207. if h.mustSkipContentLength() {
  208. return
  209. }
  210. h.contentLength = contentLength
  211. if contentLength >= 0 {
  212. h.contentLengthBytes = AppendUint(h.contentLengthBytes[:0], contentLength)
  213. h.h = delAllArgs(h.h, HeaderTransferEncoding)
  214. return
  215. } else if contentLength == -1 {
  216. h.contentLengthBytes = h.contentLengthBytes[:0]
  217. h.h = setArgBytes(h.h, strTransferEncoding, strChunked, argsHasValue)
  218. return
  219. }
  220. h.SetConnectionClose()
  221. }
  222. func (h *ResponseHeader) mustSkipContentLength() bool {
  223. // From http/1.1 specs:
  224. // All 1xx (informational), 204 (no content), and 304 (not modified) responses MUST NOT include a message-body
  225. statusCode := h.StatusCode()
  226. // Fast path.
  227. if statusCode < 100 || statusCode == StatusOK {
  228. return false
  229. }
  230. // Slow path.
  231. return statusCode == StatusNotModified || statusCode == StatusNoContent || statusCode < 200
  232. }
  233. // ContentLength returns Content-Length header value.
  234. //
  235. // It may be negative:
  236. // -1 means Transfer-Encoding: chunked.
  237. func (h *RequestHeader) ContentLength() int {
  238. return h.realContentLength()
  239. }
  240. // realContentLength returns the actual Content-Length set in the request,
  241. // including positive lengths for GET/HEAD requests.
  242. func (h *RequestHeader) realContentLength() int {
  243. return h.contentLength
  244. }
  245. // SetContentLength sets Content-Length header value.
  246. //
  247. // Negative content-length sets 'Transfer-Encoding: chunked' header.
  248. func (h *RequestHeader) SetContentLength(contentLength int) {
  249. h.contentLength = contentLength
  250. if contentLength >= 0 {
  251. h.contentLengthBytes = AppendUint(h.contentLengthBytes[:0], contentLength)
  252. h.h = delAllArgs(h.h, HeaderTransferEncoding)
  253. } else {
  254. h.contentLengthBytes = h.contentLengthBytes[:0]
  255. h.h = setArgBytes(h.h, strTransferEncoding, strChunked, argsHasValue)
  256. }
  257. }
  258. func (h *ResponseHeader) isCompressibleContentType() bool {
  259. contentType := h.ContentType()
  260. return bytes.HasPrefix(contentType, strTextSlash) ||
  261. bytes.HasPrefix(contentType, strApplicationSlash) ||
  262. bytes.HasPrefix(contentType, strImageSVG) ||
  263. bytes.HasPrefix(contentType, strImageIcon) ||
  264. bytes.HasPrefix(contentType, strFontSlash) ||
  265. bytes.HasPrefix(contentType, strMultipartSlash)
  266. }
  267. // ContentType returns Content-Type header value.
  268. func (h *ResponseHeader) ContentType() []byte {
  269. contentType := h.contentType
  270. if !h.noDefaultContentType && len(h.contentType) == 0 {
  271. contentType = defaultContentType
  272. }
  273. return contentType
  274. }
  275. // SetContentType sets Content-Type header value.
  276. func (h *ResponseHeader) SetContentType(contentType string) {
  277. h.contentType = append(h.contentType[:0], contentType...)
  278. }
  279. // SetContentTypeBytes sets Content-Type header value.
  280. func (h *ResponseHeader) SetContentTypeBytes(contentType []byte) {
  281. h.contentType = append(h.contentType[:0], contentType...)
  282. }
  283. // ContentEncoding returns Content-Encoding header value.
  284. func (h *ResponseHeader) ContentEncoding() []byte {
  285. return h.contentEncoding
  286. }
  287. // SetContentEncoding sets Content-Encoding header value.
  288. func (h *ResponseHeader) SetContentEncoding(contentEncoding string) {
  289. h.contentEncoding = append(h.contentEncoding[:0], contentEncoding...)
  290. }
  291. // SetContentEncodingBytes sets Content-Encoding header value.
  292. func (h *ResponseHeader) SetContentEncodingBytes(contentEncoding []byte) {
  293. h.contentEncoding = append(h.contentEncoding[:0], contentEncoding...)
  294. }
  295. // addVaryBytes add value to the 'Vary' header if it's not included.
  296. func (h *ResponseHeader) addVaryBytes(value []byte) {
  297. v := h.peek(strVary)
  298. if len(v) == 0 {
  299. // 'Vary' is not set
  300. h.SetBytesV(HeaderVary, value)
  301. } else if !bytes.Contains(v, value) {
  302. // 'Vary' is set and not contains target value
  303. h.SetBytesV(HeaderVary, append(append(v, ','), value...))
  304. } // else: 'Vary' is set and contains target value
  305. }
  306. // Server returns Server header value.
  307. func (h *ResponseHeader) Server() []byte {
  308. return h.server
  309. }
  310. // SetServer sets Server header value.
  311. func (h *ResponseHeader) SetServer(server string) {
  312. h.server = append(h.server[:0], server...)
  313. }
  314. // SetServerBytes sets Server header value.
  315. func (h *ResponseHeader) SetServerBytes(server []byte) {
  316. h.server = append(h.server[:0], server...)
  317. }
  318. // ContentType returns Content-Type header value.
  319. func (h *RequestHeader) ContentType() []byte {
  320. if h.disableSpecialHeader {
  321. return peekArgBytes(h.h, []byte(HeaderContentType))
  322. }
  323. return h.contentType
  324. }
  325. // SetContentType sets Content-Type header value.
  326. func (h *RequestHeader) SetContentType(contentType string) {
  327. h.contentType = append(h.contentType[:0], contentType...)
  328. }
  329. // SetContentTypeBytes sets Content-Type header value.
  330. func (h *RequestHeader) SetContentTypeBytes(contentType []byte) {
  331. h.contentType = append(h.contentType[:0], contentType...)
  332. }
  333. // ContentEncoding returns Content-Encoding header value.
  334. func (h *RequestHeader) ContentEncoding() []byte {
  335. return peekArgBytes(h.h, strContentEncoding)
  336. }
  337. // SetContentEncoding sets Content-Encoding header value.
  338. func (h *RequestHeader) SetContentEncoding(contentEncoding string) {
  339. h.SetBytesK(strContentEncoding, contentEncoding)
  340. }
  341. // SetContentEncodingBytes sets Content-Encoding header value.
  342. func (h *RequestHeader) SetContentEncodingBytes(contentEncoding []byte) {
  343. h.setNonSpecial(strContentEncoding, contentEncoding)
  344. }
  345. // SetMultipartFormBoundary sets the following Content-Type:
  346. // 'multipart/form-data; boundary=...'
  347. // where ... is substituted by the given boundary.
  348. func (h *RequestHeader) SetMultipartFormBoundary(boundary string) {
  349. b := h.bufV[:0]
  350. b = append(b, strMultipartFormData...)
  351. b = append(b, ';', ' ')
  352. b = append(b, strBoundary...)
  353. b = append(b, '=')
  354. b = append(b, boundary...)
  355. h.bufV = b
  356. h.SetContentTypeBytes(h.bufV)
  357. }
  358. // SetMultipartFormBoundaryBytes sets the following Content-Type:
  359. // 'multipart/form-data; boundary=...'
  360. // where ... is substituted by the given boundary.
  361. func (h *RequestHeader) SetMultipartFormBoundaryBytes(boundary []byte) {
  362. b := h.bufV[:0]
  363. b = append(b, strMultipartFormData...)
  364. b = append(b, ';', ' ')
  365. b = append(b, strBoundary...)
  366. b = append(b, '=')
  367. b = append(b, boundary...)
  368. h.bufV = b
  369. h.SetContentTypeBytes(h.bufV)
  370. }
  371. // SetTrailer sets header Trailer value for chunked response
  372. // to indicate which headers will be sent after the body.
  373. //
  374. // Use Set to set the trailer header later.
  375. //
  376. // Trailers are only supported with chunked transfer.
  377. // Trailers allow the sender to include additional headers at the end of chunked messages.
  378. //
  379. // The following trailers are forbidden:
  380. // 1. necessary for message framing (e.g., Transfer-Encoding and Content-Length),
  381. // 2. routing (e.g., Host),
  382. // 3. request modifiers (e.g., controls and conditionals in Section 5 of [RFC7231]),
  383. // 4. authentication (e.g., see [RFC7235] and [RFC6265]),
  384. // 5. response control data (e.g., see Section 7.1 of [RFC7231]),
  385. // 6. determining how to process the payload (e.g., Content-Encoding, Content-Type, Content-Range, and Trailer)
  386. //
  387. // Return ErrBadTrailer if contain any forbidden trailers.
  388. func (h *ResponseHeader) SetTrailer(trailer string) error {
  389. return h.SetTrailerBytes(s2b(trailer))
  390. }
  391. // SetTrailerBytes sets Trailer header value for chunked response
  392. // to indicate which headers will be sent after the body.
  393. //
  394. // Use Set to set the trailer header later.
  395. //
  396. // Trailers are only supported with chunked transfer.
  397. // Trailers allow the sender to include additional headers at the end of chunked messages.
  398. //
  399. // The following trailers are forbidden:
  400. // 1. necessary for message framing (e.g., Transfer-Encoding and Content-Length),
  401. // 2. routing (e.g., Host),
  402. // 3. request modifiers (e.g., controls and conditionals in Section 5 of [RFC7231]),
  403. // 4. authentication (e.g., see [RFC7235] and [RFC6265]),
  404. // 5. response control data (e.g., see Section 7.1 of [RFC7231]),
  405. // 6. determining how to process the payload (e.g., Content-Encoding, Content-Type, Content-Range, and Trailer)
  406. //
  407. // Return ErrBadTrailer if contain any forbidden trailers.
  408. func (h *ResponseHeader) SetTrailerBytes(trailer []byte) error {
  409. h.trailer = h.trailer[:0]
  410. return h.AddTrailerBytes(trailer)
  411. }
  412. // AddTrailer add Trailer header value for chunked response
  413. // to indicate which headers will be sent after the body.
  414. //
  415. // Use Set to set the trailer header later.
  416. //
  417. // Trailers are only supported with chunked transfer.
  418. // Trailers allow the sender to include additional headers at the end of chunked messages.
  419. //
  420. // The following trailers are forbidden:
  421. // 1. necessary for message framing (e.g., Transfer-Encoding and Content-Length),
  422. // 2. routing (e.g., Host),
  423. // 3. request modifiers (e.g., controls and conditionals in Section 5 of [RFC7231]),
  424. // 4. authentication (e.g., see [RFC7235] and [RFC6265]),
  425. // 5. response control data (e.g., see Section 7.1 of [RFC7231]),
  426. // 6. determining how to process the payload (e.g., Content-Encoding, Content-Type, Content-Range, and Trailer)
  427. //
  428. // Return ErrBadTrailer if contain any forbidden trailers.
  429. func (h *ResponseHeader) AddTrailer(trailer string) error {
  430. return h.AddTrailerBytes(s2b(trailer))
  431. }
  432. var ErrBadTrailer = errors.New("contain forbidden trailer")
  433. // AddTrailerBytes add Trailer header value for chunked response
  434. // to indicate which headers will be sent after the body.
  435. //
  436. // Use Set to set the trailer header later.
  437. //
  438. // Trailers are only supported with chunked transfer.
  439. // Trailers allow the sender to include additional headers at the end of chunked messages.
  440. //
  441. // The following trailers are forbidden:
  442. // 1. necessary for message framing (e.g., Transfer-Encoding and Content-Length),
  443. // 2. routing (e.g., Host),
  444. // 3. request modifiers (e.g., controls and conditionals in Section 5 of [RFC7231]),
  445. // 4. authentication (e.g., see [RFC7235] and [RFC6265]),
  446. // 5. response control data (e.g., see Section 7.1 of [RFC7231]),
  447. // 6. determining how to process the payload (e.g., Content-Encoding, Content-Type, Content-Range, and Trailer)
  448. //
  449. // Return ErrBadTrailer if contain any forbidden trailers.
  450. func (h *ResponseHeader) AddTrailerBytes(trailer []byte) (err error) {
  451. h.bufK, h.trailer, err = addTrailerBytes(trailer, h.bufK, h.trailer, h.disableNormalizing)
  452. return err
  453. }
  454. // validHeaderFieldByte returns true if c valid header field byte
  455. // as defined by RFC 7230.
  456. func validHeaderFieldByte(c byte) bool {
  457. return c < 128 && validHeaderFieldByteTable[c] == 1
  458. }
  459. // validHeaderValueByte returns true if c valid header value byte
  460. // as defined by RFC 7230.
  461. func validHeaderValueByte(c byte) bool {
  462. return validHeaderValueByteTable[c] == 1
  463. }
  464. // VisitHeaderParams calls f for each parameter in the given header bytes.
  465. // It stops processing when f returns false or an invalid parameter is found.
  466. // Parameter values may be quoted, in which case \ is treated as an escape
  467. // character, and the value is unquoted before being passed to value.
  468. // See: https://www.rfc-editor.org/rfc/rfc9110#section-5.6.6
  469. //
  470. // f must not retain references to key and/or value after returning.
  471. // Copy key and/or value contents before returning if you need retaining them.
  472. func VisitHeaderParams(b []byte, f func(key, value []byte) bool) {
  473. for len(b) > 0 {
  474. idxSemi := 0
  475. for idxSemi < len(b) && b[idxSemi] != ';' {
  476. idxSemi++
  477. }
  478. if idxSemi >= len(b) {
  479. return
  480. }
  481. b = b[idxSemi+1:]
  482. for len(b) > 0 && b[0] == ' ' {
  483. b = b[1:]
  484. }
  485. n := 0
  486. if len(b) == 0 || !validHeaderFieldByte(b[n]) {
  487. return
  488. }
  489. n++
  490. for n < len(b) && validHeaderFieldByte(b[n]) {
  491. n++
  492. }
  493. if n >= len(b)-1 || b[n] != '=' {
  494. return
  495. }
  496. param := b[:n]
  497. n++
  498. switch {
  499. case validHeaderFieldByte(b[n]):
  500. m := n
  501. n++
  502. for n < len(b) && validHeaderFieldByte(b[n]) {
  503. n++
  504. }
  505. if !f(param, b[m:n]) {
  506. return
  507. }
  508. case b[n] == '"':
  509. foundEndQuote := false
  510. escaping := false
  511. n++
  512. m := n
  513. for ; n < len(b); n++ {
  514. if b[n] == '"' && !escaping {
  515. foundEndQuote = true
  516. break
  517. }
  518. escaping = (b[n] == '\\' && !escaping)
  519. }
  520. if !foundEndQuote {
  521. return
  522. }
  523. if !f(param, b[m:n]) {
  524. return
  525. }
  526. n++
  527. default:
  528. return
  529. }
  530. b = b[n:]
  531. }
  532. }
  533. // MultipartFormBoundary returns boundary part
  534. // from 'multipart/form-data; boundary=...' Content-Type.
  535. func (h *RequestHeader) MultipartFormBoundary() []byte {
  536. b := h.ContentType()
  537. if !bytes.HasPrefix(b, strMultipartFormData) {
  538. return nil
  539. }
  540. b = b[len(strMultipartFormData):]
  541. if len(b) == 0 || b[0] != ';' {
  542. return nil
  543. }
  544. var n int
  545. for len(b) > 0 {
  546. n++
  547. for len(b) > n && b[n] == ' ' {
  548. n++
  549. }
  550. b = b[n:]
  551. if !bytes.HasPrefix(b, strBoundary) {
  552. if n = bytes.IndexByte(b, ';'); n < 0 {
  553. return nil
  554. }
  555. continue
  556. }
  557. b = b[len(strBoundary):]
  558. if len(b) == 0 || b[0] != '=' {
  559. return nil
  560. }
  561. b = b[1:]
  562. if n = bytes.IndexByte(b, ';'); n >= 0 {
  563. b = b[:n]
  564. }
  565. if len(b) > 1 && b[0] == '"' && b[len(b)-1] == '"' {
  566. b = b[1 : len(b)-1]
  567. }
  568. return b
  569. }
  570. return nil
  571. }
  572. // Host returns Host header value.
  573. func (h *RequestHeader) Host() []byte {
  574. if h.disableSpecialHeader {
  575. return peekArgBytes(h.h, []byte(HeaderHost))
  576. }
  577. return h.host
  578. }
  579. // SetHost sets Host header value.
  580. func (h *RequestHeader) SetHost(host string) {
  581. h.host = append(h.host[:0], host...)
  582. }
  583. // SetHostBytes sets Host header value.
  584. func (h *RequestHeader) SetHostBytes(host []byte) {
  585. h.host = append(h.host[:0], host...)
  586. }
  587. // UserAgent returns User-Agent header value.
  588. func (h *RequestHeader) UserAgent() []byte {
  589. if h.disableSpecialHeader {
  590. return peekArgBytes(h.h, []byte(HeaderUserAgent))
  591. }
  592. return h.userAgent
  593. }
  594. // SetUserAgent sets User-Agent header value.
  595. func (h *RequestHeader) SetUserAgent(userAgent string) {
  596. h.userAgent = append(h.userAgent[:0], userAgent...)
  597. }
  598. // SetUserAgentBytes sets User-Agent header value.
  599. func (h *RequestHeader) SetUserAgentBytes(userAgent []byte) {
  600. h.userAgent = append(h.userAgent[:0], userAgent...)
  601. }
  602. // Referer returns Referer header value.
  603. func (h *RequestHeader) Referer() []byte {
  604. return peekArgBytes(h.h, strReferer)
  605. }
  606. // SetReferer sets Referer header value.
  607. func (h *RequestHeader) SetReferer(referer string) {
  608. h.SetBytesK(strReferer, referer)
  609. }
  610. // SetRefererBytes sets Referer header value.
  611. func (h *RequestHeader) SetRefererBytes(referer []byte) {
  612. h.setNonSpecial(strReferer, referer)
  613. }
  614. // Method returns HTTP request method.
  615. func (h *RequestHeader) Method() []byte {
  616. if len(h.method) == 0 {
  617. return []byte(MethodGet)
  618. }
  619. return h.method
  620. }
  621. // SetMethod sets HTTP request method.
  622. func (h *RequestHeader) SetMethod(method string) {
  623. h.method = append(h.method[:0], method...)
  624. }
  625. // SetMethodBytes sets HTTP request method.
  626. func (h *RequestHeader) SetMethodBytes(method []byte) {
  627. h.method = append(h.method[:0], method...)
  628. }
  629. // Protocol returns HTTP protocol.
  630. func (h *RequestHeader) Protocol() []byte {
  631. if len(h.proto) == 0 {
  632. return strHTTP11
  633. }
  634. return h.proto
  635. }
  636. // SetProtocol sets HTTP request protocol.
  637. func (h *RequestHeader) SetProtocol(method string) {
  638. h.proto = append(h.proto[:0], method...)
  639. h.noHTTP11 = !bytes.Equal(h.proto, strHTTP11)
  640. }
  641. // SetProtocolBytes sets HTTP request protocol.
  642. func (h *RequestHeader) SetProtocolBytes(method []byte) {
  643. h.proto = append(h.proto[:0], method...)
  644. h.noHTTP11 = !bytes.Equal(h.proto, strHTTP11)
  645. }
  646. // RequestURI returns RequestURI from the first HTTP request line.
  647. func (h *RequestHeader) RequestURI() []byte {
  648. requestURI := h.requestURI
  649. if len(requestURI) == 0 {
  650. requestURI = strSlash
  651. }
  652. return requestURI
  653. }
  654. // SetRequestURI sets RequestURI for the first HTTP request line.
  655. // RequestURI must be properly encoded.
  656. // Use URI.RequestURI for constructing proper RequestURI if unsure.
  657. func (h *RequestHeader) SetRequestURI(requestURI string) {
  658. h.requestURI = append(h.requestURI[:0], requestURI...)
  659. }
  660. // SetRequestURIBytes sets RequestURI for the first HTTP request line.
  661. // RequestURI must be properly encoded.
  662. // Use URI.RequestURI for constructing proper RequestURI if unsure.
  663. func (h *RequestHeader) SetRequestURIBytes(requestURI []byte) {
  664. h.requestURI = append(h.requestURI[:0], requestURI...)
  665. }
  666. // SetTrailer sets Trailer header value for chunked request
  667. // to indicate which headers will be sent after the body.
  668. //
  669. // Use Set to set the trailer header later.
  670. //
  671. // Trailers are only supported with chunked transfer.
  672. // Trailers allow the sender to include additional headers at the end of chunked messages.
  673. //
  674. // The following trailers are forbidden:
  675. // 1. necessary for message framing (e.g., Transfer-Encoding and Content-Length),
  676. // 2. routing (e.g., Host),
  677. // 3. request modifiers (e.g., controls and conditionals in Section 5 of [RFC7231]),
  678. // 4. authentication (e.g., see [RFC7235] and [RFC6265]),
  679. // 5. response control data (e.g., see Section 7.1 of [RFC7231]),
  680. // 6. determining how to process the payload (e.g., Content-Encoding, Content-Type, Content-Range, and Trailer)
  681. //
  682. // Return ErrBadTrailer if contain any forbidden trailers.
  683. func (h *RequestHeader) SetTrailer(trailer string) error {
  684. return h.SetTrailerBytes(s2b(trailer))
  685. }
  686. // SetTrailerBytes sets Trailer header value for chunked request
  687. // to indicate which headers will be sent after the body.
  688. //
  689. // Use Set to set the trailer header later.
  690. //
  691. // Trailers are only supported with chunked transfer.
  692. // Trailers allow the sender to include additional headers at the end of chunked messages.
  693. //
  694. // The following trailers are forbidden:
  695. // 1. necessary for message framing (e.g., Transfer-Encoding and Content-Length),
  696. // 2. routing (e.g., Host),
  697. // 3. request modifiers (e.g., controls and conditionals in Section 5 of [RFC7231]),
  698. // 4. authentication (e.g., see [RFC7235] and [RFC6265]),
  699. // 5. response control data (e.g., see Section 7.1 of [RFC7231]),
  700. // 6. determining how to process the payload (e.g., Content-Encoding, Content-Type, Content-Range, and Trailer)
  701. //
  702. // Return ErrBadTrailer if contain any forbidden trailers.
  703. func (h *RequestHeader) SetTrailerBytes(trailer []byte) error {
  704. h.trailer = h.trailer[:0]
  705. return h.AddTrailerBytes(trailer)
  706. }
  707. // AddTrailer add Trailer header value for chunked request
  708. // to indicate which headers will be sent after the body.
  709. //
  710. // Use Set to set the trailer header later.
  711. //
  712. // Trailers are only supported with chunked transfer.
  713. // Trailers allow the sender to include additional headers at the end of chunked messages.
  714. //
  715. // The following trailers are forbidden:
  716. // 1. necessary for message framing (e.g., Transfer-Encoding and Content-Length),
  717. // 2. routing (e.g., Host),
  718. // 3. request modifiers (e.g., controls and conditionals in Section 5 of [RFC7231]),
  719. // 4. authentication (e.g., see [RFC7235] and [RFC6265]),
  720. // 5. response control data (e.g., see Section 7.1 of [RFC7231]),
  721. // 6. determining how to process the payload (e.g., Content-Encoding, Content-Type, Content-Range, and Trailer)
  722. //
  723. // Return ErrBadTrailer if contain any forbidden trailers.
  724. func (h *RequestHeader) AddTrailer(trailer string) error {
  725. return h.AddTrailerBytes(s2b(trailer))
  726. }
  727. // AddTrailerBytes add Trailer header value for chunked request
  728. // to indicate which headers will be sent after the body.
  729. //
  730. // Use Set to set the trailer header later.
  731. //
  732. // Trailers are only supported with chunked transfer.
  733. // Trailers allow the sender to include additional headers at the end of chunked messages.
  734. //
  735. // The following trailers are forbidden:
  736. // 1. necessary for message framing (e.g., Transfer-Encoding and Content-Length),
  737. // 2. routing (e.g., Host),
  738. // 3. request modifiers (e.g., controls and conditionals in Section 5 of [RFC7231]),
  739. // 4. authentication (e.g., see [RFC7235] and [RFC6265]),
  740. // 5. response control data (e.g., see Section 7.1 of [RFC7231]),
  741. // 6. determining how to process the payload (e.g., Content-Encoding, Content-Type, Content-Range, and Trailer)
  742. //
  743. // Return ErrBadTrailer if contain any forbidden trailers.
  744. func (h *RequestHeader) AddTrailerBytes(trailer []byte) (err error) {
  745. h.bufK, h.trailer, err = addTrailerBytes(trailer, h.bufK, h.trailer, h.disableNormalizing)
  746. return err
  747. }
  748. // IsGet returns true if request method is GET.
  749. func (h *RequestHeader) IsGet() bool {
  750. return string(h.Method()) == MethodGet
  751. }
  752. // IsPost returns true if request method is POST.
  753. func (h *RequestHeader) IsPost() bool {
  754. return string(h.Method()) == MethodPost
  755. }
  756. // IsPut returns true if request method is PUT.
  757. func (h *RequestHeader) IsPut() bool {
  758. return string(h.Method()) == MethodPut
  759. }
  760. // IsHead returns true if request method is HEAD.
  761. func (h *RequestHeader) IsHead() bool {
  762. return string(h.Method()) == MethodHead
  763. }
  764. // IsDelete returns true if request method is DELETE.
  765. func (h *RequestHeader) IsDelete() bool {
  766. return string(h.Method()) == MethodDelete
  767. }
  768. // IsConnect returns true if request method is CONNECT.
  769. func (h *RequestHeader) IsConnect() bool {
  770. return string(h.Method()) == MethodConnect
  771. }
  772. // IsOptions returns true if request method is OPTIONS.
  773. func (h *RequestHeader) IsOptions() bool {
  774. return string(h.Method()) == MethodOptions
  775. }
  776. // IsTrace returns true if request method is TRACE.
  777. func (h *RequestHeader) IsTrace() bool {
  778. return string(h.Method()) == MethodTrace
  779. }
  780. // IsPatch returns true if request method is PATCH.
  781. func (h *RequestHeader) IsPatch() bool {
  782. return string(h.Method()) == MethodPatch
  783. }
  784. // IsHTTP11 returns true if the request is HTTP/1.1.
  785. func (h *RequestHeader) IsHTTP11() bool {
  786. return !h.noHTTP11
  787. }
  788. // IsHTTP11 returns true if the response is HTTP/1.1.
  789. func (h *ResponseHeader) IsHTTP11() bool {
  790. return !h.noHTTP11
  791. }
  792. // HasAcceptEncoding returns true if the header contains
  793. // the given Accept-Encoding value.
  794. func (h *RequestHeader) HasAcceptEncoding(acceptEncoding string) bool {
  795. h.bufV = append(h.bufV[:0], acceptEncoding...)
  796. return h.HasAcceptEncodingBytes(h.bufV)
  797. }
  798. // HasAcceptEncodingBytes returns true if the header contains
  799. // the given Accept-Encoding value.
  800. func (h *RequestHeader) HasAcceptEncodingBytes(acceptEncoding []byte) bool {
  801. ae := h.peek(strAcceptEncoding)
  802. n := bytes.Index(ae, acceptEncoding)
  803. if n < 0 {
  804. return false
  805. }
  806. b := ae[n+len(acceptEncoding):]
  807. if len(b) > 0 && b[0] != ',' {
  808. return false
  809. }
  810. if n == 0 {
  811. return true
  812. }
  813. return ae[n-1] == ' '
  814. }
  815. // Len returns the number of headers set,
  816. // i.e. the number of times f is called in VisitAll.
  817. func (h *ResponseHeader) Len() int {
  818. n := 0
  819. h.VisitAll(func(_, _ []byte) { n++ })
  820. return n
  821. }
  822. // Len returns the number of headers set,
  823. // i.e. the number of times f is called in VisitAll.
  824. func (h *RequestHeader) Len() int {
  825. n := 0
  826. h.VisitAll(func(_, _ []byte) { n++ })
  827. return n
  828. }
  829. // DisableSpecialHeader disables special header processing.
  830. // fasthttp will not set any special headers for you, such as Host, Content-Type, User-Agent, etc.
  831. // You must set everything yourself.
  832. // If RequestHeader.Read() is called, special headers will be ignored.
  833. // This can be used to control case and order of special headers.
  834. // This is generally not recommended.
  835. func (h *RequestHeader) DisableSpecialHeader() {
  836. h.disableSpecialHeader = true
  837. }
  838. // EnableSpecialHeader enables special header processing.
  839. // fasthttp will send Host, Content-Type, User-Agent, etc headers for you.
  840. // This is suggested and enabled by default.
  841. func (h *RequestHeader) EnableSpecialHeader() {
  842. h.disableSpecialHeader = false
  843. }
  844. // DisableNormalizing disables header names' normalization.
  845. //
  846. // By default all the header names are normalized by uppercasing
  847. // the first letter and all the first letters following dashes,
  848. // while lowercasing all the other letters.
  849. // Examples:
  850. //
  851. // - CONNECTION -> Connection
  852. // - conteNT-tYPE -> Content-Type
  853. // - foo-bar-baz -> Foo-Bar-Baz
  854. //
  855. // Disable header names' normalization only if know what are you doing.
  856. func (h *RequestHeader) DisableNormalizing() {
  857. h.disableNormalizing = true
  858. }
  859. // EnableNormalizing enables header names' normalization.
  860. //
  861. // Header names are normalized by uppercasing the first letter and
  862. // all the first letters following dashes, while lowercasing all
  863. // the other letters.
  864. // Examples:
  865. //
  866. // - CONNECTION -> Connection
  867. // - conteNT-tYPE -> Content-Type
  868. // - foo-bar-baz -> Foo-Bar-Baz
  869. //
  870. // This is enabled by default unless disabled using DisableNormalizing().
  871. func (h *RequestHeader) EnableNormalizing() {
  872. h.disableNormalizing = false
  873. }
  874. // DisableNormalizing disables header names' normalization.
  875. //
  876. // By default all the header names are normalized by uppercasing
  877. // the first letter and all the first letters following dashes,
  878. // while lowercasing all the other letters.
  879. // Examples:
  880. //
  881. // - CONNECTION -> Connection
  882. // - conteNT-tYPE -> Content-Type
  883. // - foo-bar-baz -> Foo-Bar-Baz
  884. //
  885. // Disable header names' normalization only if know what are you doing.
  886. func (h *ResponseHeader) DisableNormalizing() {
  887. h.disableNormalizing = true
  888. }
  889. // EnableNormalizing enables header names' normalization.
  890. //
  891. // Header names are normalized by uppercasing the first letter and
  892. // all the first letters following dashes, while lowercasing all
  893. // the other letters.
  894. // Examples:
  895. //
  896. // - CONNECTION -> Connection
  897. // - conteNT-tYPE -> Content-Type
  898. // - foo-bar-baz -> Foo-Bar-Baz
  899. //
  900. // This is enabled by default unless disabled using DisableNormalizing().
  901. func (h *ResponseHeader) EnableNormalizing() {
  902. h.disableNormalizing = false
  903. }
  904. // SetNoDefaultContentType allows you to control if a default Content-Type header will be set (false) or not (true).
  905. func (h *ResponseHeader) SetNoDefaultContentType(noDefaultContentType bool) {
  906. h.noDefaultContentType = noDefaultContentType
  907. }
  908. // Reset clears response header.
  909. func (h *ResponseHeader) Reset() {
  910. h.disableNormalizing = false
  911. h.SetNoDefaultContentType(false)
  912. h.noDefaultDate = false
  913. h.resetSkipNormalize()
  914. }
  915. func (h *ResponseHeader) resetSkipNormalize() {
  916. h.noHTTP11 = false
  917. h.connectionClose = false
  918. h.statusCode = 0
  919. h.statusMessage = h.statusMessage[:0]
  920. h.protocol = h.protocol[:0]
  921. h.contentLength = 0
  922. h.contentLengthBytes = h.contentLengthBytes[:0]
  923. h.contentType = h.contentType[:0]
  924. h.contentEncoding = h.contentEncoding[:0]
  925. h.server = h.server[:0]
  926. h.h = h.h[:0]
  927. h.cookies = h.cookies[:0]
  928. h.trailer = h.trailer[:0]
  929. h.mulHeader = h.mulHeader[:0]
  930. }
  931. // SetNoDefaultContentType allows you to control if a default Content-Type header will be set (false) or not (true).
  932. func (h *RequestHeader) SetNoDefaultContentType(noDefaultContentType bool) {
  933. h.noDefaultContentType = noDefaultContentType
  934. }
  935. // Reset clears request header.
  936. func (h *RequestHeader) Reset() {
  937. h.disableSpecialHeader = false
  938. h.disableNormalizing = false
  939. h.SetNoDefaultContentType(false)
  940. h.resetSkipNormalize()
  941. }
  942. func (h *RequestHeader) resetSkipNormalize() {
  943. h.noHTTP11 = false
  944. h.connectionClose = false
  945. h.contentLength = 0
  946. h.contentLengthBytes = h.contentLengthBytes[:0]
  947. h.method = h.method[:0]
  948. h.proto = h.proto[:0]
  949. h.requestURI = h.requestURI[:0]
  950. h.host = h.host[:0]
  951. h.contentType = h.contentType[:0]
  952. h.userAgent = h.userAgent[:0]
  953. h.trailer = h.trailer[:0]
  954. h.mulHeader = h.mulHeader[:0]
  955. h.h = h.h[:0]
  956. h.cookies = h.cookies[:0]
  957. h.cookiesCollected = false
  958. h.rawHeaders = h.rawHeaders[:0]
  959. }
  960. // CopyTo copies all the headers to dst.
  961. func (h *ResponseHeader) CopyTo(dst *ResponseHeader) {
  962. dst.Reset()
  963. dst.disableNormalizing = h.disableNormalizing
  964. dst.noHTTP11 = h.noHTTP11
  965. dst.connectionClose = h.connectionClose
  966. dst.noDefaultContentType = h.noDefaultContentType
  967. dst.noDefaultDate = h.noDefaultDate
  968. dst.statusCode = h.statusCode
  969. dst.statusMessage = append(dst.statusMessage, h.statusMessage...)
  970. dst.protocol = append(dst.protocol, h.protocol...)
  971. dst.contentLength = h.contentLength
  972. dst.contentLengthBytes = append(dst.contentLengthBytes, h.contentLengthBytes...)
  973. dst.contentType = append(dst.contentType, h.contentType...)
  974. dst.contentEncoding = append(dst.contentEncoding, h.contentEncoding...)
  975. dst.server = append(dst.server, h.server...)
  976. dst.h = copyArgs(dst.h, h.h)
  977. dst.cookies = copyArgs(dst.cookies, h.cookies)
  978. dst.trailer = copyTrailer(dst.trailer, h.trailer)
  979. }
  980. // CopyTo copies all the headers to dst.
  981. func (h *RequestHeader) CopyTo(dst *RequestHeader) {
  982. dst.Reset()
  983. dst.disableNormalizing = h.disableNormalizing
  984. dst.noHTTP11 = h.noHTTP11
  985. dst.connectionClose = h.connectionClose
  986. dst.noDefaultContentType = h.noDefaultContentType
  987. dst.contentLength = h.contentLength
  988. dst.contentLengthBytes = append(dst.contentLengthBytes, h.contentLengthBytes...)
  989. dst.method = append(dst.method, h.method...)
  990. dst.proto = append(dst.proto, h.proto...)
  991. dst.requestURI = append(dst.requestURI, h.requestURI...)
  992. dst.host = append(dst.host, h.host...)
  993. dst.contentType = append(dst.contentType, h.contentType...)
  994. dst.userAgent = append(dst.userAgent, h.userAgent...)
  995. dst.trailer = copyTrailer(dst.trailer, h.trailer)
  996. dst.h = copyArgs(dst.h, h.h)
  997. dst.cookies = copyArgs(dst.cookies, h.cookies)
  998. dst.cookiesCollected = h.cookiesCollected
  999. dst.rawHeaders = append(dst.rawHeaders, h.rawHeaders...)
  1000. }
  1001. // VisitAll calls f for each header.
  1002. //
  1003. // f must not retain references to key and/or value after returning.
  1004. // Copy key and/or value contents before returning if you need retaining them.
  1005. func (h *ResponseHeader) VisitAll(f func(key, value []byte)) {
  1006. if len(h.contentLengthBytes) > 0 {
  1007. f(strContentLength, h.contentLengthBytes)
  1008. }
  1009. contentType := h.ContentType()
  1010. if len(contentType) > 0 {
  1011. f(strContentType, contentType)
  1012. }
  1013. contentEncoding := h.ContentEncoding()
  1014. if len(contentEncoding) > 0 {
  1015. f(strContentEncoding, contentEncoding)
  1016. }
  1017. server := h.Server()
  1018. if len(server) > 0 {
  1019. f(strServer, server)
  1020. }
  1021. if len(h.cookies) > 0 {
  1022. visitArgs(h.cookies, func(_, v []byte) {
  1023. f(strSetCookie, v)
  1024. })
  1025. }
  1026. if len(h.trailer) > 0 {
  1027. f(strTrailer, appendTrailerBytes(nil, h.trailer, strCommaSpace))
  1028. }
  1029. visitArgs(h.h, f)
  1030. if h.ConnectionClose() {
  1031. f(strConnection, strClose)
  1032. }
  1033. }
  1034. // VisitAllTrailer calls f for each response Trailer.
  1035. //
  1036. // f must not retain references to value after returning.
  1037. func (h *ResponseHeader) VisitAllTrailer(f func(value []byte)) {
  1038. for i := range h.trailer {
  1039. f(h.trailer[i])
  1040. }
  1041. }
  1042. // VisitAllTrailer calls f for each request Trailer.
  1043. //
  1044. // f must not retain references to value after returning.
  1045. func (h *RequestHeader) VisitAllTrailer(f func(value []byte)) {
  1046. for i := range h.trailer {
  1047. f(h.trailer[i])
  1048. }
  1049. }
  1050. // VisitAllCookie calls f for each response cookie.
  1051. //
  1052. // Cookie name is passed in key and the whole Set-Cookie header value
  1053. // is passed in value on each f invocation. Value may be parsed
  1054. // with Cookie.ParseBytes().
  1055. //
  1056. // f must not retain references to key and/or value after returning.
  1057. func (h *ResponseHeader) VisitAllCookie(f func(key, value []byte)) {
  1058. visitArgs(h.cookies, f)
  1059. }
  1060. // VisitAllCookie calls f for each request cookie.
  1061. //
  1062. // f must not retain references to key and/or value after returning.
  1063. func (h *RequestHeader) VisitAllCookie(f func(key, value []byte)) {
  1064. h.collectCookies()
  1065. visitArgs(h.cookies, f)
  1066. }
  1067. // VisitAll calls f for each header.
  1068. //
  1069. // f must not retain references to key and/or value after returning.
  1070. // Copy key and/or value contents before returning if you need retaining them.
  1071. //
  1072. // To get the headers in order they were received use VisitAllInOrder.
  1073. func (h *RequestHeader) VisitAll(f func(key, value []byte)) {
  1074. host := h.Host()
  1075. if len(host) > 0 {
  1076. f(strHost, host)
  1077. }
  1078. if len(h.contentLengthBytes) > 0 {
  1079. f(strContentLength, h.contentLengthBytes)
  1080. }
  1081. contentType := h.ContentType()
  1082. if len(contentType) > 0 {
  1083. f(strContentType, contentType)
  1084. }
  1085. userAgent := h.UserAgent()
  1086. if len(userAgent) > 0 {
  1087. f(strUserAgent, userAgent)
  1088. }
  1089. if len(h.trailer) > 0 {
  1090. f(strTrailer, appendTrailerBytes(nil, h.trailer, strCommaSpace))
  1091. }
  1092. h.collectCookies()
  1093. if len(h.cookies) > 0 {
  1094. h.bufV = appendRequestCookieBytes(h.bufV[:0], h.cookies)
  1095. f(strCookie, h.bufV)
  1096. }
  1097. visitArgs(h.h, f)
  1098. if h.ConnectionClose() {
  1099. f(strConnection, strClose)
  1100. }
  1101. }
  1102. // VisitAllInOrder calls f for each header in the order they were received.
  1103. //
  1104. // f must not retain references to key and/or value after returning.
  1105. // Copy key and/or value contents before returning if you need retaining them.
  1106. //
  1107. // This function is slightly slower than VisitAll because it has to reparse the
  1108. // raw headers to get the order.
  1109. func (h *RequestHeader) VisitAllInOrder(f func(key, value []byte)) {
  1110. var s headerScanner
  1111. s.b = h.rawHeaders
  1112. for s.next() {
  1113. normalizeHeaderKey(s.key, h.disableNormalizing || bytes.IndexByte(s.key, ' ') != -1)
  1114. if len(s.key) > 0 {
  1115. f(s.key, s.value)
  1116. }
  1117. }
  1118. }
  1119. // Del deletes header with the given key.
  1120. func (h *ResponseHeader) Del(key string) {
  1121. h.bufK = getHeaderKeyBytes(h.bufK, key, h.disableNormalizing)
  1122. h.del(h.bufK)
  1123. }
  1124. // DelBytes deletes header with the given key.
  1125. func (h *ResponseHeader) DelBytes(key []byte) {
  1126. h.bufK = append(h.bufK[:0], key...)
  1127. normalizeHeaderKey(h.bufK, h.disableNormalizing || bytes.IndexByte(key, ' ') != -1)
  1128. h.del(h.bufK)
  1129. }
  1130. func (h *ResponseHeader) del(key []byte) {
  1131. switch string(key) {
  1132. case HeaderContentType:
  1133. h.contentType = h.contentType[:0]
  1134. case HeaderContentEncoding:
  1135. h.contentEncoding = h.contentEncoding[:0]
  1136. case HeaderServer:
  1137. h.server = h.server[:0]
  1138. case HeaderSetCookie:
  1139. h.cookies = h.cookies[:0]
  1140. case HeaderContentLength:
  1141. h.contentLength = 0
  1142. h.contentLengthBytes = h.contentLengthBytes[:0]
  1143. case HeaderConnection:
  1144. h.connectionClose = false
  1145. case HeaderTrailer:
  1146. h.trailer = h.trailer[:0]
  1147. }
  1148. h.h = delAllArgs(h.h, b2s(key))
  1149. }
  1150. // Del deletes header with the given key.
  1151. func (h *RequestHeader) Del(key string) {
  1152. h.bufK = getHeaderKeyBytes(h.bufK, key, h.disableNormalizing)
  1153. h.del(h.bufK)
  1154. }
  1155. // DelBytes deletes header with the given key.
  1156. func (h *RequestHeader) DelBytes(key []byte) {
  1157. h.bufK = append(h.bufK[:0], key...)
  1158. normalizeHeaderKey(h.bufK, h.disableNormalizing || bytes.IndexByte(key, ' ') != -1)
  1159. h.del(h.bufK)
  1160. }
  1161. func (h *RequestHeader) del(key []byte) {
  1162. switch string(key) {
  1163. case HeaderHost:
  1164. h.host = h.host[:0]
  1165. case HeaderContentType:
  1166. h.contentType = h.contentType[:0]
  1167. case HeaderUserAgent:
  1168. h.userAgent = h.userAgent[:0]
  1169. case HeaderCookie:
  1170. h.cookies = h.cookies[:0]
  1171. case HeaderContentLength:
  1172. h.contentLength = 0
  1173. h.contentLengthBytes = h.contentLengthBytes[:0]
  1174. case HeaderConnection:
  1175. h.connectionClose = false
  1176. case HeaderTrailer:
  1177. h.trailer = h.trailer[:0]
  1178. }
  1179. h.h = delAllArgs(h.h, b2s(key))
  1180. }
  1181. // setSpecialHeader handles special headers and return true when a header is processed.
  1182. func (h *ResponseHeader) setSpecialHeader(key, value []byte) bool {
  1183. if len(key) == 0 {
  1184. return false
  1185. }
  1186. switch key[0] | 0x20 {
  1187. case 'c':
  1188. switch {
  1189. case caseInsensitiveCompare(strContentType, key):
  1190. h.SetContentTypeBytes(value)
  1191. return true
  1192. case caseInsensitiveCompare(strContentLength, key):
  1193. if contentLength, err := parseContentLength(value); err == nil {
  1194. h.contentLength = contentLength
  1195. h.contentLengthBytes = append(h.contentLengthBytes[:0], value...)
  1196. }
  1197. return true
  1198. case caseInsensitiveCompare(strContentEncoding, key):
  1199. h.SetContentEncodingBytes(value)
  1200. return true
  1201. case caseInsensitiveCompare(strConnection, key):
  1202. if bytes.Equal(strClose, value) {
  1203. h.SetConnectionClose()
  1204. } else {
  1205. h.ResetConnectionClose()
  1206. h.setNonSpecial(key, value)
  1207. }
  1208. return true
  1209. }
  1210. case 's':
  1211. if caseInsensitiveCompare(strServer, key) {
  1212. h.SetServerBytes(value)
  1213. return true
  1214. } else if caseInsensitiveCompare(strSetCookie, key) {
  1215. var kv *argsKV
  1216. h.cookies, kv = allocArg(h.cookies)
  1217. kv.key = getCookieKey(kv.key, value)
  1218. kv.value = append(kv.value[:0], value...)
  1219. return true
  1220. }
  1221. case 't':
  1222. if caseInsensitiveCompare(strTransferEncoding, key) {
  1223. // Transfer-Encoding is managed automatically.
  1224. return true
  1225. } else if caseInsensitiveCompare(strTrailer, key) {
  1226. _ = h.SetTrailerBytes(value)
  1227. return true
  1228. }
  1229. case 'd':
  1230. if caseInsensitiveCompare(strDate, key) {
  1231. // Date is managed automatically.
  1232. return true
  1233. }
  1234. }
  1235. return false
  1236. }
  1237. // setNonSpecial directly put into map i.e. not a basic header.
  1238. func (h *ResponseHeader) setNonSpecial(key, value []byte) {
  1239. h.h = setArgBytes(h.h, key, value, argsHasValue)
  1240. }
  1241. // setSpecialHeader handles special headers and return true when a header is processed.
  1242. func (h *RequestHeader) setSpecialHeader(key, value []byte) bool {
  1243. if len(key) == 0 || h.disableSpecialHeader {
  1244. return false
  1245. }
  1246. switch key[0] | 0x20 {
  1247. case 'c':
  1248. switch {
  1249. case caseInsensitiveCompare(strContentType, key):
  1250. h.SetContentTypeBytes(value)
  1251. return true
  1252. case caseInsensitiveCompare(strContentLength, key):
  1253. if contentLength, err := parseContentLength(value); err == nil {
  1254. h.contentLength = contentLength
  1255. h.contentLengthBytes = append(h.contentLengthBytes[:0], value...)
  1256. }
  1257. return true
  1258. case caseInsensitiveCompare(strConnection, key):
  1259. if bytes.Equal(strClose, value) {
  1260. h.SetConnectionClose()
  1261. } else {
  1262. h.ResetConnectionClose()
  1263. h.setNonSpecial(key, value)
  1264. }
  1265. return true
  1266. case caseInsensitiveCompare(strCookie, key):
  1267. h.collectCookies()
  1268. h.cookies = parseRequestCookies(h.cookies, value)
  1269. return true
  1270. }
  1271. case 't':
  1272. if caseInsensitiveCompare(strTransferEncoding, key) {
  1273. // Transfer-Encoding is managed automatically.
  1274. return true
  1275. } else if caseInsensitiveCompare(strTrailer, key) {
  1276. _ = h.SetTrailerBytes(value)
  1277. return true
  1278. }
  1279. case 'h':
  1280. if caseInsensitiveCompare(strHost, key) {
  1281. h.SetHostBytes(value)
  1282. return true
  1283. }
  1284. case 'u':
  1285. if caseInsensitiveCompare(strUserAgent, key) {
  1286. h.SetUserAgentBytes(value)
  1287. return true
  1288. }
  1289. }
  1290. return false
  1291. }
  1292. // setNonSpecial directly put into map i.e. not a basic header.
  1293. func (h *RequestHeader) setNonSpecial(key, value []byte) {
  1294. h.h = setArgBytes(h.h, key, value, argsHasValue)
  1295. }
  1296. // Add adds the given 'key: value' header.
  1297. //
  1298. // Multiple headers with the same key may be added with this function.
  1299. // Use Set for setting a single header for the given key.
  1300. //
  1301. // the Content-Type, Content-Length, Connection, Server, Transfer-Encoding
  1302. // and Date headers can only be set once and will overwrite the previous value,
  1303. // while Set-Cookie will not clear previous cookies.
  1304. //
  1305. // If the header is set as a Trailer (forbidden trailers will not be set, see AddTrailer for more details),
  1306. // it will be sent after the chunked response body.
  1307. func (h *ResponseHeader) Add(key, value string) {
  1308. h.AddBytesKV(s2b(key), s2b(value))
  1309. }
  1310. // AddBytesK adds the given 'key: value' header.
  1311. //
  1312. // Multiple headers with the same key may be added with this function.
  1313. // Use SetBytesK for setting a single header for the given key.
  1314. //
  1315. // the Content-Type, Content-Length, Connection, Server, Transfer-Encoding
  1316. // and Date headers can only be set once and will overwrite the previous value,
  1317. // while Set-Cookie will not clear previous cookies.
  1318. //
  1319. // If the header is set as a Trailer (forbidden trailers will not be set, see AddTrailer for more details),
  1320. // it will be sent after the chunked response body.
  1321. func (h *ResponseHeader) AddBytesK(key []byte, value string) {
  1322. h.AddBytesKV(key, s2b(value))
  1323. }
  1324. // AddBytesV adds the given 'key: value' header.
  1325. //
  1326. // Multiple headers with the same key may be added with this function.
  1327. // Use SetBytesV for setting a single header for the given key.
  1328. //
  1329. // the Content-Type, Content-Length, Connection, Server, Transfer-Encoding
  1330. // and Date headers can only be set once and will overwrite the previous value,
  1331. // while Set-Cookie will not clear previous cookies.
  1332. //
  1333. // If the header is set as a Trailer (forbidden trailers will not be set, see AddTrailer for more details),
  1334. // it will be sent after the chunked response body.
  1335. func (h *ResponseHeader) AddBytesV(key string, value []byte) {
  1336. h.AddBytesKV(s2b(key), value)
  1337. }
  1338. // AddBytesKV adds the given 'key: value' header.
  1339. //
  1340. // Multiple headers with the same key may be added with this function.
  1341. // Use SetBytesKV for setting a single header for the given key.
  1342. //
  1343. // the Content-Type, Content-Length, Connection, Server, Transfer-Encoding
  1344. // and Date headers can only be set once and will overwrite the previous value,
  1345. // while the Set-Cookie header will not clear previous cookies.
  1346. //
  1347. // If the header is set as a Trailer (forbidden trailers will not be set, see AddTrailer for more details),
  1348. // it will be sent after the chunked response body.
  1349. func (h *ResponseHeader) AddBytesKV(key, value []byte) {
  1350. if h.setSpecialHeader(key, value) {
  1351. return
  1352. }
  1353. h.bufK = getHeaderKeyBytes(h.bufK, b2s(key), h.disableNormalizing)
  1354. h.h = appendArgBytes(h.h, h.bufK, value, argsHasValue)
  1355. }
  1356. // Set sets the given 'key: value' header.
  1357. //
  1358. // Please note that the Set-Cookie header will not clear previous cookies,
  1359. // use SetCookie instead to reset cookies.
  1360. //
  1361. // If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details),
  1362. // it will be sent after the chunked response body.
  1363. //
  1364. // Use Add for setting multiple header values under the same key.
  1365. func (h *ResponseHeader) Set(key, value string) {
  1366. h.bufK, h.bufV = initHeaderKV(h.bufK, h.bufV, key, value, h.disableNormalizing)
  1367. h.SetCanonical(h.bufK, h.bufV)
  1368. }
  1369. // SetBytesK sets the given 'key: value' header.
  1370. //
  1371. // Please note that the Set-Cookie header will not clear previous cookies,
  1372. // use SetCookie instead to reset cookies.
  1373. //
  1374. // If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details),
  1375. // it will be sent after the chunked response body.
  1376. //
  1377. // Use AddBytesK for setting multiple header values under the same key.
  1378. func (h *ResponseHeader) SetBytesK(key []byte, value string) {
  1379. h.bufV = append(h.bufV[:0], value...)
  1380. h.SetBytesKV(key, h.bufV)
  1381. }
  1382. // SetBytesV sets the given 'key: value' header.
  1383. //
  1384. // Please note that the Set-Cookie header will not clear previous cookies,
  1385. // use SetCookie instead to reset cookies.
  1386. //
  1387. // If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details),
  1388. // it will be sent after the chunked response body.
  1389. //
  1390. // Use AddBytesV for setting multiple header values under the same key.
  1391. func (h *ResponseHeader) SetBytesV(key string, value []byte) {
  1392. h.bufK = getHeaderKeyBytes(h.bufK, key, h.disableNormalizing)
  1393. h.SetCanonical(h.bufK, value)
  1394. }
  1395. // SetBytesKV sets the given 'key: value' header.
  1396. //
  1397. // Please note that the Set-Cookie header will not clear previous cookies,
  1398. // use SetCookie instead to reset cookies.
  1399. //
  1400. // If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details),
  1401. // it will be sent after the chunked response body.
  1402. //
  1403. // Use AddBytesKV for setting multiple header values under the same key.
  1404. func (h *ResponseHeader) SetBytesKV(key, value []byte) {
  1405. h.bufK = append(h.bufK[:0], key...)
  1406. normalizeHeaderKey(h.bufK, h.disableNormalizing || bytes.IndexByte(key, ' ') != -1)
  1407. h.SetCanonical(h.bufK, value)
  1408. }
  1409. // SetCanonical sets the given 'key: value' header assuming that
  1410. // key is in canonical form.
  1411. //
  1412. // Please note that the Set-Cookie header will not clear previous cookies,
  1413. // use SetCookie instead to reset cookies.
  1414. //
  1415. // If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details),
  1416. // it will be sent after the chunked response body.
  1417. func (h *ResponseHeader) SetCanonical(key, value []byte) {
  1418. if h.setSpecialHeader(key, value) {
  1419. return
  1420. }
  1421. h.setNonSpecial(key, value)
  1422. }
  1423. // SetCookie sets the given response cookie.
  1424. //
  1425. // It is safe re-using the cookie after the function returns.
  1426. func (h *ResponseHeader) SetCookie(cookie *Cookie) {
  1427. h.cookies = setArgBytes(h.cookies, cookie.Key(), cookie.Cookie(), argsHasValue)
  1428. }
  1429. // SetCookie sets 'key: value' cookies.
  1430. func (h *RequestHeader) SetCookie(key, value string) {
  1431. h.collectCookies()
  1432. h.cookies = setArg(h.cookies, key, value, argsHasValue)
  1433. }
  1434. // SetCookieBytesK sets 'key: value' cookies.
  1435. func (h *RequestHeader) SetCookieBytesK(key []byte, value string) {
  1436. h.SetCookie(b2s(key), value)
  1437. }
  1438. // SetCookieBytesKV sets 'key: value' cookies.
  1439. func (h *RequestHeader) SetCookieBytesKV(key, value []byte) {
  1440. h.SetCookie(b2s(key), b2s(value))
  1441. }
  1442. // DelClientCookie instructs the client to remove the given cookie.
  1443. // This doesn't work for a cookie with specific domain or path,
  1444. // you should delete it manually like:
  1445. //
  1446. // c := AcquireCookie()
  1447. // c.SetKey(key)
  1448. // c.SetDomain("example.com")
  1449. // c.SetPath("/path")
  1450. // c.SetExpire(CookieExpireDelete)
  1451. // h.SetCookie(c)
  1452. // ReleaseCookie(c)
  1453. //
  1454. // Use DelCookie if you want just removing the cookie from response header.
  1455. func (h *ResponseHeader) DelClientCookie(key string) {
  1456. h.DelCookie(key)
  1457. c := AcquireCookie()
  1458. c.SetKey(key)
  1459. c.SetExpire(CookieExpireDelete)
  1460. h.SetCookie(c)
  1461. ReleaseCookie(c)
  1462. }
  1463. // DelClientCookieBytes instructs the client to remove the given cookie.
  1464. // This doesn't work for a cookie with specific domain or path,
  1465. // you should delete it manually like:
  1466. //
  1467. // c := AcquireCookie()
  1468. // c.SetKey(key)
  1469. // c.SetDomain("example.com")
  1470. // c.SetPath("/path")
  1471. // c.SetExpire(CookieExpireDelete)
  1472. // h.SetCookie(c)
  1473. // ReleaseCookie(c)
  1474. //
  1475. // Use DelCookieBytes if you want just removing the cookie from response header.
  1476. func (h *ResponseHeader) DelClientCookieBytes(key []byte) {
  1477. h.DelClientCookie(b2s(key))
  1478. }
  1479. // DelCookie removes cookie under the given key from response header.
  1480. //
  1481. // Note that DelCookie doesn't remove the cookie from the client.
  1482. // Use DelClientCookie instead.
  1483. func (h *ResponseHeader) DelCookie(key string) {
  1484. h.cookies = delAllArgs(h.cookies, key)
  1485. }
  1486. // DelCookieBytes removes cookie under the given key from response header.
  1487. //
  1488. // Note that DelCookieBytes doesn't remove the cookie from the client.
  1489. // Use DelClientCookieBytes instead.
  1490. func (h *ResponseHeader) DelCookieBytes(key []byte) {
  1491. h.DelCookie(b2s(key))
  1492. }
  1493. // DelCookie removes cookie under the given key.
  1494. func (h *RequestHeader) DelCookie(key string) {
  1495. h.collectCookies()
  1496. h.cookies = delAllArgs(h.cookies, key)
  1497. }
  1498. // DelCookieBytes removes cookie under the given key.
  1499. func (h *RequestHeader) DelCookieBytes(key []byte) {
  1500. h.DelCookie(b2s(key))
  1501. }
  1502. // DelAllCookies removes all the cookies from response headers.
  1503. func (h *ResponseHeader) DelAllCookies() {
  1504. h.cookies = h.cookies[:0]
  1505. }
  1506. // DelAllCookies removes all the cookies from request headers.
  1507. func (h *RequestHeader) DelAllCookies() {
  1508. h.collectCookies()
  1509. h.cookies = h.cookies[:0]
  1510. }
  1511. // Add adds the given 'key: value' header.
  1512. //
  1513. // Multiple headers with the same key may be added with this function.
  1514. // Use Set for setting a single header for the given key.
  1515. //
  1516. // If the header is set as a Trailer (forbidden trailers will not be set, see AddTrailer for more details),
  1517. // it will be sent after the chunked request body.
  1518. func (h *RequestHeader) Add(key, value string) {
  1519. h.AddBytesKV(s2b(key), s2b(value))
  1520. }
  1521. // AddBytesK adds the given 'key: value' header.
  1522. //
  1523. // Multiple headers with the same key may be added with this function.
  1524. // Use SetBytesK for setting a single header for the given key.
  1525. //
  1526. // If the header is set as a Trailer (forbidden trailers will not be set, see AddTrailer for more details),
  1527. // it will be sent after the chunked request body.
  1528. func (h *RequestHeader) AddBytesK(key []byte, value string) {
  1529. h.AddBytesKV(key, s2b(value))
  1530. }
  1531. // AddBytesV adds the given 'key: value' header.
  1532. //
  1533. // Multiple headers with the same key may be added with this function.
  1534. // Use SetBytesV for setting a single header for the given key.
  1535. //
  1536. // If the header is set as a Trailer (forbidden trailers will not be set, see AddTrailer for more details),
  1537. // it will be sent after the chunked request body.
  1538. func (h *RequestHeader) AddBytesV(key string, value []byte) {
  1539. h.AddBytesKV(s2b(key), value)
  1540. }
  1541. // AddBytesKV adds the given 'key: value' header.
  1542. //
  1543. // Multiple headers with the same key may be added with this function.
  1544. // Use SetBytesKV for setting a single header for the given key.
  1545. //
  1546. // the Content-Type, Content-Length, Connection, Transfer-Encoding,
  1547. // Host and User-Agent headers can only be set once and will overwrite
  1548. // the previous value, while the Cookie header will not clear previous cookies.
  1549. //
  1550. // If the header is set as a Trailer (forbidden trailers will not be set, see AddTrailer for more details),
  1551. // it will be sent after the chunked request body.
  1552. func (h *RequestHeader) AddBytesKV(key, value []byte) {
  1553. if h.setSpecialHeader(key, value) {
  1554. return
  1555. }
  1556. h.bufK = getHeaderKeyBytes(h.bufK, b2s(key), h.disableNormalizing)
  1557. h.h = appendArgBytes(h.h, h.bufK, value, argsHasValue)
  1558. }
  1559. // Set sets the given 'key: value' header.
  1560. //
  1561. // Please note that the Cookie header will not clear previous cookies,
  1562. // delete cookies before calling in order to reset cookies.
  1563. //
  1564. // If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details),
  1565. // it will be sent after the chunked request body.
  1566. //
  1567. // Use Add for setting multiple header values under the same key.
  1568. func (h *RequestHeader) Set(key, value string) {
  1569. h.bufK, h.bufV = initHeaderKV(h.bufK, h.bufV, key, value, h.disableNormalizing)
  1570. h.SetCanonical(h.bufK, h.bufV)
  1571. }
  1572. // SetBytesK sets the given 'key: value' header.
  1573. //
  1574. // Please note that the Cookie header will not clear previous cookies,
  1575. // delete cookies before calling in order to reset cookies.
  1576. //
  1577. // If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details),
  1578. // it will be sent after the chunked request body.
  1579. //
  1580. // Use AddBytesK for setting multiple header values under the same key.
  1581. func (h *RequestHeader) SetBytesK(key []byte, value string) {
  1582. h.bufV = append(h.bufV[:0], value...)
  1583. h.SetBytesKV(key, h.bufV)
  1584. }
  1585. // SetBytesV sets the given 'key: value' header.
  1586. //
  1587. // Please note that the Cookie header will not clear previous cookies,
  1588. // delete cookies before calling in order to reset cookies.
  1589. //
  1590. // If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details),
  1591. // it will be sent after the chunked request body.
  1592. //
  1593. // Use AddBytesV for setting multiple header values under the same key.
  1594. func (h *RequestHeader) SetBytesV(key string, value []byte) {
  1595. h.bufK = getHeaderKeyBytes(h.bufK, key, h.disableNormalizing)
  1596. h.SetCanonical(h.bufK, value)
  1597. }
  1598. // SetBytesKV sets the given 'key: value' header.
  1599. //
  1600. // Please note that the Cookie header will not clear previous cookies,
  1601. // delete cookies before calling in order to reset cookies.
  1602. //
  1603. // If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details),
  1604. // it will be sent after the chunked request body.
  1605. //
  1606. // Use AddBytesKV for setting multiple header values under the same key.
  1607. func (h *RequestHeader) SetBytesKV(key, value []byte) {
  1608. h.bufK = append(h.bufK[:0], key...)
  1609. normalizeHeaderKey(h.bufK, h.disableNormalizing || bytes.IndexByte(key, ' ') != -1)
  1610. h.SetCanonical(h.bufK, value)
  1611. }
  1612. // SetCanonical sets the given 'key: value' header assuming that
  1613. // key is in canonical form.
  1614. //
  1615. // Please note that the Cookie header will not clear previous cookies,
  1616. // delete cookies before calling in order to reset cookies.
  1617. //
  1618. // If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details),
  1619. // it will be sent after the chunked request body.
  1620. func (h *RequestHeader) SetCanonical(key, value []byte) {
  1621. if h.setSpecialHeader(key, value) {
  1622. return
  1623. }
  1624. h.setNonSpecial(key, value)
  1625. }
  1626. // Peek returns header value for the given key.
  1627. //
  1628. // The returned value is valid until the response is released,
  1629. // either though ReleaseResponse or your request handler returning.
  1630. // Do not store references to the returned value. Make copies instead.
  1631. func (h *ResponseHeader) Peek(key string) []byte {
  1632. h.bufK = getHeaderKeyBytes(h.bufK, key, h.disableNormalizing)
  1633. return h.peek(h.bufK)
  1634. }
  1635. // PeekBytes returns header value for the given key.
  1636. //
  1637. // The returned value is valid until the response is released,
  1638. // either though ReleaseResponse or your request handler returning.
  1639. // Do not store references to returned value. Make copies instead.
  1640. func (h *ResponseHeader) PeekBytes(key []byte) []byte {
  1641. h.bufK = append(h.bufK[:0], key...)
  1642. normalizeHeaderKey(h.bufK, h.disableNormalizing || bytes.IndexByte(key, ' ') != -1)
  1643. return h.peek(h.bufK)
  1644. }
  1645. // Peek returns header value for the given key.
  1646. //
  1647. // The returned value is valid until the request is released,
  1648. // either though ReleaseRequest or your request handler returning.
  1649. // Do not store references to returned value. Make copies instead.
  1650. func (h *RequestHeader) Peek(key string) []byte {
  1651. h.bufK = getHeaderKeyBytes(h.bufK, key, h.disableNormalizing)
  1652. return h.peek(h.bufK)
  1653. }
  1654. // PeekBytes returns header value for the given key.
  1655. //
  1656. // The returned value is valid until the request is released,
  1657. // either though ReleaseRequest or your request handler returning.
  1658. // Do not store references to returned value. Make copies instead.
  1659. func (h *RequestHeader) PeekBytes(key []byte) []byte {
  1660. h.bufK = append(h.bufK[:0], key...)
  1661. normalizeHeaderKey(h.bufK, h.disableNormalizing || bytes.IndexByte(key, ' ') != -1)
  1662. return h.peek(h.bufK)
  1663. }
  1664. func (h *ResponseHeader) peek(key []byte) []byte {
  1665. switch string(key) {
  1666. case HeaderContentType:
  1667. return h.ContentType()
  1668. case HeaderContentEncoding:
  1669. return h.ContentEncoding()
  1670. case HeaderServer:
  1671. return h.Server()
  1672. case HeaderConnection:
  1673. if h.ConnectionClose() {
  1674. return strClose
  1675. }
  1676. return peekArgBytes(h.h, key)
  1677. case HeaderContentLength:
  1678. return h.contentLengthBytes
  1679. case HeaderSetCookie:
  1680. return appendResponseCookieBytes(nil, h.cookies)
  1681. case HeaderTrailer:
  1682. return appendTrailerBytes(nil, h.trailer, strCommaSpace)
  1683. default:
  1684. return peekArgBytes(h.h, key)
  1685. }
  1686. }
  1687. func (h *RequestHeader) peek(key []byte) []byte {
  1688. switch string(key) {
  1689. case HeaderHost:
  1690. return h.Host()
  1691. case HeaderContentType:
  1692. return h.ContentType()
  1693. case HeaderUserAgent:
  1694. return h.UserAgent()
  1695. case HeaderConnection:
  1696. if h.ConnectionClose() {
  1697. return strClose
  1698. }
  1699. return peekArgBytes(h.h, key)
  1700. case HeaderContentLength:
  1701. return h.contentLengthBytes
  1702. case HeaderCookie:
  1703. if h.cookiesCollected {
  1704. return appendRequestCookieBytes(nil, h.cookies)
  1705. }
  1706. return peekArgBytes(h.h, key)
  1707. case HeaderTrailer:
  1708. return appendTrailerBytes(nil, h.trailer, strCommaSpace)
  1709. default:
  1710. return peekArgBytes(h.h, key)
  1711. }
  1712. }
  1713. // PeekAll returns all header value for the given key.
  1714. //
  1715. // The returned value is valid until the request is released,
  1716. // either though ReleaseRequest or your request handler returning.
  1717. // Any future calls to the Peek* will modify the returned value.
  1718. // Do not store references to returned value. Make copies instead.
  1719. func (h *RequestHeader) PeekAll(key string) [][]byte {
  1720. h.bufK = getHeaderKeyBytes(h.bufK, key, h.disableNormalizing)
  1721. return h.peekAll(h.bufK)
  1722. }
  1723. func (h *RequestHeader) peekAll(key []byte) [][]byte {
  1724. h.mulHeader = h.mulHeader[:0]
  1725. switch string(key) {
  1726. case HeaderHost:
  1727. if host := h.Host(); len(host) > 0 {
  1728. h.mulHeader = append(h.mulHeader, host)
  1729. }
  1730. case HeaderContentType:
  1731. if contentType := h.ContentType(); len(contentType) > 0 {
  1732. h.mulHeader = append(h.mulHeader, contentType)
  1733. }
  1734. case HeaderUserAgent:
  1735. if ua := h.UserAgent(); len(ua) > 0 {
  1736. h.mulHeader = append(h.mulHeader, ua)
  1737. }
  1738. case HeaderConnection:
  1739. if h.ConnectionClose() {
  1740. h.mulHeader = append(h.mulHeader, strClose)
  1741. } else {
  1742. h.mulHeader = peekAllArgBytesToDst(h.mulHeader, h.h, key)
  1743. }
  1744. case HeaderContentLength:
  1745. h.mulHeader = append(h.mulHeader, h.contentLengthBytes)
  1746. case HeaderCookie:
  1747. if h.cookiesCollected {
  1748. h.mulHeader = append(h.mulHeader, appendRequestCookieBytes(nil, h.cookies))
  1749. } else {
  1750. h.mulHeader = peekAllArgBytesToDst(h.mulHeader, h.h, key)
  1751. }
  1752. case HeaderTrailer:
  1753. h.mulHeader = append(h.mulHeader, appendTrailerBytes(nil, h.trailer, strCommaSpace))
  1754. default:
  1755. h.mulHeader = peekAllArgBytesToDst(h.mulHeader, h.h, key)
  1756. }
  1757. return h.mulHeader
  1758. }
  1759. // PeekAll returns all header value for the given key.
  1760. //
  1761. // The returned value is valid until the request is released,
  1762. // either though ReleaseResponse or your request handler returning.
  1763. // Any future calls to the Peek* will modify the returned value.
  1764. // Do not store references to returned value. Make copies instead.
  1765. func (h *ResponseHeader) PeekAll(key string) [][]byte {
  1766. h.bufK = getHeaderKeyBytes(h.bufK, key, h.disableNormalizing)
  1767. return h.peekAll(h.bufK)
  1768. }
  1769. func (h *ResponseHeader) peekAll(key []byte) [][]byte {
  1770. h.mulHeader = h.mulHeader[:0]
  1771. switch string(key) {
  1772. case HeaderContentType:
  1773. if contentType := h.ContentType(); len(contentType) > 0 {
  1774. h.mulHeader = append(h.mulHeader, contentType)
  1775. }
  1776. case HeaderContentEncoding:
  1777. if contentEncoding := h.ContentEncoding(); len(contentEncoding) > 0 {
  1778. h.mulHeader = append(h.mulHeader, contentEncoding)
  1779. }
  1780. case HeaderServer:
  1781. if server := h.Server(); len(server) > 0 {
  1782. h.mulHeader = append(h.mulHeader, server)
  1783. }
  1784. case HeaderConnection:
  1785. if h.ConnectionClose() {
  1786. h.mulHeader = append(h.mulHeader, strClose)
  1787. } else {
  1788. h.mulHeader = peekAllArgBytesToDst(h.mulHeader, h.h, key)
  1789. }
  1790. case HeaderContentLength:
  1791. h.mulHeader = append(h.mulHeader, h.contentLengthBytes)
  1792. case HeaderSetCookie:
  1793. h.mulHeader = append(h.mulHeader, appendResponseCookieBytes(nil, h.cookies))
  1794. case HeaderTrailer:
  1795. h.mulHeader = append(h.mulHeader, appendTrailerBytes(nil, h.trailer, strCommaSpace))
  1796. default:
  1797. h.mulHeader = peekAllArgBytesToDst(h.mulHeader, h.h, key)
  1798. }
  1799. return h.mulHeader
  1800. }
  1801. // PeekKeys return all header keys.
  1802. //
  1803. // The returned value is valid until the request is released,
  1804. // either though ReleaseRequest or your request handler returning.
  1805. // Any future calls to the Peek* will modify the returned value.
  1806. // Do not store references to returned value. Make copies instead.
  1807. func (h *RequestHeader) PeekKeys() [][]byte {
  1808. h.mulHeader = h.mulHeader[:0]
  1809. h.mulHeader = peekArgsKeys(h.mulHeader, h.h)
  1810. return h.mulHeader
  1811. }
  1812. // PeekTrailerKeys return all trailer keys.
  1813. //
  1814. // The returned value is valid until the request is released,
  1815. // either though ReleaseRequest or your request handler returning.
  1816. // Any future calls to the Peek* will modify the returned value.
  1817. // Do not store references to returned value. Make copies instead.
  1818. func (h *RequestHeader) PeekTrailerKeys() [][]byte {
  1819. h.mulHeader = copyTrailer(h.mulHeader, h.trailer)
  1820. return h.mulHeader
  1821. }
  1822. // PeekKeys return all header keys.
  1823. //
  1824. // The returned value is valid until the request is released,
  1825. // either though ReleaseResponse or your request handler returning.
  1826. // Any future calls to the Peek* will modify the returned value.
  1827. // Do not store references to returned value. Make copies instead.
  1828. func (h *ResponseHeader) PeekKeys() [][]byte {
  1829. h.mulHeader = h.mulHeader[:0]
  1830. h.mulHeader = peekArgsKeys(h.mulHeader, h.h)
  1831. return h.mulHeader
  1832. }
  1833. // PeekTrailerKeys return all trailer keys.
  1834. //
  1835. // The returned value is valid until the request is released,
  1836. // either though ReleaseResponse or your request handler returning.
  1837. // Any future calls to the Peek* will modify the returned value.
  1838. // Do not store references to returned value. Make copies instead.
  1839. func (h *ResponseHeader) PeekTrailerKeys() [][]byte {
  1840. h.mulHeader = h.mulHeader[:0]
  1841. for i, n := 0, len(h.trailer); i < n; i++ {
  1842. h.mulHeader = append(h.mulHeader, h.trailer[i])
  1843. }
  1844. return h.mulHeader
  1845. }
  1846. // Cookie returns cookie for the given key.
  1847. func (h *RequestHeader) Cookie(key string) []byte {
  1848. h.collectCookies()
  1849. return peekArgStr(h.cookies, key)
  1850. }
  1851. // CookieBytes returns cookie for the given key.
  1852. func (h *RequestHeader) CookieBytes(key []byte) []byte {
  1853. h.collectCookies()
  1854. return peekArgBytes(h.cookies, key)
  1855. }
  1856. // Cookie fills cookie for the given cookie.Key.
  1857. //
  1858. // Returns false if cookie with the given cookie.Key is missing.
  1859. func (h *ResponseHeader) Cookie(cookie *Cookie) bool {
  1860. v := peekArgBytes(h.cookies, cookie.Key())
  1861. if v == nil {
  1862. return false
  1863. }
  1864. cookie.ParseBytes(v) //nolint:errcheck
  1865. return true
  1866. }
  1867. // Read reads response header from r.
  1868. //
  1869. // io.EOF is returned if r is closed before reading the first header byte.
  1870. func (h *ResponseHeader) Read(r *bufio.Reader) error {
  1871. n := 1
  1872. for {
  1873. err := h.tryRead(r, n)
  1874. if err == nil {
  1875. return nil
  1876. }
  1877. if err != errNeedMore {
  1878. h.resetSkipNormalize()
  1879. return err
  1880. }
  1881. n = r.Buffered() + 1
  1882. }
  1883. }
  1884. func (h *ResponseHeader) tryRead(r *bufio.Reader, n int) error {
  1885. h.resetSkipNormalize()
  1886. b, err := r.Peek(n)
  1887. if len(b) == 0 {
  1888. // Return ErrTimeout on any timeout.
  1889. if x, ok := err.(interface{ Timeout() bool }); ok && x.Timeout() {
  1890. return ErrTimeout
  1891. }
  1892. // treat all other errors on the first byte read as EOF
  1893. if n == 1 || err == io.EOF {
  1894. return io.EOF
  1895. }
  1896. // This is for go 1.6 bug. See https://github.com/golang/go/issues/14121 .
  1897. if err == bufio.ErrBufferFull {
  1898. if h.secureErrorLogMessage {
  1899. return &ErrSmallBuffer{
  1900. error: errors.New("error when reading response headers"),
  1901. }
  1902. }
  1903. return &ErrSmallBuffer{
  1904. error: fmt.Errorf("error when reading response headers: %w", errSmallBuffer),
  1905. }
  1906. }
  1907. return fmt.Errorf("error when reading response headers: %w", err)
  1908. }
  1909. b = mustPeekBuffered(r)
  1910. headersLen, errParse := h.parse(b)
  1911. if errParse != nil {
  1912. return headerError("response", err, errParse, b, h.secureErrorLogMessage)
  1913. }
  1914. mustDiscard(r, headersLen)
  1915. return nil
  1916. }
  1917. // ReadTrailer reads response trailer header from r.
  1918. //
  1919. // io.EOF is returned if r is closed before reading the first byte.
  1920. func (h *ResponseHeader) ReadTrailer(r *bufio.Reader) error {
  1921. n := 1
  1922. for {
  1923. err := h.tryReadTrailer(r, n)
  1924. if err == nil {
  1925. return nil
  1926. }
  1927. if err != errNeedMore {
  1928. return err
  1929. }
  1930. n = r.Buffered() + 1
  1931. }
  1932. }
  1933. func (h *ResponseHeader) tryReadTrailer(r *bufio.Reader, n int) error {
  1934. b, err := r.Peek(n)
  1935. if len(b) == 0 {
  1936. // Return ErrTimeout on any timeout.
  1937. if x, ok := err.(interface{ Timeout() bool }); ok && x.Timeout() {
  1938. return ErrTimeout
  1939. }
  1940. if n == 1 || err == io.EOF {
  1941. return io.EOF
  1942. }
  1943. // This is for go 1.6 bug. See https://github.com/golang/go/issues/14121 .
  1944. if err == bufio.ErrBufferFull {
  1945. if h.secureErrorLogMessage {
  1946. return &ErrSmallBuffer{
  1947. error: errors.New("error when reading response trailer"),
  1948. }
  1949. }
  1950. return &ErrSmallBuffer{
  1951. error: fmt.Errorf("error when reading response trailer: %w", errSmallBuffer),
  1952. }
  1953. }
  1954. return fmt.Errorf("error when reading response trailer: %w", err)
  1955. }
  1956. b = mustPeekBuffered(r)
  1957. trailers, headersLen, errParse := parseTrailer(b, h.h, h.disableNormalizing)
  1958. h.h = trailers
  1959. if errParse != nil {
  1960. if err == io.EOF {
  1961. return err
  1962. }
  1963. return headerError("response", err, errParse, b, h.secureErrorLogMessage)
  1964. }
  1965. mustDiscard(r, headersLen)
  1966. return nil
  1967. }
  1968. func headerError(typ string, err, errParse error, b []byte, secureErrorLogMessage bool) error {
  1969. if errParse != errNeedMore {
  1970. return headerErrorMsg(typ, errParse, b, secureErrorLogMessage)
  1971. }
  1972. if err == nil {
  1973. return errNeedMore
  1974. }
  1975. // Buggy servers may leave trailing CRLFs after http body.
  1976. // Treat this case as EOF.
  1977. if isOnlyCRLF(b) {
  1978. return io.EOF
  1979. }
  1980. if err != bufio.ErrBufferFull {
  1981. return headerErrorMsg(typ, err, b, secureErrorLogMessage)
  1982. }
  1983. return &ErrSmallBuffer{
  1984. error: headerErrorMsg(typ, errSmallBuffer, b, secureErrorLogMessage),
  1985. }
  1986. }
  1987. func headerErrorMsg(typ string, err error, b []byte, secureErrorLogMessage bool) error {
  1988. if secureErrorLogMessage {
  1989. return fmt.Errorf("error when reading %s headers: %w. Buffer size=%d", typ, err, len(b))
  1990. }
  1991. return fmt.Errorf("error when reading %s headers: %w. Buffer size=%d, contents: %s", typ, err, len(b), bufferSnippet(b))
  1992. }
  1993. // Read reads request header from r.
  1994. //
  1995. // io.EOF is returned if r is closed before reading the first header byte.
  1996. func (h *RequestHeader) Read(r *bufio.Reader) error {
  1997. return h.readLoop(r, true)
  1998. }
  1999. // readLoop reads request header from r optionally loops until it has enough data.
  2000. //
  2001. // io.EOF is returned if r is closed before reading the first header byte.
  2002. func (h *RequestHeader) readLoop(r *bufio.Reader, waitForMore bool) error {
  2003. n := 1
  2004. for {
  2005. err := h.tryRead(r, n)
  2006. if err == nil {
  2007. return nil
  2008. }
  2009. if !waitForMore || err != errNeedMore {
  2010. h.resetSkipNormalize()
  2011. return err
  2012. }
  2013. n = r.Buffered() + 1
  2014. }
  2015. }
  2016. // ReadTrailer reads request trailer header from r.
  2017. //
  2018. // io.EOF is returned if r is closed before reading the first byte.
  2019. func (h *RequestHeader) ReadTrailer(r *bufio.Reader) error {
  2020. n := 1
  2021. for {
  2022. err := h.tryReadTrailer(r, n)
  2023. if err == nil {
  2024. return nil
  2025. }
  2026. if err != errNeedMore {
  2027. return err
  2028. }
  2029. n = r.Buffered() + 1
  2030. }
  2031. }
  2032. func (h *RequestHeader) tryReadTrailer(r *bufio.Reader, n int) error {
  2033. b, err := r.Peek(n)
  2034. if len(b) == 0 {
  2035. // Return ErrTimeout on any timeout.
  2036. if x, ok := err.(interface{ Timeout() bool }); ok && x.Timeout() {
  2037. return ErrTimeout
  2038. }
  2039. if n == 1 || err == io.EOF {
  2040. return io.EOF
  2041. }
  2042. // This is for go 1.6 bug. See https://github.com/golang/go/issues/14121 .
  2043. if err == bufio.ErrBufferFull {
  2044. if h.secureErrorLogMessage {
  2045. return &ErrSmallBuffer{
  2046. error: errors.New("error when reading request trailer"),
  2047. }
  2048. }
  2049. return &ErrSmallBuffer{
  2050. error: fmt.Errorf("error when reading request trailer: %w", errSmallBuffer),
  2051. }
  2052. }
  2053. return fmt.Errorf("error when reading request trailer: %w", err)
  2054. }
  2055. b = mustPeekBuffered(r)
  2056. trailers, headersLen, errParse := parseTrailer(b, h.h, h.disableNormalizing)
  2057. h.h = trailers
  2058. if errParse != nil {
  2059. if err == io.EOF {
  2060. return err
  2061. }
  2062. return headerError("request", err, errParse, b, h.secureErrorLogMessage)
  2063. }
  2064. mustDiscard(r, headersLen)
  2065. return nil
  2066. }
  2067. func (h *RequestHeader) tryRead(r *bufio.Reader, n int) error {
  2068. h.resetSkipNormalize()
  2069. b, err := r.Peek(n)
  2070. if len(b) == 0 {
  2071. if err == io.EOF {
  2072. return err
  2073. }
  2074. if err == nil {
  2075. panic("bufio.Reader.Peek() returned nil, nil")
  2076. }
  2077. // This is for go 1.6 bug. See https://github.com/golang/go/issues/14121 .
  2078. if err == bufio.ErrBufferFull {
  2079. return &ErrSmallBuffer{
  2080. error: fmt.Errorf("error when reading request headers: %w (n=%d, r.Buffered()=%d)", errSmallBuffer, n, r.Buffered()),
  2081. }
  2082. }
  2083. // n == 1 on the first read for the request.
  2084. if n == 1 {
  2085. // We didn't read a single byte.
  2086. return ErrNothingRead{error: err}
  2087. }
  2088. return fmt.Errorf("error when reading request headers: %w", err)
  2089. }
  2090. b = mustPeekBuffered(r)
  2091. headersLen, errParse := h.parse(b)
  2092. if errParse != nil {
  2093. return headerError("request", err, errParse, b, h.secureErrorLogMessage)
  2094. }
  2095. mustDiscard(r, headersLen)
  2096. return nil
  2097. }
  2098. func bufferSnippet(b []byte) string {
  2099. n := len(b)
  2100. start := 200
  2101. end := n - start
  2102. if start >= end {
  2103. start = n
  2104. end = n
  2105. }
  2106. bStart, bEnd := b[:start], b[end:]
  2107. if len(bEnd) == 0 {
  2108. return fmt.Sprintf("%q", b)
  2109. }
  2110. return fmt.Sprintf("%q...%q", bStart, bEnd)
  2111. }
  2112. func isOnlyCRLF(b []byte) bool {
  2113. for _, ch := range b {
  2114. if ch != rChar && ch != nChar {
  2115. return false
  2116. }
  2117. }
  2118. return true
  2119. }
  2120. func updateServerDate() {
  2121. refreshServerDate()
  2122. go func() {
  2123. for {
  2124. time.Sleep(time.Second)
  2125. refreshServerDate()
  2126. }
  2127. }()
  2128. }
  2129. var (
  2130. serverDate atomic.Value
  2131. serverDateOnce sync.Once // serverDateOnce.Do(updateServerDate)
  2132. )
  2133. func refreshServerDate() {
  2134. b := AppendHTTPDate(nil, time.Now())
  2135. serverDate.Store(b)
  2136. }
  2137. // Write writes response header to w.
  2138. func (h *ResponseHeader) Write(w *bufio.Writer) error {
  2139. _, err := w.Write(h.Header())
  2140. return err
  2141. }
  2142. // WriteTo writes response header to w.
  2143. //
  2144. // WriteTo implements io.WriterTo interface.
  2145. func (h *ResponseHeader) WriteTo(w io.Writer) (int64, error) {
  2146. n, err := w.Write(h.Header())
  2147. return int64(n), err
  2148. }
  2149. // Header returns response header representation.
  2150. //
  2151. // Headers that set as Trailer will not represent. Use TrailerHeader for trailers.
  2152. //
  2153. // The returned value is valid until the request is released,
  2154. // either though ReleaseRequest or your request handler returning.
  2155. // Do not store references to returned value. Make copies instead.
  2156. func (h *ResponseHeader) Header() []byte {
  2157. h.bufV = h.AppendBytes(h.bufV[:0])
  2158. return h.bufV
  2159. }
  2160. // writeTrailer writes response trailer to w.
  2161. func (h *ResponseHeader) writeTrailer(w *bufio.Writer) error {
  2162. _, err := w.Write(h.TrailerHeader())
  2163. return err
  2164. }
  2165. // TrailerHeader returns response trailer header representation.
  2166. //
  2167. // Trailers will only be received with chunked transfer.
  2168. //
  2169. // The returned value is valid until the request is released,
  2170. // either though ReleaseRequest or your request handler returning.
  2171. // Do not store references to returned value. Make copies instead.
  2172. func (h *ResponseHeader) TrailerHeader() []byte {
  2173. h.bufV = h.bufV[:0]
  2174. for _, t := range h.trailer {
  2175. value := h.peek(t)
  2176. h.bufV = appendHeaderLine(h.bufV, t, value)
  2177. }
  2178. h.bufV = append(h.bufV, strCRLF...)
  2179. return h.bufV
  2180. }
  2181. // String returns response header representation.
  2182. func (h *ResponseHeader) String() string {
  2183. return string(h.Header())
  2184. }
  2185. // appendStatusLine appends the response status line to dst and returns
  2186. // the extended dst.
  2187. func (h *ResponseHeader) appendStatusLine(dst []byte) []byte {
  2188. statusCode := h.StatusCode()
  2189. if statusCode < 0 {
  2190. statusCode = StatusOK
  2191. }
  2192. return formatStatusLine(dst, h.Protocol(), statusCode, h.StatusMessage())
  2193. }
  2194. // AppendBytes appends response header representation to dst and returns
  2195. // the extended dst.
  2196. func (h *ResponseHeader) AppendBytes(dst []byte) []byte {
  2197. dst = h.appendStatusLine(dst[:0])
  2198. server := h.Server()
  2199. if len(server) != 0 {
  2200. dst = appendHeaderLine(dst, strServer, server)
  2201. }
  2202. if !h.noDefaultDate {
  2203. serverDateOnce.Do(updateServerDate)
  2204. dst = appendHeaderLine(dst, strDate, serverDate.Load().([]byte))
  2205. }
  2206. // Append Content-Type only for non-zero responses
  2207. // or if it is explicitly set.
  2208. // See https://github.com/valyala/fasthttp/issues/28 .
  2209. if h.ContentLength() != 0 || len(h.contentType) > 0 {
  2210. contentType := h.ContentType()
  2211. if len(contentType) > 0 {
  2212. dst = appendHeaderLine(dst, strContentType, contentType)
  2213. }
  2214. }
  2215. contentEncoding := h.ContentEncoding()
  2216. if len(contentEncoding) > 0 {
  2217. dst = appendHeaderLine(dst, strContentEncoding, contentEncoding)
  2218. }
  2219. if len(h.contentLengthBytes) > 0 {
  2220. dst = appendHeaderLine(dst, strContentLength, h.contentLengthBytes)
  2221. }
  2222. for i, n := 0, len(h.h); i < n; i++ {
  2223. kv := &h.h[i]
  2224. // Exclude trailer from header
  2225. exclude := false
  2226. for _, t := range h.trailer {
  2227. if bytes.Equal(kv.key, t) {
  2228. exclude = true
  2229. break
  2230. }
  2231. }
  2232. if !exclude && (h.noDefaultDate || !bytes.Equal(kv.key, strDate)) {
  2233. dst = appendHeaderLine(dst, kv.key, kv.value)
  2234. }
  2235. }
  2236. if len(h.trailer) > 0 {
  2237. dst = appendHeaderLine(dst, strTrailer, appendTrailerBytes(nil, h.trailer, strCommaSpace))
  2238. }
  2239. n := len(h.cookies)
  2240. if n > 0 {
  2241. for i := 0; i < n; i++ {
  2242. kv := &h.cookies[i]
  2243. dst = appendHeaderLine(dst, strSetCookie, kv.value)
  2244. }
  2245. }
  2246. if h.ConnectionClose() {
  2247. dst = appendHeaderLine(dst, strConnection, strClose)
  2248. }
  2249. return append(dst, strCRLF...)
  2250. }
  2251. // Write writes request header to w.
  2252. func (h *RequestHeader) Write(w *bufio.Writer) error {
  2253. _, err := w.Write(h.Header())
  2254. return err
  2255. }
  2256. // WriteTo writes request header to w.
  2257. //
  2258. // WriteTo implements io.WriterTo interface.
  2259. func (h *RequestHeader) WriteTo(w io.Writer) (int64, error) {
  2260. n, err := w.Write(h.Header())
  2261. return int64(n), err
  2262. }
  2263. // Header returns request header representation.
  2264. //
  2265. // Headers that set as Trailer will not represent. Use TrailerHeader for trailers.
  2266. //
  2267. // The returned value is valid until the request is released,
  2268. // either though ReleaseRequest or your request handler returning.
  2269. // Do not store references to returned value. Make copies instead.
  2270. func (h *RequestHeader) Header() []byte {
  2271. h.bufV = h.AppendBytes(h.bufV[:0])
  2272. return h.bufV
  2273. }
  2274. // writeTrailer writes request trailer to w.
  2275. func (h *RequestHeader) writeTrailer(w *bufio.Writer) error {
  2276. _, err := w.Write(h.TrailerHeader())
  2277. return err
  2278. }
  2279. // TrailerHeader returns request trailer header representation.
  2280. //
  2281. // Trailers will only be received with chunked transfer.
  2282. //
  2283. // The returned value is valid until the request is released,
  2284. // either though ReleaseRequest or your request handler returning.
  2285. // Do not store references to returned value. Make copies instead.
  2286. func (h *RequestHeader) TrailerHeader() []byte {
  2287. h.bufV = h.bufV[:0]
  2288. for _, t := range h.trailer {
  2289. value := h.peek(t)
  2290. h.bufV = appendHeaderLine(h.bufV, t, value)
  2291. }
  2292. h.bufV = append(h.bufV, strCRLF...)
  2293. return h.bufV
  2294. }
  2295. // RawHeaders returns raw header key/value bytes.
  2296. //
  2297. // Depending on server configuration, header keys may be normalized to
  2298. // capital-case in place.
  2299. //
  2300. // This copy is set aside during parsing, so empty slice is returned for all
  2301. // cases where parsing did not happen. Similarly, request line is not stored
  2302. // during parsing and can not be returned.
  2303. //
  2304. // The slice is not safe to use after the handler returns.
  2305. func (h *RequestHeader) RawHeaders() []byte {
  2306. return h.rawHeaders
  2307. }
  2308. // String returns request header representation.
  2309. func (h *RequestHeader) String() string {
  2310. return string(h.Header())
  2311. }
  2312. // AppendBytes appends request header representation to dst and returns
  2313. // the extended dst.
  2314. func (h *RequestHeader) AppendBytes(dst []byte) []byte {
  2315. dst = append(dst, h.Method()...)
  2316. dst = append(dst, ' ')
  2317. dst = append(dst, h.RequestURI()...)
  2318. dst = append(dst, ' ')
  2319. dst = append(dst, h.Protocol()...)
  2320. dst = append(dst, strCRLF...)
  2321. userAgent := h.UserAgent()
  2322. if len(userAgent) > 0 && !h.disableSpecialHeader {
  2323. dst = appendHeaderLine(dst, strUserAgent, userAgent)
  2324. }
  2325. host := h.Host()
  2326. if len(host) > 0 && !h.disableSpecialHeader {
  2327. dst = appendHeaderLine(dst, strHost, host)
  2328. }
  2329. contentType := h.ContentType()
  2330. if !h.noDefaultContentType && len(contentType) == 0 && !h.ignoreBody() {
  2331. contentType = strDefaultContentType
  2332. }
  2333. if len(contentType) > 0 && !h.disableSpecialHeader {
  2334. dst = appendHeaderLine(dst, strContentType, contentType)
  2335. }
  2336. if len(h.contentLengthBytes) > 0 && !h.disableSpecialHeader {
  2337. dst = appendHeaderLine(dst, strContentLength, h.contentLengthBytes)
  2338. }
  2339. for i, n := 0, len(h.h); i < n; i++ {
  2340. kv := &h.h[i]
  2341. // Exclude trailer from header
  2342. exclude := false
  2343. for _, t := range h.trailer {
  2344. if bytes.Equal(kv.key, t) {
  2345. exclude = true
  2346. break
  2347. }
  2348. }
  2349. if !exclude {
  2350. dst = appendHeaderLine(dst, kv.key, kv.value)
  2351. }
  2352. }
  2353. if len(h.trailer) > 0 {
  2354. dst = appendHeaderLine(dst, strTrailer, appendTrailerBytes(nil, h.trailer, strCommaSpace))
  2355. }
  2356. // there is no need in h.collectCookies() here, since if cookies aren't collected yet,
  2357. // they all are located in h.h.
  2358. n := len(h.cookies)
  2359. if n > 0 && !h.disableSpecialHeader {
  2360. dst = append(dst, strCookie...)
  2361. dst = append(dst, strColonSpace...)
  2362. dst = appendRequestCookieBytes(dst, h.cookies)
  2363. dst = append(dst, strCRLF...)
  2364. }
  2365. if h.ConnectionClose() && !h.disableSpecialHeader {
  2366. dst = appendHeaderLine(dst, strConnection, strClose)
  2367. }
  2368. return append(dst, strCRLF...)
  2369. }
  2370. func appendHeaderLine(dst, key, value []byte) []byte {
  2371. dst = append(dst, key...)
  2372. dst = append(dst, strColonSpace...)
  2373. dst = append(dst, value...)
  2374. return append(dst, strCRLF...)
  2375. }
  2376. func (h *ResponseHeader) parse(buf []byte) (int, error) {
  2377. m, err := h.parseFirstLine(buf)
  2378. if err != nil {
  2379. return 0, err
  2380. }
  2381. n, err := h.parseHeaders(buf[m:])
  2382. if err != nil {
  2383. return 0, err
  2384. }
  2385. return m + n, nil
  2386. }
  2387. func (h *RequestHeader) ignoreBody() bool {
  2388. return h.IsGet() || h.IsHead()
  2389. }
  2390. func (h *RequestHeader) parse(buf []byte) (int, error) {
  2391. m, err := h.parseFirstLine(buf)
  2392. if err != nil {
  2393. return 0, err
  2394. }
  2395. h.rawHeaders, _, err = readRawHeaders(h.rawHeaders[:0], buf[m:])
  2396. if err != nil {
  2397. return 0, err
  2398. }
  2399. var n int
  2400. n, err = h.parseHeaders(buf[m:])
  2401. if err != nil {
  2402. return 0, err
  2403. }
  2404. return m + n, nil
  2405. }
  2406. func addTrailerBytes(src, buf []byte, trailers [][]byte, disableNormalizing bool) ([]byte, [][]byte, error) {
  2407. var err error
  2408. for i := -1; i+1 < len(src); {
  2409. src = src[i+1:]
  2410. i = bytes.IndexByte(src, ',')
  2411. if i < 0 {
  2412. i = len(src)
  2413. }
  2414. key := src[:i]
  2415. for len(key) > 0 && key[0] == ' ' {
  2416. key = key[1:]
  2417. }
  2418. for len(key) > 0 && key[len(key)-1] == ' ' {
  2419. key = key[:len(key)-1]
  2420. }
  2421. // Forbidden by RFC 7230, section 4.1.2
  2422. if isBadTrailer(key) {
  2423. err = ErrBadTrailer
  2424. continue
  2425. }
  2426. buf = append(buf[:0], key...)
  2427. normalizeHeaderKey(buf, disableNormalizing || bytes.IndexByte(buf, ' ') != -1)
  2428. if cap(trailers) > len(trailers) {
  2429. trailers = trailers[:len(trailers)+1]
  2430. trailers[len(trailers)-1] = append(trailers[len(trailers)-1][:0], buf...)
  2431. } else {
  2432. key = make([]byte, len(buf))
  2433. copy(key, buf)
  2434. trailers = append(trailers, key)
  2435. }
  2436. }
  2437. return buf, trailers, err
  2438. }
  2439. func parseTrailer(src []byte, dest []argsKV, disableNormalizing bool) ([]argsKV, int, error) {
  2440. // Skip any 0 length chunk.
  2441. if src[0] == '0' {
  2442. skip := len(strCRLF) + 1
  2443. if len(src) < skip {
  2444. return dest, 0, io.EOF
  2445. }
  2446. src = src[skip:]
  2447. }
  2448. var s headerScanner
  2449. s.b = src
  2450. for s.next() {
  2451. if len(s.key) == 0 {
  2452. continue
  2453. }
  2454. disable := disableNormalizing
  2455. for _, ch := range s.key {
  2456. if !validHeaderFieldByte(ch) {
  2457. // We accept invalid headers with a space before the
  2458. // colon, but must not canonicalize them.
  2459. // See: https://github.com/valyala/fasthttp/issues/1917
  2460. if ch == ' ' {
  2461. disable = true
  2462. continue
  2463. }
  2464. return dest, 0, fmt.Errorf("invalid trailer key %q", s.key)
  2465. }
  2466. }
  2467. // Forbidden by RFC 7230, section 4.1.2
  2468. if isBadTrailer(s.key) {
  2469. return dest, 0, fmt.Errorf("forbidden trailer key %q", s.key)
  2470. }
  2471. normalizeHeaderKey(s.key, disable)
  2472. dest = appendArgBytes(dest, s.key, s.value, argsHasValue)
  2473. }
  2474. if s.err != nil {
  2475. return dest, 0, s.err
  2476. }
  2477. return dest, s.hLen, nil
  2478. }
  2479. func isBadTrailer(key []byte) bool {
  2480. if len(key) == 0 {
  2481. return true
  2482. }
  2483. switch key[0] | 0x20 {
  2484. case 'a':
  2485. return caseInsensitiveCompare(key, strAuthorization)
  2486. case 'c':
  2487. if len(key) > len(HeaderContentType) && caseInsensitiveCompare(key[:8], strContentType[:8]) {
  2488. // skip compare prefix 'Content-'
  2489. return caseInsensitiveCompare(key[8:], strContentEncoding[8:]) ||
  2490. caseInsensitiveCompare(key[8:], strContentLength[8:]) ||
  2491. caseInsensitiveCompare(key[8:], strContentType[8:]) ||
  2492. caseInsensitiveCompare(key[8:], strContentRange[8:])
  2493. }
  2494. return caseInsensitiveCompare(key, strConnection)
  2495. case 'e':
  2496. return caseInsensitiveCompare(key, strExpect)
  2497. case 'h':
  2498. return caseInsensitiveCompare(key, strHost)
  2499. case 'k':
  2500. return caseInsensitiveCompare(key, strKeepAlive)
  2501. case 'm':
  2502. return caseInsensitiveCompare(key, strMaxForwards)
  2503. case 'p':
  2504. if len(key) > len(HeaderProxyConnection) && caseInsensitiveCompare(key[:6], strProxyConnection[:6]) {
  2505. // skip compare prefix 'Proxy-'
  2506. return caseInsensitiveCompare(key[6:], strProxyConnection[6:]) ||
  2507. caseInsensitiveCompare(key[6:], strProxyAuthenticate[6:]) ||
  2508. caseInsensitiveCompare(key[6:], strProxyAuthorization[6:])
  2509. }
  2510. case 'r':
  2511. return caseInsensitiveCompare(key, strRange)
  2512. case 't':
  2513. return caseInsensitiveCompare(key, strTE) ||
  2514. caseInsensitiveCompare(key, strTrailer) ||
  2515. caseInsensitiveCompare(key, strTransferEncoding)
  2516. case 'w':
  2517. return caseInsensitiveCompare(key, strWWWAuthenticate)
  2518. }
  2519. return false
  2520. }
  2521. func (h *ResponseHeader) parseFirstLine(buf []byte) (int, error) {
  2522. bNext := buf
  2523. var b []byte
  2524. var err error
  2525. for len(b) == 0 {
  2526. if b, bNext, err = nextLine(bNext); err != nil {
  2527. return 0, err
  2528. }
  2529. }
  2530. // parse protocol
  2531. n := bytes.IndexByte(b, ' ')
  2532. if n < 0 {
  2533. if h.secureErrorLogMessage {
  2534. return 0, errors.New("cannot find whitespace in the first line of response")
  2535. }
  2536. return 0, fmt.Errorf("cannot find whitespace in the first line of response %q", buf)
  2537. }
  2538. h.noHTTP11 = !bytes.Equal(b[:n], strHTTP11)
  2539. b = b[n+1:]
  2540. // parse status code
  2541. h.statusCode, n, err = parseUintBuf(b)
  2542. if err != nil {
  2543. if h.secureErrorLogMessage {
  2544. return 0, fmt.Errorf("cannot parse response status code: %w", err)
  2545. }
  2546. return 0, fmt.Errorf("cannot parse response status code: %w. Response %q", err, buf)
  2547. }
  2548. if len(b) > n && b[n] != ' ' {
  2549. if h.secureErrorLogMessage {
  2550. return 0, errors.New("unexpected char at the end of status code")
  2551. }
  2552. return 0, fmt.Errorf("unexpected char at the end of status code. Response %q", buf)
  2553. }
  2554. if len(b) > n+1 {
  2555. h.SetStatusMessage(b[n+1:])
  2556. }
  2557. return len(buf) - len(bNext), nil
  2558. }
  2559. func isValidMethod(method []byte) bool {
  2560. for _, ch := range method {
  2561. if validMethodValueByteTable[ch] == 0 {
  2562. return false
  2563. }
  2564. }
  2565. return true
  2566. }
  2567. func (h *RequestHeader) parseFirstLine(buf []byte) (int, error) {
  2568. bNext := buf
  2569. var b []byte
  2570. var err error
  2571. for len(b) == 0 {
  2572. if b, bNext, err = nextLine(bNext); err != nil {
  2573. return 0, err
  2574. }
  2575. }
  2576. // parse method
  2577. n := bytes.IndexByte(b, ' ')
  2578. if n <= 0 {
  2579. if h.secureErrorLogMessage {
  2580. return 0, errors.New("cannot find http request method")
  2581. }
  2582. return 0, fmt.Errorf("cannot find http request method in %q", buf)
  2583. }
  2584. h.method = append(h.method[:0], b[:n]...)
  2585. if !isValidMethod(h.method) {
  2586. if h.secureErrorLogMessage {
  2587. return 0, errors.New("unsupported http request method")
  2588. }
  2589. return 0, fmt.Errorf("unsupported http request method %q in %q", h.method, buf)
  2590. }
  2591. b = b[n+1:]
  2592. // parse requestURI
  2593. n = bytes.LastIndexByte(b, ' ')
  2594. if n < 0 {
  2595. return 0, fmt.Errorf("cannot find whitespace in the first line of request %q", buf)
  2596. } else if n == 0 {
  2597. if h.secureErrorLogMessage {
  2598. return 0, errors.New("requestURI cannot be empty")
  2599. }
  2600. return 0, fmt.Errorf("requestURI cannot be empty in %q", buf)
  2601. }
  2602. protoStr := b[n+1:]
  2603. // Follow RFCs 7230 and 9112 and require that HTTP versions match the following pattern: HTTP/[0-9]\.[0-9]
  2604. if len(protoStr) != len(strHTTP11) {
  2605. if h.secureErrorLogMessage {
  2606. return 0, fmt.Errorf("unsupported HTTP version %q", protoStr)
  2607. }
  2608. return 0, fmt.Errorf("unsupported HTTP version %q in %q", protoStr, buf)
  2609. }
  2610. if !bytes.HasPrefix(protoStr, strHTTP11[:5]) {
  2611. if h.secureErrorLogMessage {
  2612. return 0, fmt.Errorf("unsupported HTTP version %q", protoStr)
  2613. }
  2614. return 0, fmt.Errorf("unsupported HTTP version %q in %q", protoStr, buf)
  2615. }
  2616. if protoStr[5] < '0' || protoStr[5] > '9' || protoStr[7] < '0' || protoStr[7] > '9' {
  2617. if h.secureErrorLogMessage {
  2618. return 0, fmt.Errorf("unsupported HTTP version %q", protoStr)
  2619. }
  2620. return 0, fmt.Errorf("unsupported HTTP version %q in %q", protoStr, buf)
  2621. }
  2622. h.noHTTP11 = !bytes.Equal(protoStr, strHTTP11)
  2623. h.proto = append(h.proto[:0], protoStr...)
  2624. h.requestURI = append(h.requestURI[:0], b[:n]...)
  2625. return len(buf) - len(bNext), nil
  2626. }
  2627. func readRawHeaders(dst, buf []byte) ([]byte, int, error) {
  2628. n := bytes.IndexByte(buf, nChar)
  2629. if n < 0 {
  2630. return dst[:0], 0, errNeedMore
  2631. }
  2632. if (n == 1 && buf[0] == rChar) || n == 0 {
  2633. // empty headers
  2634. return dst, n + 1, nil
  2635. }
  2636. n++
  2637. b := buf
  2638. m := n
  2639. for {
  2640. b = b[m:]
  2641. m = bytes.IndexByte(b, nChar)
  2642. if m < 0 {
  2643. return dst, 0, errNeedMore
  2644. }
  2645. m++
  2646. n += m
  2647. if (m == 2 && b[0] == rChar) || m == 1 {
  2648. dst = append(dst, buf[:n]...)
  2649. return dst, n, nil
  2650. }
  2651. }
  2652. }
  2653. func (h *ResponseHeader) parseHeaders(buf []byte) (int, error) {
  2654. // 'identity' content-length by default
  2655. h.contentLength = -2
  2656. var s headerScanner
  2657. s.b = buf
  2658. var kv *argsKV
  2659. for s.next() {
  2660. if len(s.key) == 0 {
  2661. h.connectionClose = true
  2662. return 0, fmt.Errorf("invalid header key %q", s.key)
  2663. }
  2664. disableNormalizing := h.disableNormalizing
  2665. for _, ch := range s.key {
  2666. if !validHeaderFieldByte(ch) {
  2667. h.connectionClose = true
  2668. // We accept invalid headers with a space before the
  2669. // colon, but must not canonicalize them.
  2670. // See: https://github.com/valyala/fasthttp/issues/1917
  2671. if ch == ' ' {
  2672. disableNormalizing = true
  2673. continue
  2674. }
  2675. return 0, fmt.Errorf("invalid header key %q", s.key)
  2676. }
  2677. }
  2678. normalizeHeaderKey(s.key, disableNormalizing)
  2679. for _, ch := range s.value {
  2680. if !validHeaderValueByte(ch) {
  2681. h.connectionClose = true
  2682. return 0, fmt.Errorf("invalid header value %q", s.value)
  2683. }
  2684. }
  2685. switch s.key[0] | 0x20 {
  2686. case 'c':
  2687. if caseInsensitiveCompare(s.key, strContentType) {
  2688. h.contentType = append(h.contentType[:0], s.value...)
  2689. continue
  2690. }
  2691. if caseInsensitiveCompare(s.key, strContentEncoding) {
  2692. h.contentEncoding = append(h.contentEncoding[:0], s.value...)
  2693. continue
  2694. }
  2695. if caseInsensitiveCompare(s.key, strContentLength) {
  2696. if h.contentLength != -1 {
  2697. var err error
  2698. h.contentLength, err = parseContentLength(s.value)
  2699. if err != nil {
  2700. h.contentLength = -2
  2701. h.connectionClose = true
  2702. return 0, err
  2703. }
  2704. h.contentLengthBytes = append(h.contentLengthBytes[:0], s.value...)
  2705. }
  2706. continue
  2707. }
  2708. if caseInsensitiveCompare(s.key, strConnection) {
  2709. if bytes.Equal(s.value, strClose) {
  2710. h.connectionClose = true
  2711. } else {
  2712. h.connectionClose = false
  2713. h.h = appendArgBytes(h.h, s.key, s.value, argsHasValue)
  2714. }
  2715. continue
  2716. }
  2717. case 's':
  2718. if caseInsensitiveCompare(s.key, strServer) {
  2719. h.server = append(h.server[:0], s.value...)
  2720. continue
  2721. }
  2722. if caseInsensitiveCompare(s.key, strSetCookie) {
  2723. h.cookies, kv = allocArg(h.cookies)
  2724. kv.key = getCookieKey(kv.key, s.value)
  2725. kv.value = append(kv.value[:0], s.value...)
  2726. continue
  2727. }
  2728. case 't':
  2729. if caseInsensitiveCompare(s.key, strTransferEncoding) {
  2730. if len(s.value) > 0 && !bytes.Equal(s.value, strIdentity) {
  2731. h.contentLength = -1
  2732. h.h = setArgBytes(h.h, strTransferEncoding, strChunked, argsHasValue)
  2733. }
  2734. continue
  2735. }
  2736. if caseInsensitiveCompare(s.key, strTrailer) {
  2737. err := h.SetTrailerBytes(s.value)
  2738. if err != nil {
  2739. h.connectionClose = true
  2740. return 0, err
  2741. }
  2742. continue
  2743. }
  2744. }
  2745. h.h = appendArgBytes(h.h, s.key, s.value, argsHasValue)
  2746. }
  2747. if s.err != nil {
  2748. h.connectionClose = true
  2749. return 0, s.err
  2750. }
  2751. if h.contentLength < 0 {
  2752. h.contentLengthBytes = h.contentLengthBytes[:0]
  2753. }
  2754. if h.contentLength == -2 && !h.ConnectionUpgrade() && !h.mustSkipContentLength() {
  2755. // According to modern HTTP/1.1 specifications (RFC 7230):
  2756. // `identity` as a value for `Transfer-Encoding` was removed
  2757. // in the errata to RFC 2616.
  2758. // Therefore, we do not include `Transfer-Encoding: identity` in the header.
  2759. // See: https://github.com/valyala/fasthttp/issues/1909
  2760. h.connectionClose = true
  2761. }
  2762. if h.noHTTP11 && !h.connectionClose {
  2763. // close connection for non-http/1.1 response unless 'Connection: keep-alive' is set.
  2764. v := peekArgBytes(h.h, strConnection)
  2765. h.connectionClose = !hasHeaderValue(v, strKeepAlive)
  2766. }
  2767. return len(buf) - len(s.b), nil
  2768. }
  2769. func (h *RequestHeader) parseHeaders(buf []byte) (int, error) {
  2770. h.contentLength = -2
  2771. contentLengthSeen := false
  2772. var s headerScanner
  2773. s.b = buf
  2774. for s.next() {
  2775. if len(s.key) == 0 {
  2776. h.connectionClose = true
  2777. return 0, fmt.Errorf("invalid header key %q", s.key)
  2778. }
  2779. disableNormalizing := h.disableNormalizing
  2780. for _, ch := range s.key {
  2781. if !validHeaderFieldByte(ch) {
  2782. if ch == ' ' {
  2783. disableNormalizing = true
  2784. continue
  2785. }
  2786. h.connectionClose = true
  2787. return 0, fmt.Errorf("invalid header key %q", s.key)
  2788. }
  2789. }
  2790. normalizeHeaderKey(s.key, disableNormalizing)
  2791. for _, ch := range s.value {
  2792. if !validHeaderValueByte(ch) {
  2793. h.connectionClose = true
  2794. return 0, fmt.Errorf("invalid header value %q", s.value)
  2795. }
  2796. }
  2797. if h.disableSpecialHeader {
  2798. h.h = appendArgBytes(h.h, s.key, s.value, argsHasValue)
  2799. continue
  2800. }
  2801. switch s.key[0] | 0x20 {
  2802. case 'h':
  2803. if caseInsensitiveCompare(s.key, strHost) {
  2804. h.host = append(h.host[:0], s.value...)
  2805. continue
  2806. }
  2807. case 'u':
  2808. if caseInsensitiveCompare(s.key, strUserAgent) {
  2809. h.userAgent = append(h.userAgent[:0], s.value...)
  2810. continue
  2811. }
  2812. case 'c':
  2813. if caseInsensitiveCompare(s.key, strContentType) {
  2814. h.contentType = append(h.contentType[:0], s.value...)
  2815. continue
  2816. }
  2817. if caseInsensitiveCompare(s.key, strContentLength) {
  2818. if contentLengthSeen {
  2819. h.connectionClose = true
  2820. return 0, errors.New("duplicate Content-Length header")
  2821. }
  2822. contentLengthSeen = true
  2823. if h.contentLength != -1 {
  2824. var err error
  2825. h.contentLength, err = parseContentLength(s.value)
  2826. if err != nil {
  2827. h.contentLength = -2
  2828. h.connectionClose = true
  2829. return 0, err
  2830. }
  2831. h.contentLengthBytes = append(h.contentLengthBytes[:0], s.value...)
  2832. }
  2833. continue
  2834. }
  2835. if caseInsensitiveCompare(s.key, strConnection) {
  2836. if bytes.Equal(s.value, strClose) {
  2837. h.connectionClose = true
  2838. } else {
  2839. h.connectionClose = false
  2840. h.h = appendArgBytes(h.h, s.key, s.value, argsHasValue)
  2841. }
  2842. continue
  2843. }
  2844. case 't':
  2845. if caseInsensitiveCompare(s.key, strTransferEncoding) {
  2846. isIdentity := caseInsensitiveCompare(s.value, strIdentity)
  2847. isChunked := caseInsensitiveCompare(s.value, strChunked)
  2848. if !isIdentity && !isChunked {
  2849. h.connectionClose = true
  2850. if h.secureErrorLogMessage {
  2851. return 0, errors.New("unsupported Transfer-Encoding")
  2852. }
  2853. return 0, fmt.Errorf("unsupported Transfer-Encoding: %q", s.value)
  2854. }
  2855. if isChunked {
  2856. h.contentLength = -1
  2857. h.h = setArgBytes(h.h, strTransferEncoding, strChunked, argsHasValue)
  2858. }
  2859. continue
  2860. }
  2861. if caseInsensitiveCompare(s.key, strTrailer) {
  2862. err := h.SetTrailerBytes(s.value)
  2863. if err != nil {
  2864. h.connectionClose = true
  2865. return 0, err
  2866. }
  2867. continue
  2868. }
  2869. }
  2870. h.h = appendArgBytes(h.h, s.key, s.value, argsHasValue)
  2871. }
  2872. if s.err != nil {
  2873. h.connectionClose = true
  2874. return 0, s.err
  2875. }
  2876. if h.contentLength < 0 {
  2877. h.contentLengthBytes = h.contentLengthBytes[:0]
  2878. }
  2879. if h.noHTTP11 && !h.connectionClose {
  2880. // close connection for non-http/1.1 request unless 'Connection: keep-alive' is set.
  2881. v := peekArgBytes(h.h, strConnection)
  2882. h.connectionClose = !hasHeaderValue(v, strKeepAlive)
  2883. }
  2884. return s.hLen, nil
  2885. }
  2886. func (h *RequestHeader) collectCookies() {
  2887. if h.cookiesCollected {
  2888. return
  2889. }
  2890. for i, n := 0, len(h.h); i < n; i++ {
  2891. kv := &h.h[i]
  2892. if caseInsensitiveCompare(kv.key, strCookie) {
  2893. h.cookies = parseRequestCookies(h.cookies, kv.value)
  2894. tmp := *kv
  2895. copy(h.h[i:], h.h[i+1:])
  2896. n--
  2897. i--
  2898. h.h[n] = tmp
  2899. h.h = h.h[:n]
  2900. }
  2901. }
  2902. h.cookiesCollected = true
  2903. }
  2904. var errNonNumericChars = errors.New("non-numeric chars found")
  2905. func parseContentLength(b []byte) (int, error) {
  2906. v, n, err := parseUintBuf(b)
  2907. if err != nil {
  2908. return -1, fmt.Errorf("cannot parse Content-Length: %w", err)
  2909. }
  2910. if n != len(b) {
  2911. return -1, fmt.Errorf("cannot parse Content-Length: %w", errNonNumericChars)
  2912. }
  2913. return v, nil
  2914. }
  2915. type headerScanner struct {
  2916. err error
  2917. b []byte
  2918. key []byte
  2919. value []byte
  2920. // hLen stores header subslice len
  2921. hLen int
  2922. // by checking whether the next line contains a colon or not to tell
  2923. // it's a header entry or a multi line value of current header entry.
  2924. // the side effect of this operation is that we know the index of the
  2925. // next colon and new line, so this can be used during next iteration,
  2926. // instead of find them again.
  2927. nextColon int
  2928. nextNewLine int
  2929. initialized bool
  2930. }
  2931. func (s *headerScanner) next() bool {
  2932. if !s.initialized {
  2933. s.nextColon = -1
  2934. s.nextNewLine = -1
  2935. s.initialized = true
  2936. }
  2937. bLen := len(s.b)
  2938. if bLen >= 2 && s.b[0] == rChar && s.b[1] == nChar {
  2939. s.b = s.b[2:]
  2940. s.hLen += 2
  2941. return false
  2942. }
  2943. if bLen >= 1 && s.b[0] == nChar {
  2944. s.b = s.b[1:]
  2945. s.hLen++
  2946. return false
  2947. }
  2948. var n int
  2949. if s.nextColon >= 0 {
  2950. n = s.nextColon
  2951. s.nextColon = -1
  2952. } else {
  2953. n = bytes.IndexByte(s.b, ':')
  2954. // There can't be a \n inside the header name, check for this.
  2955. x := bytes.IndexByte(s.b, nChar)
  2956. if x < 0 {
  2957. // A header name should always at some point be followed by a \n
  2958. // even if it's the one that terminates the header block.
  2959. s.err = errNeedMore
  2960. return false
  2961. }
  2962. if x < n {
  2963. // There was a \n before the :
  2964. s.err = errInvalidName
  2965. return false
  2966. }
  2967. }
  2968. if n < 0 {
  2969. s.err = errNeedMore
  2970. return false
  2971. }
  2972. s.key = s.b[:n]
  2973. n++
  2974. for len(s.b) > n && (s.b[n] == ' ' || s.b[n] == '\t') {
  2975. n++
  2976. // the newline index is a relative index, and lines below trimmed `s.b` by `n`,
  2977. // so the relative newline index also shifted forward. it's safe to decrease
  2978. // to a minus value, it means it's invalid, and will find the newline again.
  2979. s.nextNewLine--
  2980. }
  2981. s.hLen += n
  2982. s.b = s.b[n:]
  2983. if s.nextNewLine >= 0 {
  2984. n = s.nextNewLine
  2985. s.nextNewLine = -1
  2986. } else {
  2987. n = bytes.IndexByte(s.b, nChar)
  2988. }
  2989. if n < 0 {
  2990. s.err = errNeedMore
  2991. return false
  2992. }
  2993. for n+1 < len(s.b) {
  2994. if s.b[n+1] != ' ' && s.b[n+1] != '\t' {
  2995. break
  2996. }
  2997. d := bytes.IndexByte(s.b[n+1:], nChar)
  2998. if d <= 0 {
  2999. break
  3000. } else if d == 1 && s.b[n+1] == rChar {
  3001. break
  3002. }
  3003. e := n + d + 1
  3004. if c := bytes.IndexByte(s.b[n+1:e], ':'); c >= 0 {
  3005. s.nextColon = c
  3006. s.nextNewLine = d - c - 1
  3007. break
  3008. }
  3009. n = e
  3010. }
  3011. if n >= len(s.b) {
  3012. s.err = errNeedMore
  3013. return false
  3014. }
  3015. s.value = s.b[:n]
  3016. s.hLen += n + 1
  3017. s.b = s.b[n+1:]
  3018. if n > 0 && s.value[n-1] == rChar {
  3019. n--
  3020. }
  3021. for n > 0 && (s.value[n-1] == ' ' || s.value[n-1] == '\t') {
  3022. n--
  3023. }
  3024. s.value = s.value[:n]
  3025. if bytes.Contains(s.b, strCRLF) {
  3026. s.value = normalizeHeaderValue(s.value)
  3027. }
  3028. return true
  3029. }
  3030. type headerValueScanner struct {
  3031. b []byte
  3032. value []byte
  3033. }
  3034. func (s *headerValueScanner) next() bool {
  3035. b := s.b
  3036. if len(b) == 0 {
  3037. return false
  3038. }
  3039. n := bytes.IndexByte(b, ',')
  3040. if n < 0 {
  3041. s.value = stripSpace(b)
  3042. s.b = b[len(b):]
  3043. return true
  3044. }
  3045. s.value = stripSpace(b[:n])
  3046. s.b = b[n+1:]
  3047. return true
  3048. }
  3049. func stripSpace(b []byte) []byte {
  3050. for len(b) > 0 && b[0] == ' ' {
  3051. b = b[1:]
  3052. }
  3053. for len(b) > 0 && b[len(b)-1] == ' ' {
  3054. b = b[:len(b)-1]
  3055. }
  3056. return b
  3057. }
  3058. func hasHeaderValue(s, value []byte) bool {
  3059. var vs headerValueScanner
  3060. vs.b = s
  3061. for vs.next() {
  3062. if caseInsensitiveCompare(vs.value, value) {
  3063. return true
  3064. }
  3065. }
  3066. return false
  3067. }
  3068. func nextLine(b []byte) ([]byte, []byte, error) {
  3069. nNext := bytes.IndexByte(b, nChar)
  3070. if nNext < 0 {
  3071. return nil, nil, errNeedMore
  3072. }
  3073. n := nNext
  3074. if n > 0 && b[n-1] == rChar {
  3075. n--
  3076. }
  3077. return b[:n], b[nNext+1:], nil
  3078. }
  3079. func initHeaderKV(bufK, bufV []byte, key, value string, disableNormalizing bool) ([]byte, []byte) {
  3080. bufK = getHeaderKeyBytes(bufK, key, disableNormalizing)
  3081. // https://tools.ietf.org/html/rfc7230#section-3.2.4
  3082. bufV = append(bufV[:0], value...)
  3083. bufV = removeNewLines(bufV)
  3084. return bufK, bufV
  3085. }
  3086. func getHeaderKeyBytes(bufK []byte, key string, disableNormalizing bool) []byte {
  3087. bufK = append(bufK[:0], key...)
  3088. normalizeHeaderKey(bufK, disableNormalizing || bytes.IndexByte(bufK, ' ') != -1)
  3089. return bufK
  3090. }
  3091. func normalizeHeaderValue(ov []byte) (nv []byte) {
  3092. nv = ov
  3093. length := len(ov)
  3094. if length <= 0 {
  3095. return
  3096. }
  3097. write := 0
  3098. shrunk := 0
  3099. once := false
  3100. lineStart := false
  3101. for read := 0; read < length; read++ {
  3102. c := ov[read]
  3103. switch {
  3104. case c == rChar || c == nChar:
  3105. shrunk++
  3106. if c == nChar {
  3107. lineStart = true
  3108. once = false
  3109. }
  3110. continue
  3111. case lineStart && (c == '\t' || c == ' '):
  3112. if !once {
  3113. c = ' '
  3114. once = true
  3115. } else {
  3116. shrunk++
  3117. continue
  3118. }
  3119. default:
  3120. lineStart = false
  3121. }
  3122. nv[write] = c
  3123. write++
  3124. }
  3125. nv = nv[:length-shrunk]
  3126. return
  3127. }
  3128. func normalizeHeaderKey(b []byte, disableNormalizing bool) {
  3129. if disableNormalizing {
  3130. return
  3131. }
  3132. n := len(b)
  3133. if n == 0 {
  3134. return
  3135. }
  3136. b[0] = toUpperTable[b[0]]
  3137. for i := 1; i < n; i++ {
  3138. p := &b[i]
  3139. if *p == '-' {
  3140. i++
  3141. if i < n {
  3142. b[i] = toUpperTable[b[i]]
  3143. }
  3144. continue
  3145. }
  3146. *p = toLowerTable[*p]
  3147. }
  3148. }
  3149. // removeNewLines will replace `\r` and `\n` with an empty space.
  3150. func removeNewLines(raw []byte) []byte {
  3151. // check if a `\r` is present and save the position.
  3152. // if no `\r` is found, check if a `\n` is present.
  3153. foundR := bytes.IndexByte(raw, rChar)
  3154. foundN := bytes.IndexByte(raw, nChar)
  3155. start := 0
  3156. switch {
  3157. case foundN != -1:
  3158. if foundR > foundN {
  3159. start = foundN
  3160. } else if foundR != -1 {
  3161. start = foundR
  3162. }
  3163. case foundR != -1:
  3164. start = foundR
  3165. default:
  3166. return raw
  3167. }
  3168. for i := start; i < len(raw); i++ {
  3169. switch raw[i] {
  3170. case rChar, nChar:
  3171. raw[i] = ' '
  3172. default:
  3173. continue
  3174. }
  3175. }
  3176. return raw
  3177. }
  3178. // AppendNormalizedHeaderKey appends normalized header key (name) to dst
  3179. // and returns the resulting dst.
  3180. //
  3181. // Normalized header key starts with uppercase letter. The first letters
  3182. // after dashes are also uppercased. All the other letters are lowercased.
  3183. // Examples:
  3184. //
  3185. // - coNTENT-TYPe -> Content-Type
  3186. // - HOST -> Host
  3187. // - foo-bar-baz -> Foo-Bar-Baz
  3188. func AppendNormalizedHeaderKey(dst []byte, key string) []byte {
  3189. dst = append(dst, key...)
  3190. normalizeHeaderKey(dst[len(dst)-len(key):], false)
  3191. return dst
  3192. }
  3193. // AppendNormalizedHeaderKeyBytes appends normalized header key (name) to dst
  3194. // and returns the resulting dst.
  3195. //
  3196. // Normalized header key starts with uppercase letter. The first letters
  3197. // after dashes are also uppercased. All the other letters are lowercased.
  3198. // Examples:
  3199. //
  3200. // - coNTENT-TYPe -> Content-Type
  3201. // - HOST -> Host
  3202. // - foo-bar-baz -> Foo-Bar-Baz
  3203. func AppendNormalizedHeaderKeyBytes(dst, key []byte) []byte {
  3204. return AppendNormalizedHeaderKey(dst, b2s(key))
  3205. }
  3206. func appendTrailerBytes(dst []byte, trailer [][]byte, sep []byte) []byte {
  3207. for i, n := 0, len(trailer); i < n; i++ {
  3208. dst = append(dst, trailer[i]...)
  3209. if i+1 < n {
  3210. dst = append(dst, sep...)
  3211. }
  3212. }
  3213. return dst
  3214. }
  3215. func copyTrailer(dst, src [][]byte) [][]byte {
  3216. if cap(dst) > len(src) {
  3217. dst = dst[:len(src)]
  3218. } else {
  3219. dst = append(dst[:0], src...)
  3220. }
  3221. for i := range dst {
  3222. dst[i] = make([]byte, len(src[i]))
  3223. copy(dst[i], src[i])
  3224. }
  3225. return dst
  3226. }
  3227. var (
  3228. errNeedMore = errors.New("need more data: cannot find trailing lf")
  3229. errInvalidName = errors.New("invalid header name")
  3230. errSmallBuffer = errors.New("small read buffer. Increase ReadBufferSize")
  3231. )
  3232. // ErrNothingRead is returned when a keep-alive connection is closed,
  3233. // either because the remote closed it or because of a read timeout.
  3234. type ErrNothingRead struct {
  3235. error
  3236. }
  3237. // ErrSmallBuffer is returned when the provided buffer size is too small
  3238. // for reading request and/or response headers.
  3239. //
  3240. // ReadBufferSize value from Server or clients should reduce the number
  3241. // of such errors.
  3242. type ErrSmallBuffer struct {
  3243. error
  3244. }
  3245. func mustPeekBuffered(r *bufio.Reader) []byte {
  3246. buf, err := r.Peek(r.Buffered())
  3247. if len(buf) == 0 || err != nil {
  3248. panic(fmt.Sprintf("bufio.Reader.Peek() returned unexpected data (%q, %v)", buf, err))
  3249. }
  3250. return buf
  3251. }
  3252. func mustDiscard(r *bufio.Reader, n int) {
  3253. if _, err := r.Discard(n); err != nil {
  3254. panic(fmt.Sprintf("bufio.Reader.Discard(%d) failed: %v", n, err))
  3255. }
  3256. }