header.go 96 KB

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