header.go 102 KB

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