header.go 101 KB

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