header.go 96 KB

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