header.go 96 KB

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