header.go 93 KB

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