header.go 94 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391
  1. package fasthttp
  2. import (
  3. "bufio"
  4. "bytes"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "sync"
  9. "sync/atomic"
  10. "time"
  11. )
  12. const (
  13. rChar = byte('\r')
  14. nChar = byte('\n')
  15. )
  16. // ResponseHeader represents HTTP response header.
  17. //
  18. // It is forbidden copying ResponseHeader instances.
  19. // Create new instances instead and use CopyTo.
  20. //
  21. // ResponseHeader instance MUST NOT be used from concurrently running
  22. // goroutines.
  23. type ResponseHeader struct {
  24. noCopy noCopy
  25. disableNormalizing bool
  26. noHTTP11 bool
  27. connectionClose bool
  28. noDefaultContentType bool
  29. noDefaultDate bool
  30. statusCode int
  31. statusMessage []byte
  32. protocol []byte
  33. contentLength int
  34. contentLengthBytes []byte
  35. secureErrorLogMessage bool
  36. contentType []byte
  37. contentEncoding []byte
  38. server []byte
  39. mulHeader [][]byte
  40. h []argsKV
  41. trailer []argsKV
  42. bufKV argsKV
  43. cookies []argsKV
  44. }
  45. // RequestHeader represents HTTP request header.
  46. //
  47. // It is forbidden copying RequestHeader instances.
  48. // Create new instances instead and use CopyTo.
  49. //
  50. // RequestHeader instance MUST NOT be used from concurrently running
  51. // goroutines.
  52. type RequestHeader struct {
  53. noCopy noCopy
  54. disableNormalizing bool
  55. noHTTP11 bool
  56. connectionClose bool
  57. noDefaultContentType bool
  58. // 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.noDefaultContentType = h.noDefaultContentType
  915. dst.contentLength = h.contentLength
  916. dst.contentLengthBytes = append(dst.contentLengthBytes, h.contentLengthBytes...)
  917. dst.method = append(dst.method, h.method...)
  918. dst.proto = append(dst.proto, h.proto...)
  919. dst.requestURI = append(dst.requestURI, h.requestURI...)
  920. dst.host = append(dst.host, h.host...)
  921. dst.contentType = append(dst.contentType, h.contentType...)
  922. dst.userAgent = append(dst.userAgent, h.userAgent...)
  923. dst.trailer = append(dst.trailer, h.trailer...)
  924. dst.h = copyArgs(dst.h, h.h)
  925. dst.cookies = copyArgs(dst.cookies, h.cookies)
  926. dst.cookiesCollected = h.cookiesCollected
  927. dst.rawHeaders = append(dst.rawHeaders, h.rawHeaders...)
  928. }
  929. // VisitAll calls f for each header.
  930. //
  931. // f must not retain references to key and/or value after returning.
  932. // Copy key and/or value contents before returning if you need retaining them.
  933. func (h *ResponseHeader) VisitAll(f func(key, value []byte)) {
  934. if len(h.contentLengthBytes) > 0 {
  935. f(strContentLength, h.contentLengthBytes)
  936. }
  937. contentType := h.ContentType()
  938. if len(contentType) > 0 {
  939. f(strContentType, contentType)
  940. }
  941. contentEncoding := h.ContentEncoding()
  942. if len(contentEncoding) > 0 {
  943. f(strContentEncoding, contentEncoding)
  944. }
  945. server := h.Server()
  946. if len(server) > 0 {
  947. f(strServer, server)
  948. }
  949. if len(h.cookies) > 0 {
  950. visitArgs(h.cookies, func(_, v []byte) {
  951. f(strSetCookie, v)
  952. })
  953. }
  954. if len(h.trailer) > 0 {
  955. f(strTrailer, appendArgsKeyBytes(nil, h.trailer, strCommaSpace))
  956. }
  957. visitArgs(h.h, f)
  958. if h.ConnectionClose() {
  959. f(strConnection, strClose)
  960. }
  961. }
  962. // VisitAllTrailer calls f for each response Trailer.
  963. //
  964. // f must not retain references to value after returning.
  965. func (h *ResponseHeader) VisitAllTrailer(f func(value []byte)) {
  966. visitArgsKey(h.trailer, f)
  967. }
  968. // VisitAllTrailer calls f for each request Trailer.
  969. //
  970. // f must not retain references to value after returning.
  971. func (h *RequestHeader) VisitAllTrailer(f func(value []byte)) {
  972. visitArgsKey(h.trailer, f)
  973. }
  974. // VisitAllCookie calls f for each response cookie.
  975. //
  976. // Cookie name is passed in key and the whole Set-Cookie header value
  977. // is passed in value on each f invocation. Value may be parsed
  978. // with Cookie.ParseBytes().
  979. //
  980. // f must not retain references to key and/or value after returning.
  981. func (h *ResponseHeader) VisitAllCookie(f func(key, value []byte)) {
  982. visitArgs(h.cookies, f)
  983. }
  984. // VisitAllCookie calls f for each request cookie.
  985. //
  986. // f must not retain references to key and/or value after returning.
  987. func (h *RequestHeader) VisitAllCookie(f func(key, value []byte)) {
  988. h.collectCookies()
  989. visitArgs(h.cookies, f)
  990. }
  991. // VisitAll calls f for each header.
  992. //
  993. // f must not retain references to key and/or value after returning.
  994. // Copy key and/or value contents before returning if you need retaining them.
  995. //
  996. // To get the headers in order they were received use VisitAllInOrder.
  997. func (h *RequestHeader) VisitAll(f func(key, value []byte)) {
  998. host := h.Host()
  999. if len(host) > 0 {
  1000. f(strHost, host)
  1001. }
  1002. if len(h.contentLengthBytes) > 0 {
  1003. f(strContentLength, h.contentLengthBytes)
  1004. }
  1005. contentType := h.ContentType()
  1006. if len(contentType) > 0 {
  1007. f(strContentType, contentType)
  1008. }
  1009. userAgent := h.UserAgent()
  1010. if len(userAgent) > 0 {
  1011. f(strUserAgent, userAgent)
  1012. }
  1013. if len(h.trailer) > 0 {
  1014. f(strTrailer, appendArgsKeyBytes(nil, h.trailer, strCommaSpace))
  1015. }
  1016. h.collectCookies()
  1017. if len(h.cookies) > 0 {
  1018. h.bufKV.value = appendRequestCookieBytes(h.bufKV.value[:0], h.cookies)
  1019. f(strCookie, h.bufKV.value)
  1020. }
  1021. visitArgs(h.h, f)
  1022. if h.ConnectionClose() {
  1023. f(strConnection, strClose)
  1024. }
  1025. }
  1026. // VisitAllInOrder calls f for each header in the order they were received.
  1027. //
  1028. // f must not retain references to key and/or value after returning.
  1029. // Copy key and/or value contents before returning if you need retaining them.
  1030. //
  1031. // This function is slightly slower than VisitAll because it has to reparse the
  1032. // raw headers to get the order.
  1033. func (h *RequestHeader) VisitAllInOrder(f func(key, value []byte)) {
  1034. var s headerScanner
  1035. s.b = h.rawHeaders
  1036. s.disableNormalizing = h.disableNormalizing
  1037. for s.next() {
  1038. if len(s.key) > 0 {
  1039. f(s.key, s.value)
  1040. }
  1041. }
  1042. }
  1043. // Del deletes header with the given key.
  1044. func (h *ResponseHeader) Del(key string) {
  1045. k := getHeaderKeyBytes(&h.bufKV, key, h.disableNormalizing)
  1046. h.del(k)
  1047. }
  1048. // DelBytes deletes header with the given key.
  1049. func (h *ResponseHeader) DelBytes(key []byte) {
  1050. h.bufKV.key = append(h.bufKV.key[:0], key...)
  1051. normalizeHeaderKey(h.bufKV.key, h.disableNormalizing)
  1052. h.del(h.bufKV.key)
  1053. }
  1054. func (h *ResponseHeader) del(key []byte) {
  1055. switch string(key) {
  1056. case HeaderContentType:
  1057. h.contentType = h.contentType[:0]
  1058. case HeaderContentEncoding:
  1059. h.contentEncoding = h.contentEncoding[:0]
  1060. case HeaderServer:
  1061. h.server = h.server[:0]
  1062. case HeaderSetCookie:
  1063. h.cookies = h.cookies[:0]
  1064. case HeaderContentLength:
  1065. h.contentLength = 0
  1066. h.contentLengthBytes = h.contentLengthBytes[:0]
  1067. case HeaderConnection:
  1068. h.connectionClose = false
  1069. case HeaderTrailer:
  1070. h.trailer = h.trailer[:0]
  1071. }
  1072. h.h = delAllArgsBytes(h.h, key)
  1073. }
  1074. // Del deletes header with the given key.
  1075. func (h *RequestHeader) Del(key string) {
  1076. k := getHeaderKeyBytes(&h.bufKV, key, h.disableNormalizing)
  1077. h.del(k)
  1078. }
  1079. // DelBytes deletes header with the given key.
  1080. func (h *RequestHeader) DelBytes(key []byte) {
  1081. h.bufKV.key = append(h.bufKV.key[:0], key...)
  1082. normalizeHeaderKey(h.bufKV.key, h.disableNormalizing)
  1083. h.del(h.bufKV.key)
  1084. }
  1085. func (h *RequestHeader) del(key []byte) {
  1086. switch string(key) {
  1087. case HeaderHost:
  1088. h.host = h.host[:0]
  1089. case HeaderContentType:
  1090. h.contentType = h.contentType[:0]
  1091. case HeaderUserAgent:
  1092. h.userAgent = h.userAgent[:0]
  1093. case HeaderCookie:
  1094. h.cookies = h.cookies[:0]
  1095. case HeaderContentLength:
  1096. h.contentLength = 0
  1097. h.contentLengthBytes = h.contentLengthBytes[:0]
  1098. case HeaderConnection:
  1099. h.connectionClose = false
  1100. case HeaderTrailer:
  1101. h.trailer = h.trailer[:0]
  1102. }
  1103. h.h = delAllArgsBytes(h.h, key)
  1104. }
  1105. // setSpecialHeader handles special headers and return true when a header is processed.
  1106. func (h *ResponseHeader) setSpecialHeader(key, value []byte) bool {
  1107. if len(key) == 0 {
  1108. return false
  1109. }
  1110. switch key[0] | 0x20 {
  1111. case 'c':
  1112. if caseInsensitiveCompare(strContentType, key) {
  1113. h.SetContentTypeBytes(value)
  1114. return true
  1115. } else if caseInsensitiveCompare(strContentLength, key) {
  1116. if contentLength, err := parseContentLength(value); err == nil {
  1117. h.contentLength = contentLength
  1118. h.contentLengthBytes = append(h.contentLengthBytes[:0], value...)
  1119. }
  1120. return true
  1121. } else if caseInsensitiveCompare(strContentEncoding, key) {
  1122. h.SetContentEncodingBytes(value)
  1123. return true
  1124. } else if caseInsensitiveCompare(strConnection, key) {
  1125. if bytes.Equal(strClose, value) {
  1126. h.SetConnectionClose()
  1127. } else {
  1128. h.ResetConnectionClose()
  1129. h.setNonSpecial(key, value)
  1130. }
  1131. return true
  1132. }
  1133. case 's':
  1134. if caseInsensitiveCompare(strServer, key) {
  1135. h.SetServerBytes(value)
  1136. return true
  1137. } else if caseInsensitiveCompare(strSetCookie, key) {
  1138. var kv *argsKV
  1139. h.cookies, kv = allocArg(h.cookies)
  1140. kv.key = getCookieKey(kv.key, value)
  1141. kv.value = append(kv.value[:0], value...)
  1142. return true
  1143. }
  1144. case 't':
  1145. if caseInsensitiveCompare(strTransferEncoding, key) {
  1146. // Transfer-Encoding is managed automatically.
  1147. return true
  1148. } else if caseInsensitiveCompare(strTrailer, key) {
  1149. _ = h.SetTrailerBytes(value)
  1150. return true
  1151. }
  1152. case 'd':
  1153. if caseInsensitiveCompare(strDate, key) {
  1154. // Date is managed automatically.
  1155. return true
  1156. }
  1157. }
  1158. return false
  1159. }
  1160. // setNonSpecial directly put into map i.e. not a basic header
  1161. func (h *ResponseHeader) setNonSpecial(key []byte, value []byte) {
  1162. h.h = setArgBytes(h.h, key, value, argsHasValue)
  1163. }
  1164. // setSpecialHeader handles special headers and return true when a header is processed.
  1165. func (h *RequestHeader) setSpecialHeader(key, value []byte) bool {
  1166. if len(key) == 0 {
  1167. return false
  1168. }
  1169. switch key[0] | 0x20 {
  1170. case 'c':
  1171. if caseInsensitiveCompare(strContentType, key) {
  1172. h.SetContentTypeBytes(value)
  1173. return true
  1174. } else if caseInsensitiveCompare(strContentLength, key) {
  1175. if contentLength, err := parseContentLength(value); err == nil {
  1176. h.contentLength = contentLength
  1177. h.contentLengthBytes = append(h.contentLengthBytes[:0], value...)
  1178. }
  1179. return true
  1180. } else if caseInsensitiveCompare(strConnection, key) {
  1181. if bytes.Equal(strClose, value) {
  1182. h.SetConnectionClose()
  1183. } else {
  1184. h.ResetConnectionClose()
  1185. h.setNonSpecial(key, value)
  1186. }
  1187. return true
  1188. } else if caseInsensitiveCompare(strCookie, key) {
  1189. h.collectCookies()
  1190. h.cookies = parseRequestCookies(h.cookies, value)
  1191. return true
  1192. }
  1193. case 't':
  1194. if caseInsensitiveCompare(strTransferEncoding, key) {
  1195. // Transfer-Encoding is managed automatically.
  1196. return true
  1197. } else if caseInsensitiveCompare(strTrailer, key) {
  1198. _ = h.SetTrailerBytes(value)
  1199. return true
  1200. }
  1201. case 'h':
  1202. if caseInsensitiveCompare(strHost, key) {
  1203. h.SetHostBytes(value)
  1204. return true
  1205. }
  1206. case 'u':
  1207. if caseInsensitiveCompare(strUserAgent, key) {
  1208. h.SetUserAgentBytes(value)
  1209. return true
  1210. }
  1211. }
  1212. return false
  1213. }
  1214. // setNonSpecial directly put into map i.e. not a basic header
  1215. func (h *RequestHeader) setNonSpecial(key []byte, value []byte) {
  1216. h.h = setArgBytes(h.h, key, value, argsHasValue)
  1217. }
  1218. // Add adds the given 'key: value' header.
  1219. //
  1220. // Multiple headers with the same key may be added with this function.
  1221. // Use Set for setting a single header for the given key.
  1222. //
  1223. // the Content-Type, Content-Length, Connection, Server, Set-Cookie,
  1224. // Transfer-Encoding and Date headers can only be set once and will
  1225. // overwrite the previous value.
  1226. //
  1227. // If the header is set as a Trailer (forbidden trailers will not be set, see AddTrailer for more details),
  1228. // it will be sent after the chunked response body.
  1229. func (h *ResponseHeader) Add(key, value string) {
  1230. h.AddBytesKV(s2b(key), s2b(value))
  1231. }
  1232. // AddBytesK adds the given 'key: value' header.
  1233. //
  1234. // Multiple headers with the same key may be added with this function.
  1235. // Use SetBytesK for setting a single header for the given key.
  1236. //
  1237. // the Content-Type, Content-Length, Connection, Server, Set-Cookie,
  1238. // Transfer-Encoding and Date headers can only be set once and will
  1239. // overwrite the previous value.
  1240. //
  1241. // If the header is set as a Trailer (forbidden trailers will not be set, see AddTrailer for more details),
  1242. // it will be sent after the chunked response body.
  1243. func (h *ResponseHeader) AddBytesK(key []byte, value string) {
  1244. h.AddBytesKV(key, s2b(value))
  1245. }
  1246. // AddBytesV adds the given 'key: value' header.
  1247. //
  1248. // Multiple headers with the same key may be added with this function.
  1249. // Use SetBytesV for setting a single header for the given key.
  1250. //
  1251. // the Content-Type, Content-Length, Connection, Server, Set-Cookie,
  1252. // Transfer-Encoding and Date headers can only be set once and will
  1253. // overwrite the previous value.
  1254. //
  1255. // If the header is set as a Trailer (forbidden trailers will not be set, see AddTrailer for more details),
  1256. // it will be sent after the chunked response body.
  1257. func (h *ResponseHeader) AddBytesV(key string, value []byte) {
  1258. h.AddBytesKV(s2b(key), value)
  1259. }
  1260. // AddBytesKV adds the given 'key: value' header.
  1261. //
  1262. // Multiple headers with the same key may be added with this function.
  1263. // Use SetBytesKV for setting a single header for the given key.
  1264. //
  1265. // the Content-Type, Content-Length, Connection, Server, Set-Cookie,
  1266. // Transfer-Encoding and Date headers can only be set once and will
  1267. // overwrite the previous value.
  1268. //
  1269. // If the header is set as a Trailer (forbidden trailers will not be set, see AddTrailer for more details),
  1270. // it will be sent after the chunked response body.
  1271. func (h *ResponseHeader) AddBytesKV(key, value []byte) {
  1272. if h.setSpecialHeader(key, value) {
  1273. return
  1274. }
  1275. k := getHeaderKeyBytes(&h.bufKV, b2s(key), h.disableNormalizing)
  1276. h.h = appendArgBytes(h.h, k, value, argsHasValue)
  1277. }
  1278. // Set sets the given 'key: value' header.
  1279. //
  1280. // If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details),
  1281. // it will be sent after the chunked response body.
  1282. //
  1283. // Use Add for setting multiple header values under the same key.
  1284. func (h *ResponseHeader) Set(key, value string) {
  1285. initHeaderKV(&h.bufKV, key, value, h.disableNormalizing)
  1286. h.SetCanonical(h.bufKV.key, h.bufKV.value)
  1287. }
  1288. // SetBytesK sets the given 'key: value' header.
  1289. //
  1290. // If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details),
  1291. // it will be sent after the chunked response body.
  1292. //
  1293. // Use AddBytesK for setting multiple header values under the same key.
  1294. func (h *ResponseHeader) SetBytesK(key []byte, value string) {
  1295. h.bufKV.value = append(h.bufKV.value[:0], value...)
  1296. h.SetBytesKV(key, h.bufKV.value)
  1297. }
  1298. // SetBytesV sets the given 'key: value' header.
  1299. //
  1300. // If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details),
  1301. // it will be sent after the chunked response body.
  1302. //
  1303. // Use AddBytesV for setting multiple header values under the same key.
  1304. func (h *ResponseHeader) SetBytesV(key string, value []byte) {
  1305. k := getHeaderKeyBytes(&h.bufKV, key, h.disableNormalizing)
  1306. h.SetCanonical(k, value)
  1307. }
  1308. // SetBytesKV sets the given 'key: value' header.
  1309. //
  1310. // If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details),
  1311. // it will be sent after the chunked response body.
  1312. //
  1313. // Use AddBytesKV for setting multiple header values under the same key.
  1314. func (h *ResponseHeader) SetBytesKV(key, value []byte) {
  1315. h.bufKV.key = append(h.bufKV.key[:0], key...)
  1316. normalizeHeaderKey(h.bufKV.key, h.disableNormalizing)
  1317. h.SetCanonical(h.bufKV.key, value)
  1318. }
  1319. // SetCanonical sets the given 'key: value' header assuming that
  1320. // key is in canonical form.
  1321. //
  1322. // If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details),
  1323. // it will be sent after the chunked response body.
  1324. func (h *ResponseHeader) SetCanonical(key, value []byte) {
  1325. if h.setSpecialHeader(key, value) {
  1326. return
  1327. }
  1328. h.setNonSpecial(key, value)
  1329. }
  1330. // SetCookie sets the given response cookie.
  1331. //
  1332. // It is safe re-using the cookie after the function returns.
  1333. func (h *ResponseHeader) SetCookie(cookie *Cookie) {
  1334. h.cookies = setArgBytes(h.cookies, cookie.Key(), cookie.Cookie(), argsHasValue)
  1335. }
  1336. // SetCookie sets 'key: value' cookies.
  1337. func (h *RequestHeader) SetCookie(key, value string) {
  1338. h.collectCookies()
  1339. h.cookies = setArg(h.cookies, key, value, argsHasValue)
  1340. }
  1341. // SetCookieBytesK sets 'key: value' cookies.
  1342. func (h *RequestHeader) SetCookieBytesK(key []byte, value string) {
  1343. h.SetCookie(b2s(key), value)
  1344. }
  1345. // SetCookieBytesKV sets 'key: value' cookies.
  1346. func (h *RequestHeader) SetCookieBytesKV(key, value []byte) {
  1347. h.SetCookie(b2s(key), b2s(value))
  1348. }
  1349. // DelClientCookie instructs the client to remove the given cookie.
  1350. // This doesn't work for a cookie with specific domain or path,
  1351. // you should delete it manually like:
  1352. //
  1353. // c := AcquireCookie()
  1354. // c.SetKey(key)
  1355. // c.SetDomain("example.com")
  1356. // c.SetPath("/path")
  1357. // c.SetExpire(CookieExpireDelete)
  1358. // h.SetCookie(c)
  1359. // ReleaseCookie(c)
  1360. //
  1361. // Use DelCookie if you want just removing the cookie from response header.
  1362. func (h *ResponseHeader) DelClientCookie(key string) {
  1363. h.DelCookie(key)
  1364. c := AcquireCookie()
  1365. c.SetKey(key)
  1366. c.SetExpire(CookieExpireDelete)
  1367. h.SetCookie(c)
  1368. ReleaseCookie(c)
  1369. }
  1370. // DelClientCookieBytes instructs the client to remove the given cookie.
  1371. // This doesn't work for a cookie with specific domain or path,
  1372. // you should delete it manually like:
  1373. //
  1374. // c := AcquireCookie()
  1375. // c.SetKey(key)
  1376. // c.SetDomain("example.com")
  1377. // c.SetPath("/path")
  1378. // c.SetExpire(CookieExpireDelete)
  1379. // h.SetCookie(c)
  1380. // ReleaseCookie(c)
  1381. //
  1382. // Use DelCookieBytes if you want just removing the cookie from response header.
  1383. func (h *ResponseHeader) DelClientCookieBytes(key []byte) {
  1384. h.DelClientCookie(b2s(key))
  1385. }
  1386. // DelCookie removes cookie under the given key from response header.
  1387. //
  1388. // Note that DelCookie doesn't remove the cookie from the client.
  1389. // Use DelClientCookie instead.
  1390. func (h *ResponseHeader) DelCookie(key string) {
  1391. h.cookies = delAllArgs(h.cookies, key)
  1392. }
  1393. // DelCookieBytes removes cookie under the given key from response header.
  1394. //
  1395. // Note that DelCookieBytes doesn't remove the cookie from the client.
  1396. // Use DelClientCookieBytes instead.
  1397. func (h *ResponseHeader) DelCookieBytes(key []byte) {
  1398. h.DelCookie(b2s(key))
  1399. }
  1400. // DelCookie removes cookie under the given key.
  1401. func (h *RequestHeader) DelCookie(key string) {
  1402. h.collectCookies()
  1403. h.cookies = delAllArgs(h.cookies, key)
  1404. }
  1405. // DelCookieBytes removes cookie under the given key.
  1406. func (h *RequestHeader) DelCookieBytes(key []byte) {
  1407. h.DelCookie(b2s(key))
  1408. }
  1409. // DelAllCookies removes all the cookies from response headers.
  1410. func (h *ResponseHeader) DelAllCookies() {
  1411. h.cookies = h.cookies[:0]
  1412. }
  1413. // DelAllCookies removes all the cookies from request headers.
  1414. func (h *RequestHeader) DelAllCookies() {
  1415. h.collectCookies()
  1416. h.cookies = h.cookies[:0]
  1417. }
  1418. // Add adds the given 'key: value' header.
  1419. //
  1420. // Multiple headers with the same key may be added with this function.
  1421. // Use Set for setting a single header for the given key.
  1422. //
  1423. // If the header is set as a Trailer (forbidden trailers will not be set, see AddTrailer for more details),
  1424. // it will be sent after the chunked request body.
  1425. func (h *RequestHeader) Add(key, value string) {
  1426. h.AddBytesKV(s2b(key), s2b(value))
  1427. }
  1428. // AddBytesK adds the given 'key: value' header.
  1429. //
  1430. // Multiple headers with the same key may be added with this function.
  1431. // Use SetBytesK for setting a single header for the given key.
  1432. //
  1433. // If the header is set as a Trailer (forbidden trailers will not be set, see AddTrailer for more details),
  1434. // it will be sent after the chunked request body.
  1435. func (h *RequestHeader) AddBytesK(key []byte, value string) {
  1436. h.AddBytesKV(key, s2b(value))
  1437. }
  1438. // AddBytesV adds the given 'key: value' header.
  1439. //
  1440. // Multiple headers with the same key may be added with this function.
  1441. // Use SetBytesV for setting a single header for the given key.
  1442. //
  1443. // If the header is set as a Trailer (forbidden trailers will not be set, see AddTrailer for more details),
  1444. // it will be sent after the chunked request body.
  1445. func (h *RequestHeader) AddBytesV(key string, value []byte) {
  1446. h.AddBytesKV(s2b(key), value)
  1447. }
  1448. // AddBytesKV adds the given 'key: value' header.
  1449. //
  1450. // Multiple headers with the same key may be added with this function.
  1451. // Use SetBytesKV for setting a single header for the given key.
  1452. //
  1453. // the Content-Type, Content-Length, Connection, Cookie,
  1454. // Transfer-Encoding, Host and User-Agent headers can only be set once
  1455. // and will overwrite the previous value.
  1456. //
  1457. // If the header is set as a Trailer (forbidden trailers will not be set, see AddTrailer for more details),
  1458. // it will be sent after the chunked request body.
  1459. func (h *RequestHeader) AddBytesKV(key, value []byte) {
  1460. if h.setSpecialHeader(key, value) {
  1461. return
  1462. }
  1463. k := getHeaderKeyBytes(&h.bufKV, b2s(key), h.disableNormalizing)
  1464. h.h = appendArgBytes(h.h, k, value, argsHasValue)
  1465. }
  1466. // Set sets the given 'key: value' header.
  1467. //
  1468. // If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details),
  1469. // it will be sent after the chunked request body.
  1470. //
  1471. // Use Add for setting multiple header values under the same key.
  1472. func (h *RequestHeader) Set(key, value string) {
  1473. initHeaderKV(&h.bufKV, key, value, h.disableNormalizing)
  1474. h.SetCanonical(h.bufKV.key, h.bufKV.value)
  1475. }
  1476. // SetBytesK sets the given 'key: value' header.
  1477. //
  1478. // If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details),
  1479. // it will be sent after the chunked request body.
  1480. //
  1481. // Use AddBytesK for setting multiple header values under the same key.
  1482. func (h *RequestHeader) SetBytesK(key []byte, value string) {
  1483. h.bufKV.value = append(h.bufKV.value[:0], value...)
  1484. h.SetBytesKV(key, h.bufKV.value)
  1485. }
  1486. // SetBytesV sets the given 'key: value' header.
  1487. //
  1488. // If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details),
  1489. // it will be sent after the chunked request body.
  1490. //
  1491. // Use AddBytesV for setting multiple header values under the same key.
  1492. func (h *RequestHeader) SetBytesV(key string, value []byte) {
  1493. k := getHeaderKeyBytes(&h.bufKV, key, h.disableNormalizing)
  1494. h.SetCanonical(k, value)
  1495. }
  1496. // SetBytesKV sets the given 'key: value' header.
  1497. //
  1498. // If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details),
  1499. // it will be sent after the chunked request body.
  1500. //
  1501. // Use AddBytesKV for setting multiple header values under the same key.
  1502. func (h *RequestHeader) SetBytesKV(key, value []byte) {
  1503. h.bufKV.key = append(h.bufKV.key[:0], key...)
  1504. normalizeHeaderKey(h.bufKV.key, h.disableNormalizing)
  1505. h.SetCanonical(h.bufKV.key, value)
  1506. }
  1507. // SetCanonical sets the given 'key: value' header assuming that
  1508. // key is in canonical form.
  1509. //
  1510. // If the header is set as a Trailer (forbidden trailers will not be set, see SetTrailer for more details),
  1511. // it will be sent after the chunked request body.
  1512. func (h *RequestHeader) SetCanonical(key, value []byte) {
  1513. if h.setSpecialHeader(key, value) {
  1514. return
  1515. }
  1516. h.setNonSpecial(key, value)
  1517. }
  1518. // Peek returns header value for the given key.
  1519. //
  1520. // The returned value is valid until the response is released,
  1521. // either though ReleaseResponse or your request handler returning.
  1522. // Do not store references to the returned value. Make copies instead.
  1523. func (h *ResponseHeader) Peek(key string) []byte {
  1524. k := getHeaderKeyBytes(&h.bufKV, key, h.disableNormalizing)
  1525. return h.peek(k)
  1526. }
  1527. // PeekBytes returns header value for the given key.
  1528. //
  1529. // The returned value is valid until the response is released,
  1530. // either though ReleaseResponse or your request handler returning.
  1531. // Do not store references to returned value. Make copies instead.
  1532. func (h *ResponseHeader) PeekBytes(key []byte) []byte {
  1533. h.bufKV.key = append(h.bufKV.key[:0], key...)
  1534. normalizeHeaderKey(h.bufKV.key, h.disableNormalizing)
  1535. return h.peek(h.bufKV.key)
  1536. }
  1537. // Peek returns header value for the given key.
  1538. //
  1539. // The returned value is valid until the request is released,
  1540. // either though ReleaseRequest or your request handler returning.
  1541. // Do not store references to returned value. Make copies instead.
  1542. func (h *RequestHeader) Peek(key string) []byte {
  1543. k := getHeaderKeyBytes(&h.bufKV, key, h.disableNormalizing)
  1544. return h.peek(k)
  1545. }
  1546. // PeekBytes returns header value for the given key.
  1547. //
  1548. // The returned value is valid until the request is released,
  1549. // either though ReleaseRequest or your request handler returning.
  1550. // Do not store references to returned value. Make copies instead.
  1551. func (h *RequestHeader) PeekBytes(key []byte) []byte {
  1552. h.bufKV.key = append(h.bufKV.key[:0], key...)
  1553. normalizeHeaderKey(h.bufKV.key, h.disableNormalizing)
  1554. return h.peek(h.bufKV.key)
  1555. }
  1556. func (h *ResponseHeader) peek(key []byte) []byte {
  1557. switch string(key) {
  1558. case HeaderContentType:
  1559. return h.ContentType()
  1560. case HeaderContentEncoding:
  1561. return h.ContentEncoding()
  1562. case HeaderServer:
  1563. return h.Server()
  1564. case HeaderConnection:
  1565. if h.ConnectionClose() {
  1566. return strClose
  1567. }
  1568. return peekArgBytes(h.h, key)
  1569. case HeaderContentLength:
  1570. return h.contentLengthBytes
  1571. case HeaderSetCookie:
  1572. return appendResponseCookieBytes(nil, h.cookies)
  1573. case HeaderTrailer:
  1574. return appendArgsKeyBytes(nil, h.trailer, strCommaSpace)
  1575. default:
  1576. return peekArgBytes(h.h, key)
  1577. }
  1578. }
  1579. func (h *RequestHeader) peek(key []byte) []byte {
  1580. switch string(key) {
  1581. case HeaderHost:
  1582. return h.Host()
  1583. case HeaderContentType:
  1584. return h.ContentType()
  1585. case HeaderUserAgent:
  1586. return h.UserAgent()
  1587. case HeaderConnection:
  1588. if h.ConnectionClose() {
  1589. return strClose
  1590. }
  1591. return peekArgBytes(h.h, key)
  1592. case HeaderContentLength:
  1593. return h.contentLengthBytes
  1594. case HeaderCookie:
  1595. if h.cookiesCollected {
  1596. return appendRequestCookieBytes(nil, h.cookies)
  1597. }
  1598. return peekArgBytes(h.h, key)
  1599. case HeaderTrailer:
  1600. return appendArgsKeyBytes(nil, h.trailer, strCommaSpace)
  1601. default:
  1602. return peekArgBytes(h.h, key)
  1603. }
  1604. }
  1605. // PeekAll returns all header value for the given key.
  1606. //
  1607. // The returned value is valid until the request is released,
  1608. // either though ReleaseRequest or your request handler returning.
  1609. // Any future calls to the Peek* will modify the returned value.
  1610. // Do not store references to returned value. Make copies instead.
  1611. func (h *RequestHeader) PeekAll(key string) [][]byte {
  1612. k := getHeaderKeyBytes(&h.bufKV, key, h.disableNormalizing)
  1613. return h.peekAll(k)
  1614. }
  1615. func (h *RequestHeader) peekAll(key []byte) [][]byte {
  1616. h.mulHeader = h.mulHeader[:0]
  1617. switch string(key) {
  1618. case HeaderHost:
  1619. if host := h.Host(); len(host) > 0 {
  1620. h.mulHeader = append(h.mulHeader, host)
  1621. }
  1622. case HeaderContentType:
  1623. if contentType := h.ContentType(); len(contentType) > 0 {
  1624. h.mulHeader = append(h.mulHeader, contentType)
  1625. }
  1626. case HeaderUserAgent:
  1627. if ua := h.UserAgent(); len(ua) > 0 {
  1628. h.mulHeader = append(h.mulHeader, ua)
  1629. }
  1630. case HeaderConnection:
  1631. if h.ConnectionClose() {
  1632. h.mulHeader = append(h.mulHeader, strClose)
  1633. } else {
  1634. h.mulHeader = peekAllArgBytesToDst(h.mulHeader, h.h, key)
  1635. }
  1636. case HeaderContentLength:
  1637. h.mulHeader = append(h.mulHeader, h.contentLengthBytes)
  1638. case HeaderCookie:
  1639. if h.cookiesCollected {
  1640. h.mulHeader = append(h.mulHeader, appendRequestCookieBytes(nil, h.cookies))
  1641. } else {
  1642. h.mulHeader = peekAllArgBytesToDst(h.mulHeader, h.h, key)
  1643. }
  1644. case HeaderTrailer:
  1645. h.mulHeader = append(h.mulHeader, appendArgsKeyBytes(nil, h.trailer, strCommaSpace))
  1646. default:
  1647. h.mulHeader = peekAllArgBytesToDst(h.mulHeader, h.h, key)
  1648. }
  1649. return h.mulHeader
  1650. }
  1651. // PeekAll returns all header value for the given key.
  1652. //
  1653. // The returned value is valid until the request is released,
  1654. // either though ReleaseResponse or your request handler returning.
  1655. // Any future calls to the Peek* will modify the returned value.
  1656. // Do not store references to returned value. Make copies instead.
  1657. func (h *ResponseHeader) PeekAll(key string) [][]byte {
  1658. k := getHeaderKeyBytes(&h.bufKV, key, h.disableNormalizing)
  1659. return h.peekAll(k)
  1660. }
  1661. func (h *ResponseHeader) peekAll(key []byte) [][]byte {
  1662. h.mulHeader = h.mulHeader[:0]
  1663. switch string(key) {
  1664. case HeaderContentType:
  1665. if contentType := h.ContentType(); len(contentType) > 0 {
  1666. h.mulHeader = append(h.mulHeader, contentType)
  1667. }
  1668. case HeaderContentEncoding:
  1669. if contentEncoding := h.ContentEncoding(); len(contentEncoding) > 0 {
  1670. h.mulHeader = append(h.mulHeader, contentEncoding)
  1671. }
  1672. case HeaderServer:
  1673. if server := h.Server(); len(server) > 0 {
  1674. h.mulHeader = append(h.mulHeader, server)
  1675. }
  1676. case HeaderConnection:
  1677. if h.ConnectionClose() {
  1678. h.mulHeader = append(h.mulHeader, strClose)
  1679. } else {
  1680. h.mulHeader = peekAllArgBytesToDst(h.mulHeader, h.h, key)
  1681. }
  1682. case HeaderContentLength:
  1683. h.mulHeader = append(h.mulHeader, h.contentLengthBytes)
  1684. case HeaderSetCookie:
  1685. h.mulHeader = append(h.mulHeader, appendResponseCookieBytes(nil, h.cookies))
  1686. case HeaderTrailer:
  1687. h.mulHeader = append(h.mulHeader, appendArgsKeyBytes(nil, h.trailer, strCommaSpace))
  1688. default:
  1689. h.mulHeader = peekAllArgBytesToDst(h.mulHeader, h.h, key)
  1690. }
  1691. return h.mulHeader
  1692. }
  1693. // PeekKeys return all header keys.
  1694. //
  1695. // The returned value is valid until the request is released,
  1696. // either though ReleaseRequest or your request handler returning.
  1697. // Any future calls to the Peek* will modify the returned value.
  1698. // Do not store references to returned value. Make copies instead.
  1699. func (h *RequestHeader) PeekKeys() [][]byte {
  1700. h.mulHeader = h.mulHeader[:0]
  1701. h.mulHeader = peekArgsKeys(h.mulHeader, h.h)
  1702. return h.mulHeader
  1703. }
  1704. // PeekTrailerKeys return all trailer keys.
  1705. //
  1706. // The returned value is valid until the request is released,
  1707. // either though ReleaseRequest or your request handler returning.
  1708. // Any future calls to the Peek* will modify the returned value.
  1709. // Do not store references to returned value. Make copies instead.
  1710. func (h *RequestHeader) PeekTrailerKeys() [][]byte {
  1711. h.mulHeader = h.mulHeader[:0]
  1712. h.mulHeader = peekArgsKeys(h.mulHeader, h.trailer)
  1713. return h.mulHeader
  1714. }
  1715. // PeekKeys return all header keys.
  1716. //
  1717. // The returned value is valid until the request is released,
  1718. // either though ReleaseResponse or your request handler returning.
  1719. // Any future calls to the Peek* will modify the returned value.
  1720. // Do not store references to returned value. Make copies instead.
  1721. func (h *ResponseHeader) PeekKeys() [][]byte {
  1722. h.mulHeader = h.mulHeader[:0]
  1723. h.mulHeader = peekArgsKeys(h.mulHeader, h.h)
  1724. return h.mulHeader
  1725. }
  1726. // PeekTrailerKeys return all trailer keys.
  1727. //
  1728. // The returned value is valid until the request is released,
  1729. // either though ReleaseResponse or your request handler returning.
  1730. // Any future calls to the Peek* will modify the returned value.
  1731. // Do not store references to returned value. Make copies instead.
  1732. func (h *ResponseHeader) PeekTrailerKeys() [][]byte {
  1733. h.mulHeader = h.mulHeader[:0]
  1734. h.mulHeader = peekArgsKeys(h.mulHeader, h.trailer)
  1735. return h.mulHeader
  1736. }
  1737. // Cookie returns cookie for the given key.
  1738. func (h *RequestHeader) Cookie(key string) []byte {
  1739. h.collectCookies()
  1740. return peekArgStr(h.cookies, key)
  1741. }
  1742. // CookieBytes returns cookie for the given key.
  1743. func (h *RequestHeader) CookieBytes(key []byte) []byte {
  1744. h.collectCookies()
  1745. return peekArgBytes(h.cookies, key)
  1746. }
  1747. // Cookie fills cookie for the given cookie.Key.
  1748. //
  1749. // Returns false if cookie with the given cookie.Key is missing.
  1750. func (h *ResponseHeader) Cookie(cookie *Cookie) bool {
  1751. v := peekArgBytes(h.cookies, cookie.Key())
  1752. if v == nil {
  1753. return false
  1754. }
  1755. cookie.ParseBytes(v) //nolint:errcheck
  1756. return true
  1757. }
  1758. // Read reads response header from r.
  1759. //
  1760. // io.EOF is returned if r is closed before reading the first header byte.
  1761. func (h *ResponseHeader) Read(r *bufio.Reader) error {
  1762. n := 1
  1763. for {
  1764. err := h.tryRead(r, n)
  1765. if err == nil {
  1766. return nil
  1767. }
  1768. if err != errNeedMore {
  1769. h.resetSkipNormalize()
  1770. return err
  1771. }
  1772. n = r.Buffered() + 1
  1773. }
  1774. }
  1775. func (h *ResponseHeader) tryRead(r *bufio.Reader, n int) error {
  1776. h.resetSkipNormalize()
  1777. b, err := r.Peek(n)
  1778. if len(b) == 0 {
  1779. // Return ErrTimeout on any timeout.
  1780. if x, ok := err.(interface{ Timeout() bool }); ok && x.Timeout() {
  1781. return ErrTimeout
  1782. }
  1783. // treat all other errors on the first byte read as EOF
  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 headers"),
  1792. }
  1793. }
  1794. return &ErrSmallBuffer{
  1795. error: fmt.Errorf("error when reading response headers: %w", errSmallBuffer),
  1796. }
  1797. }
  1798. return fmt.Errorf("error when reading response headers: %w", err)
  1799. }
  1800. b = mustPeekBuffered(r)
  1801. headersLen, errParse := h.parse(b)
  1802. if errParse != nil {
  1803. return headerError("response", err, errParse, b, h.secureErrorLogMessage)
  1804. }
  1805. mustDiscard(r, headersLen)
  1806. return nil
  1807. }
  1808. // ReadTrailer reads response trailer header from r.
  1809. //
  1810. // io.EOF is returned if r is closed before reading the first byte.
  1811. func (h *ResponseHeader) ReadTrailer(r *bufio.Reader) error {
  1812. n := 1
  1813. for {
  1814. err := h.tryReadTrailer(r, n)
  1815. if err == nil {
  1816. return nil
  1817. }
  1818. if err != errNeedMore {
  1819. return err
  1820. }
  1821. n = r.Buffered() + 1
  1822. }
  1823. }
  1824. func (h *ResponseHeader) tryReadTrailer(r *bufio.Reader, n int) error {
  1825. b, err := r.Peek(n)
  1826. if len(b) == 0 {
  1827. // Return ErrTimeout on any timeout.
  1828. if x, ok := err.(interface{ Timeout() bool }); ok && x.Timeout() {
  1829. return ErrTimeout
  1830. }
  1831. if n == 1 || err == io.EOF {
  1832. return io.EOF
  1833. }
  1834. // This is for go 1.6 bug. See https://github.com/golang/go/issues/14121 .
  1835. if err == bufio.ErrBufferFull {
  1836. if h.secureErrorLogMessage {
  1837. return &ErrSmallBuffer{
  1838. error: fmt.Errorf("error when reading response trailer"),
  1839. }
  1840. }
  1841. return &ErrSmallBuffer{
  1842. error: fmt.Errorf("error when reading response trailer: %w", errSmallBuffer),
  1843. }
  1844. }
  1845. return fmt.Errorf("error when reading response trailer: %w", err)
  1846. }
  1847. b = mustPeekBuffered(r)
  1848. headersLen, errParse := h.parseTrailer(b)
  1849. if errParse != nil {
  1850. if err == io.EOF {
  1851. return err
  1852. }
  1853. return headerError("response", err, errParse, b, h.secureErrorLogMessage)
  1854. }
  1855. mustDiscard(r, headersLen)
  1856. return nil
  1857. }
  1858. func headerError(typ string, err, errParse error, b []byte, secureErrorLogMessage bool) error {
  1859. if errParse != errNeedMore {
  1860. return headerErrorMsg(typ, errParse, b, secureErrorLogMessage)
  1861. }
  1862. if err == nil {
  1863. return errNeedMore
  1864. }
  1865. // Buggy servers may leave trailing CRLFs after http body.
  1866. // Treat this case as EOF.
  1867. if isOnlyCRLF(b) {
  1868. return io.EOF
  1869. }
  1870. if err != bufio.ErrBufferFull {
  1871. return headerErrorMsg(typ, err, b, secureErrorLogMessage)
  1872. }
  1873. return &ErrSmallBuffer{
  1874. error: headerErrorMsg(typ, errSmallBuffer, b, secureErrorLogMessage),
  1875. }
  1876. }
  1877. func headerErrorMsg(typ string, err error, b []byte, secureErrorLogMessage bool) error {
  1878. if secureErrorLogMessage {
  1879. return fmt.Errorf("error when reading %s headers: %w. Buffer size=%d", typ, err, len(b))
  1880. }
  1881. return fmt.Errorf("error when reading %s headers: %w. Buffer size=%d, contents: %s", typ, err, len(b), bufferSnippet(b))
  1882. }
  1883. // Read reads request header from r.
  1884. //
  1885. // io.EOF is returned if r is closed before reading the first header byte.
  1886. func (h *RequestHeader) Read(r *bufio.Reader) error {
  1887. return h.readLoop(r, true)
  1888. }
  1889. // readLoop reads request header from r optionally loops until it has enough data.
  1890. //
  1891. // io.EOF is returned if r is closed before reading the first header byte.
  1892. func (h *RequestHeader) readLoop(r *bufio.Reader, waitForMore bool) error {
  1893. n := 1
  1894. for {
  1895. err := h.tryRead(r, n)
  1896. if err == nil {
  1897. return nil
  1898. }
  1899. if !waitForMore || err != errNeedMore {
  1900. h.resetSkipNormalize()
  1901. return err
  1902. }
  1903. n = r.Buffered() + 1
  1904. }
  1905. }
  1906. // ReadTrailer reads request trailer header from r.
  1907. //
  1908. // io.EOF is returned if r is closed before reading the first byte.
  1909. func (h *RequestHeader) ReadTrailer(r *bufio.Reader) error {
  1910. n := 1
  1911. for {
  1912. err := h.tryReadTrailer(r, n)
  1913. if err == nil {
  1914. return nil
  1915. }
  1916. if err != errNeedMore {
  1917. return err
  1918. }
  1919. n = r.Buffered() + 1
  1920. }
  1921. }
  1922. func (h *RequestHeader) tryReadTrailer(r *bufio.Reader, n int) error {
  1923. b, err := r.Peek(n)
  1924. if len(b) == 0 {
  1925. // Return ErrTimeout on any timeout.
  1926. if x, ok := err.(interface{ Timeout() bool }); ok && x.Timeout() {
  1927. return ErrTimeout
  1928. }
  1929. if n == 1 || err == io.EOF {
  1930. return io.EOF
  1931. }
  1932. // This is for go 1.6 bug. See https://github.com/golang/go/issues/14121 .
  1933. if err == bufio.ErrBufferFull {
  1934. if h.secureErrorLogMessage {
  1935. return &ErrSmallBuffer{
  1936. error: fmt.Errorf("error when reading request trailer"),
  1937. }
  1938. }
  1939. return &ErrSmallBuffer{
  1940. error: fmt.Errorf("error when reading request trailer: %w", errSmallBuffer),
  1941. }
  1942. }
  1943. return fmt.Errorf("error when reading request trailer: %w", err)
  1944. }
  1945. b = mustPeekBuffered(r)
  1946. headersLen, errParse := h.parseTrailer(b)
  1947. if errParse != nil {
  1948. if err == io.EOF {
  1949. return err
  1950. }
  1951. return headerError("request", err, errParse, b, h.secureErrorLogMessage)
  1952. }
  1953. mustDiscard(r, headersLen)
  1954. return nil
  1955. }
  1956. func (h *RequestHeader) tryRead(r *bufio.Reader, n int) error {
  1957. h.resetSkipNormalize()
  1958. b, err := r.Peek(n)
  1959. if len(b) == 0 {
  1960. if err == io.EOF {
  1961. return err
  1962. }
  1963. if err == nil {
  1964. panic("bufio.Reader.Peek() returned nil, nil")
  1965. }
  1966. // This is for go 1.6 bug. See https://github.com/golang/go/issues/14121 .
  1967. if err == bufio.ErrBufferFull {
  1968. return &ErrSmallBuffer{
  1969. error: fmt.Errorf("error when reading request headers: %w (n=%d, r.Buffered()=%d)", errSmallBuffer, n, r.Buffered()),
  1970. }
  1971. }
  1972. // n == 1 on the first read for the request.
  1973. if n == 1 {
  1974. // We didn't read a single byte.
  1975. return ErrNothingRead{err}
  1976. }
  1977. return fmt.Errorf("error when reading request headers: %w", err)
  1978. }
  1979. b = mustPeekBuffered(r)
  1980. headersLen, errParse := h.parse(b)
  1981. if errParse != nil {
  1982. return headerError("request", err, errParse, b, h.secureErrorLogMessage)
  1983. }
  1984. mustDiscard(r, headersLen)
  1985. return nil
  1986. }
  1987. func bufferSnippet(b []byte) string {
  1988. n := len(b)
  1989. start := 200
  1990. end := n - start
  1991. if start >= end {
  1992. start = n
  1993. end = n
  1994. }
  1995. bStart, bEnd := b[:start], b[end:]
  1996. if len(bEnd) == 0 {
  1997. return fmt.Sprintf("%q", b)
  1998. }
  1999. return fmt.Sprintf("%q...%q", bStart, bEnd)
  2000. }
  2001. func isOnlyCRLF(b []byte) bool {
  2002. for _, ch := range b {
  2003. if ch != rChar && ch != nChar {
  2004. return false
  2005. }
  2006. }
  2007. return true
  2008. }
  2009. func updateServerDate() {
  2010. refreshServerDate()
  2011. go func() {
  2012. for {
  2013. time.Sleep(time.Second)
  2014. refreshServerDate()
  2015. }
  2016. }()
  2017. }
  2018. var (
  2019. serverDate atomic.Value
  2020. serverDateOnce sync.Once // serverDateOnce.Do(updateServerDate)
  2021. )
  2022. func refreshServerDate() {
  2023. b := AppendHTTPDate(nil, time.Now())
  2024. serverDate.Store(b)
  2025. }
  2026. // Write writes response header to w.
  2027. func (h *ResponseHeader) Write(w *bufio.Writer) error {
  2028. _, err := w.Write(h.Header())
  2029. return err
  2030. }
  2031. // WriteTo writes response header to w.
  2032. //
  2033. // WriteTo implements io.WriterTo interface.
  2034. func (h *ResponseHeader) WriteTo(w io.Writer) (int64, error) {
  2035. n, err := w.Write(h.Header())
  2036. return int64(n), err
  2037. }
  2038. // Header returns response header representation.
  2039. //
  2040. // Headers that set as Trailer will not represent. Use TrailerHeader for trailers.
  2041. //
  2042. // The returned value is valid until the request is released,
  2043. // either though ReleaseRequest or your request handler returning.
  2044. // Do not store references to returned value. Make copies instead.
  2045. func (h *ResponseHeader) Header() []byte {
  2046. h.bufKV.value = h.AppendBytes(h.bufKV.value[:0])
  2047. return h.bufKV.value
  2048. }
  2049. // writeTrailer writes response trailer to w.
  2050. func (h *ResponseHeader) writeTrailer(w *bufio.Writer) error {
  2051. _, err := w.Write(h.TrailerHeader())
  2052. return err
  2053. }
  2054. // TrailerHeader returns response trailer header representation.
  2055. //
  2056. // Trailers will only be received with chunked transfer.
  2057. //
  2058. // The returned value is valid until the request is released,
  2059. // either though ReleaseRequest or your request handler returning.
  2060. // Do not store references to returned value. Make copies instead.
  2061. func (h *ResponseHeader) TrailerHeader() []byte {
  2062. h.bufKV.value = h.bufKV.value[:0]
  2063. for _, t := range h.trailer {
  2064. value := h.peek(t.key)
  2065. h.bufKV.value = appendHeaderLine(h.bufKV.value, t.key, value)
  2066. }
  2067. h.bufKV.value = append(h.bufKV.value, strCRLF...)
  2068. return h.bufKV.value
  2069. }
  2070. // String returns response header representation.
  2071. func (h *ResponseHeader) String() string {
  2072. return string(h.Header())
  2073. }
  2074. // appendStatusLine appends the response status line to dst and returns
  2075. // the extended dst.
  2076. func (h *ResponseHeader) appendStatusLine(dst []byte) []byte {
  2077. statusCode := h.StatusCode()
  2078. if statusCode < 0 {
  2079. statusCode = StatusOK
  2080. }
  2081. return formatStatusLine(dst, h.Protocol(), statusCode, h.StatusMessage())
  2082. }
  2083. // AppendBytes appends response header representation to dst and returns
  2084. // the extended dst.
  2085. func (h *ResponseHeader) AppendBytes(dst []byte) []byte {
  2086. dst = h.appendStatusLine(dst[:0])
  2087. server := h.Server()
  2088. if len(server) != 0 {
  2089. dst = appendHeaderLine(dst, strServer, server)
  2090. }
  2091. if !h.noDefaultDate {
  2092. serverDateOnce.Do(updateServerDate)
  2093. dst = appendHeaderLine(dst, strDate, serverDate.Load().([]byte))
  2094. }
  2095. // Append Content-Type only for non-zero responses
  2096. // or if it is explicitly set.
  2097. // See https://github.com/valyala/fasthttp/issues/28 .
  2098. if h.ContentLength() != 0 || len(h.contentType) > 0 {
  2099. contentType := h.ContentType()
  2100. if len(contentType) > 0 {
  2101. dst = appendHeaderLine(dst, strContentType, contentType)
  2102. }
  2103. }
  2104. contentEncoding := h.ContentEncoding()
  2105. if len(contentEncoding) > 0 {
  2106. dst = appendHeaderLine(dst, strContentEncoding, contentEncoding)
  2107. }
  2108. if len(h.contentLengthBytes) > 0 {
  2109. dst = appendHeaderLine(dst, strContentLength, h.contentLengthBytes)
  2110. }
  2111. for i, n := 0, len(h.h); i < n; i++ {
  2112. kv := &h.h[i]
  2113. // Exclude trailer from header
  2114. exclude := false
  2115. for _, t := range h.trailer {
  2116. if bytes.Equal(kv.key, t.key) {
  2117. exclude = true
  2118. break
  2119. }
  2120. }
  2121. if !exclude && (h.noDefaultDate || !bytes.Equal(kv.key, strDate)) {
  2122. dst = appendHeaderLine(dst, kv.key, kv.value)
  2123. }
  2124. }
  2125. if len(h.trailer) > 0 {
  2126. dst = appendHeaderLine(dst, strTrailer, appendArgsKeyBytes(nil, h.trailer, strCommaSpace))
  2127. }
  2128. n := len(h.cookies)
  2129. if n > 0 {
  2130. for i := 0; i < n; i++ {
  2131. kv := &h.cookies[i]
  2132. dst = appendHeaderLine(dst, strSetCookie, kv.value)
  2133. }
  2134. }
  2135. if h.ConnectionClose() {
  2136. dst = appendHeaderLine(dst, strConnection, strClose)
  2137. }
  2138. return append(dst, strCRLF...)
  2139. }
  2140. // Write writes request header to w.
  2141. func (h *RequestHeader) Write(w *bufio.Writer) error {
  2142. _, err := w.Write(h.Header())
  2143. return err
  2144. }
  2145. // WriteTo writes request header to w.
  2146. //
  2147. // WriteTo implements io.WriterTo interface.
  2148. func (h *RequestHeader) WriteTo(w io.Writer) (int64, error) {
  2149. n, err := w.Write(h.Header())
  2150. return int64(n), err
  2151. }
  2152. // Header returns request header representation.
  2153. //
  2154. // Headers that set as Trailer will not represent. Use TrailerHeader for trailers.
  2155. //
  2156. // The returned value is valid until the request is released,
  2157. // either though ReleaseRequest or your request handler returning.
  2158. // Do not store references to returned value. Make copies instead.
  2159. func (h *RequestHeader) Header() []byte {
  2160. h.bufKV.value = h.AppendBytes(h.bufKV.value[:0])
  2161. return h.bufKV.value
  2162. }
  2163. // writeTrailer writes request trailer to w.
  2164. func (h *RequestHeader) writeTrailer(w *bufio.Writer) error {
  2165. _, err := w.Write(h.TrailerHeader())
  2166. return err
  2167. }
  2168. // TrailerHeader returns request trailer header representation.
  2169. //
  2170. // Trailers will only be received with chunked transfer.
  2171. //
  2172. // The returned value is valid until the request is released,
  2173. // either though ReleaseRequest or your request handler returning.
  2174. // Do not store references to returned value. Make copies instead.
  2175. func (h *RequestHeader) TrailerHeader() []byte {
  2176. h.bufKV.value = h.bufKV.value[:0]
  2177. for _, t := range h.trailer {
  2178. value := h.peek(t.key)
  2179. h.bufKV.value = appendHeaderLine(h.bufKV.value, t.key, value)
  2180. }
  2181. h.bufKV.value = append(h.bufKV.value, strCRLF...)
  2182. return h.bufKV.value
  2183. }
  2184. // RawHeaders returns raw header key/value bytes.
  2185. //
  2186. // Depending on server configuration, header keys may be normalized to
  2187. // capital-case in place.
  2188. //
  2189. // This copy is set aside during parsing, so empty slice is returned for all
  2190. // cases where parsing did not happen. Similarly, request line is not stored
  2191. // during parsing and can not be returned.
  2192. //
  2193. // The slice is not safe to use after the handler returns.
  2194. func (h *RequestHeader) RawHeaders() []byte {
  2195. return h.rawHeaders
  2196. }
  2197. // String returns request header representation.
  2198. func (h *RequestHeader) String() string {
  2199. return string(h.Header())
  2200. }
  2201. // AppendBytes appends request header representation to dst and returns
  2202. // the extended dst.
  2203. func (h *RequestHeader) AppendBytes(dst []byte) []byte {
  2204. dst = append(dst, h.Method()...)
  2205. dst = append(dst, ' ')
  2206. dst = append(dst, h.RequestURI()...)
  2207. dst = append(dst, ' ')
  2208. dst = append(dst, h.Protocol()...)
  2209. dst = append(dst, strCRLF...)
  2210. userAgent := h.UserAgent()
  2211. if len(userAgent) > 0 {
  2212. dst = appendHeaderLine(dst, strUserAgent, userAgent)
  2213. }
  2214. host := h.Host()
  2215. if len(host) > 0 {
  2216. dst = appendHeaderLine(dst, strHost, host)
  2217. }
  2218. contentType := h.ContentType()
  2219. if !h.noDefaultContentType && len(contentType) == 0 && !h.ignoreBody() {
  2220. contentType = strDefaultContentType
  2221. }
  2222. if len(contentType) > 0 {
  2223. dst = appendHeaderLine(dst, strContentType, contentType)
  2224. }
  2225. if len(h.contentLengthBytes) > 0 {
  2226. dst = appendHeaderLine(dst, strContentLength, h.contentLengthBytes)
  2227. }
  2228. for i, n := 0, len(h.h); i < n; i++ {
  2229. kv := &h.h[i]
  2230. // Exclude trailer from header
  2231. exclude := false
  2232. for _, t := range h.trailer {
  2233. if bytes.Equal(kv.key, t.key) {
  2234. exclude = true
  2235. break
  2236. }
  2237. }
  2238. if !exclude {
  2239. dst = appendHeaderLine(dst, kv.key, kv.value)
  2240. }
  2241. }
  2242. if len(h.trailer) > 0 {
  2243. dst = appendHeaderLine(dst, strTrailer, appendArgsKeyBytes(nil, h.trailer, strCommaSpace))
  2244. }
  2245. // there is no need in h.collectCookies() here, since if cookies aren't collected yet,
  2246. // they all are located in h.h.
  2247. n := len(h.cookies)
  2248. if n > 0 {
  2249. dst = append(dst, strCookie...)
  2250. dst = append(dst, strColonSpace...)
  2251. dst = appendRequestCookieBytes(dst, h.cookies)
  2252. dst = append(dst, strCRLF...)
  2253. }
  2254. if h.ConnectionClose() {
  2255. dst = appendHeaderLine(dst, strConnection, strClose)
  2256. }
  2257. return append(dst, strCRLF...)
  2258. }
  2259. func appendHeaderLine(dst, key, value []byte) []byte {
  2260. dst = append(dst, key...)
  2261. dst = append(dst, strColonSpace...)
  2262. dst = append(dst, value...)
  2263. return append(dst, strCRLF...)
  2264. }
  2265. func (h *ResponseHeader) parse(buf []byte) (int, error) {
  2266. m, err := h.parseFirstLine(buf)
  2267. if err != nil {
  2268. return 0, err
  2269. }
  2270. n, err := h.parseHeaders(buf[m:])
  2271. if err != nil {
  2272. return 0, err
  2273. }
  2274. return m + n, nil
  2275. }
  2276. func (h *ResponseHeader) parseTrailer(buf []byte) (int, error) {
  2277. // Skip any 0 length chunk.
  2278. if buf[0] == '0' {
  2279. skip := len(strCRLF) + 1
  2280. if len(buf) < skip {
  2281. return 0, io.EOF
  2282. }
  2283. buf = buf[skip:]
  2284. }
  2285. var s headerScanner
  2286. s.b = buf
  2287. s.disableNormalizing = h.disableNormalizing
  2288. var err error
  2289. for s.next() {
  2290. if len(s.key) > 0 {
  2291. if bytes.IndexByte(s.key, ' ') != -1 || bytes.IndexByte(s.key, '\t') != -1 {
  2292. err = fmt.Errorf("invalid trailer key %q", s.key)
  2293. continue
  2294. }
  2295. // Forbidden by RFC 7230, section 4.1.2
  2296. if isBadTrailer(s.key) {
  2297. err = fmt.Errorf("forbidden trailer key %q", s.key)
  2298. continue
  2299. }
  2300. h.h = appendArgBytes(h.h, s.key, s.value, argsHasValue)
  2301. }
  2302. }
  2303. if s.err != nil {
  2304. return 0, s.err
  2305. }
  2306. if err != nil {
  2307. return 0, err
  2308. }
  2309. return s.hLen, nil
  2310. }
  2311. func (h *RequestHeader) ignoreBody() bool {
  2312. return h.IsGet() || h.IsHead()
  2313. }
  2314. func (h *RequestHeader) parse(buf []byte) (int, error) {
  2315. m, err := h.parseFirstLine(buf)
  2316. if err != nil {
  2317. return 0, err
  2318. }
  2319. h.rawHeaders, _, err = readRawHeaders(h.rawHeaders[:0], buf[m:])
  2320. if err != nil {
  2321. return 0, err
  2322. }
  2323. var n int
  2324. n, err = h.parseHeaders(buf[m:])
  2325. if err != nil {
  2326. return 0, err
  2327. }
  2328. return m + n, nil
  2329. }
  2330. func (h *RequestHeader) parseTrailer(buf []byte) (int, error) {
  2331. // Skip any 0 length chunk.
  2332. if buf[0] == '0' {
  2333. skip := len(strCRLF) + 1
  2334. if len(buf) < skip {
  2335. return 0, io.EOF
  2336. }
  2337. buf = buf[skip:]
  2338. }
  2339. var s headerScanner
  2340. s.b = buf
  2341. s.disableNormalizing = h.disableNormalizing
  2342. var err error
  2343. for s.next() {
  2344. if len(s.key) > 0 {
  2345. if bytes.IndexByte(s.key, ' ') != -1 || bytes.IndexByte(s.key, '\t') != -1 {
  2346. err = fmt.Errorf("invalid trailer key %q", s.key)
  2347. continue
  2348. }
  2349. // Forbidden by RFC 7230, section 4.1.2
  2350. if isBadTrailer(s.key) {
  2351. err = fmt.Errorf("forbidden trailer key %q", s.key)
  2352. continue
  2353. }
  2354. h.h = appendArgBytes(h.h, s.key, s.value, argsHasValue)
  2355. }
  2356. }
  2357. if s.err != nil {
  2358. return 0, s.err
  2359. }
  2360. if err != nil {
  2361. return 0, err
  2362. }
  2363. return s.hLen, nil
  2364. }
  2365. func isBadTrailer(key []byte) bool {
  2366. if len(key) == 0 {
  2367. return true
  2368. }
  2369. switch key[0] | 0x20 {
  2370. case 'a':
  2371. return caseInsensitiveCompare(key, strAuthorization)
  2372. case 'c':
  2373. if len(key) > len(HeaderContentType) && caseInsensitiveCompare(key[:8], strContentType[:8]) {
  2374. // skip compare prefix 'Content-'
  2375. return caseInsensitiveCompare(key[8:], strContentEncoding[8:]) ||
  2376. caseInsensitiveCompare(key[8:], strContentLength[8:]) ||
  2377. caseInsensitiveCompare(key[8:], strContentType[8:]) ||
  2378. caseInsensitiveCompare(key[8:], strContentRange[8:])
  2379. }
  2380. return caseInsensitiveCompare(key, strConnection)
  2381. case 'e':
  2382. return caseInsensitiveCompare(key, strExpect)
  2383. case 'h':
  2384. return caseInsensitiveCompare(key, strHost)
  2385. case 'k':
  2386. return caseInsensitiveCompare(key, strKeepAlive)
  2387. case 'm':
  2388. return caseInsensitiveCompare(key, strMaxForwards)
  2389. case 'p':
  2390. if len(key) > len(HeaderProxyConnection) && caseInsensitiveCompare(key[:6], strProxyConnection[:6]) {
  2391. // skip compare prefix 'Proxy-'
  2392. return caseInsensitiveCompare(key[6:], strProxyConnection[6:]) ||
  2393. caseInsensitiveCompare(key[6:], strProxyAuthenticate[6:]) ||
  2394. caseInsensitiveCompare(key[6:], strProxyAuthorization[6:])
  2395. }
  2396. case 'r':
  2397. return caseInsensitiveCompare(key, strRange)
  2398. case 't':
  2399. return caseInsensitiveCompare(key, strTE) ||
  2400. caseInsensitiveCompare(key, strTrailer) ||
  2401. caseInsensitiveCompare(key, strTransferEncoding)
  2402. case 'w':
  2403. return caseInsensitiveCompare(key, strWWWAuthenticate)
  2404. }
  2405. return false
  2406. }
  2407. func (h *ResponseHeader) parseFirstLine(buf []byte) (int, error) {
  2408. bNext := buf
  2409. var b []byte
  2410. var err error
  2411. for len(b) == 0 {
  2412. if b, bNext, err = nextLine(bNext); err != nil {
  2413. return 0, err
  2414. }
  2415. }
  2416. // parse protocol
  2417. n := bytes.IndexByte(b, ' ')
  2418. if n < 0 {
  2419. if h.secureErrorLogMessage {
  2420. return 0, fmt.Errorf("cannot find whitespace in the first line of response")
  2421. }
  2422. return 0, fmt.Errorf("cannot find whitespace in the first line of response %q", buf)
  2423. }
  2424. h.noHTTP11 = !bytes.Equal(b[:n], strHTTP11)
  2425. b = b[n+1:]
  2426. // parse status code
  2427. h.statusCode, n, err = parseUintBuf(b)
  2428. if err != nil {
  2429. if h.secureErrorLogMessage {
  2430. return 0, fmt.Errorf("cannot parse response status code: %w", err)
  2431. }
  2432. return 0, fmt.Errorf("cannot parse response status code: %w. Response %q", err, buf)
  2433. }
  2434. if len(b) > n && b[n] != ' ' {
  2435. if h.secureErrorLogMessage {
  2436. return 0, fmt.Errorf("unexpected char at the end of status code")
  2437. }
  2438. return 0, fmt.Errorf("unexpected char at the end of status code. Response %q", buf)
  2439. }
  2440. if len(b) > n+1 {
  2441. h.SetStatusMessage(b[n+1:])
  2442. }
  2443. return len(buf) - len(bNext), nil
  2444. }
  2445. func (h *RequestHeader) parseFirstLine(buf []byte) (int, error) {
  2446. bNext := buf
  2447. var b []byte
  2448. var err error
  2449. for len(b) == 0 {
  2450. if b, bNext, err = nextLine(bNext); err != nil {
  2451. return 0, err
  2452. }
  2453. }
  2454. // parse method
  2455. n := bytes.IndexByte(b, ' ')
  2456. if n <= 0 {
  2457. if h.secureErrorLogMessage {
  2458. return 0, fmt.Errorf("cannot find http request method")
  2459. }
  2460. return 0, fmt.Errorf("cannot find http request method in %q", buf)
  2461. }
  2462. h.method = append(h.method[:0], b[:n]...)
  2463. b = b[n+1:]
  2464. protoStr := strHTTP11
  2465. // parse requestURI
  2466. n = bytes.LastIndexByte(b, ' ')
  2467. if n < 0 {
  2468. h.noHTTP11 = true
  2469. n = len(b)
  2470. protoStr = strHTTP10
  2471. } else if n == 0 {
  2472. if h.secureErrorLogMessage {
  2473. return 0, fmt.Errorf("requestURI cannot be empty")
  2474. }
  2475. return 0, fmt.Errorf("requestURI cannot be empty in %q", buf)
  2476. } else if !bytes.Equal(b[n+1:], strHTTP11) {
  2477. h.noHTTP11 = true
  2478. protoStr = b[n+1:]
  2479. }
  2480. h.proto = append(h.proto[:0], protoStr...)
  2481. h.requestURI = append(h.requestURI[:0], b[:n]...)
  2482. return len(buf) - len(bNext), nil
  2483. }
  2484. func readRawHeaders(dst, buf []byte) ([]byte, int, error) {
  2485. n := bytes.IndexByte(buf, nChar)
  2486. if n < 0 {
  2487. return dst[:0], 0, errNeedMore
  2488. }
  2489. if (n == 1 && buf[0] == rChar) || n == 0 {
  2490. // empty headers
  2491. return dst, n + 1, nil
  2492. }
  2493. n++
  2494. b := buf
  2495. m := n
  2496. for {
  2497. b = b[m:]
  2498. m = bytes.IndexByte(b, nChar)
  2499. if m < 0 {
  2500. return dst, 0, errNeedMore
  2501. }
  2502. m++
  2503. n += m
  2504. if (m == 2 && b[0] == rChar) || m == 1 {
  2505. dst = append(dst, buf[:n]...)
  2506. return dst, n, nil
  2507. }
  2508. }
  2509. }
  2510. func (h *ResponseHeader) parseHeaders(buf []byte) (int, error) {
  2511. // 'identity' content-length by default
  2512. h.contentLength = -2
  2513. var s headerScanner
  2514. s.b = buf
  2515. s.disableNormalizing = h.disableNormalizing
  2516. var err error
  2517. var kv *argsKV
  2518. for s.next() {
  2519. if len(s.key) > 0 {
  2520. switch s.key[0] | 0x20 {
  2521. case 'c':
  2522. if caseInsensitiveCompare(s.key, strContentType) {
  2523. h.contentType = append(h.contentType[:0], s.value...)
  2524. continue
  2525. }
  2526. if caseInsensitiveCompare(s.key, strContentEncoding) {
  2527. h.contentEncoding = append(h.contentEncoding[:0], s.value...)
  2528. continue
  2529. }
  2530. if caseInsensitiveCompare(s.key, strContentLength) {
  2531. if h.contentLength != -1 {
  2532. if h.contentLength, err = parseContentLength(s.value); err != nil {
  2533. h.contentLength = -2
  2534. } else {
  2535. h.contentLengthBytes = append(h.contentLengthBytes[:0], s.value...)
  2536. }
  2537. }
  2538. continue
  2539. }
  2540. if caseInsensitiveCompare(s.key, strConnection) {
  2541. if bytes.Equal(s.value, strClose) {
  2542. h.connectionClose = true
  2543. } else {
  2544. h.connectionClose = false
  2545. h.h = appendArgBytes(h.h, s.key, s.value, argsHasValue)
  2546. }
  2547. continue
  2548. }
  2549. case 's':
  2550. if caseInsensitiveCompare(s.key, strServer) {
  2551. h.server = append(h.server[:0], s.value...)
  2552. continue
  2553. }
  2554. if caseInsensitiveCompare(s.key, strSetCookie) {
  2555. h.cookies, kv = allocArg(h.cookies)
  2556. kv.key = getCookieKey(kv.key, s.value)
  2557. kv.value = append(kv.value[:0], s.value...)
  2558. continue
  2559. }
  2560. case 't':
  2561. if caseInsensitiveCompare(s.key, strTransferEncoding) {
  2562. if len(s.value) > 0 && !bytes.Equal(s.value, strIdentity) {
  2563. h.contentLength = -1
  2564. h.h = setArgBytes(h.h, strTransferEncoding, strChunked, argsHasValue)
  2565. }
  2566. continue
  2567. }
  2568. if caseInsensitiveCompare(s.key, strTrailer) {
  2569. err = h.SetTrailerBytes(s.value)
  2570. continue
  2571. }
  2572. }
  2573. h.h = appendArgBytes(h.h, s.key, s.value, argsHasValue)
  2574. }
  2575. }
  2576. if s.err != nil {
  2577. h.connectionClose = true
  2578. return 0, s.err
  2579. }
  2580. if h.contentLength < 0 {
  2581. h.contentLengthBytes = h.contentLengthBytes[:0]
  2582. }
  2583. if h.contentLength == -2 && !h.ConnectionUpgrade() && !h.mustSkipContentLength() {
  2584. h.h = setArgBytes(h.h, strTransferEncoding, strIdentity, argsHasValue)
  2585. h.connectionClose = true
  2586. }
  2587. if h.noHTTP11 && !h.connectionClose {
  2588. // close connection for non-http/1.1 response unless 'Connection: keep-alive' is set.
  2589. v := peekArgBytes(h.h, strConnection)
  2590. h.connectionClose = !hasHeaderValue(v, strKeepAlive)
  2591. }
  2592. return len(buf) - len(s.b), err
  2593. }
  2594. func (h *RequestHeader) parseHeaders(buf []byte) (int, error) {
  2595. h.contentLength = -2
  2596. var s headerScanner
  2597. s.b = buf
  2598. s.disableNormalizing = h.disableNormalizing
  2599. var err error
  2600. for s.next() {
  2601. if len(s.key) > 0 {
  2602. // Spaces between the header key and colon are not allowed.
  2603. // See RFC 7230, Section 3.2.4.
  2604. if bytes.IndexByte(s.key, ' ') != -1 || bytes.IndexByte(s.key, '\t') != -1 {
  2605. err = fmt.Errorf("invalid header key %q", s.key)
  2606. continue
  2607. }
  2608. switch s.key[0] | 0x20 {
  2609. case 'h':
  2610. if caseInsensitiveCompare(s.key, strHost) {
  2611. h.host = append(h.host[:0], s.value...)
  2612. continue
  2613. }
  2614. case 'u':
  2615. if caseInsensitiveCompare(s.key, strUserAgent) {
  2616. h.userAgent = append(h.userAgent[:0], s.value...)
  2617. continue
  2618. }
  2619. case 'c':
  2620. if caseInsensitiveCompare(s.key, strContentType) {
  2621. h.contentType = append(h.contentType[:0], s.value...)
  2622. continue
  2623. }
  2624. if caseInsensitiveCompare(s.key, strContentLength) {
  2625. if h.contentLength != -1 {
  2626. var nerr error
  2627. if h.contentLength, nerr = parseContentLength(s.value); nerr != nil {
  2628. if err == nil {
  2629. err = nerr
  2630. }
  2631. h.contentLength = -2
  2632. } else {
  2633. h.contentLengthBytes = append(h.contentLengthBytes[:0], s.value...)
  2634. }
  2635. }
  2636. continue
  2637. }
  2638. if caseInsensitiveCompare(s.key, strConnection) {
  2639. if bytes.Equal(s.value, strClose) {
  2640. h.connectionClose = true
  2641. } else {
  2642. h.connectionClose = false
  2643. h.h = appendArgBytes(h.h, s.key, s.value, argsHasValue)
  2644. }
  2645. continue
  2646. }
  2647. case 't':
  2648. if caseInsensitiveCompare(s.key, strTransferEncoding) {
  2649. if !bytes.Equal(s.value, strIdentity) {
  2650. h.contentLength = -1
  2651. h.h = setArgBytes(h.h, strTransferEncoding, strChunked, argsHasValue)
  2652. }
  2653. continue
  2654. }
  2655. if caseInsensitiveCompare(s.key, strTrailer) {
  2656. if nerr := h.SetTrailerBytes(s.value); nerr != nil {
  2657. if err == nil {
  2658. err = nerr
  2659. }
  2660. }
  2661. continue
  2662. }
  2663. }
  2664. }
  2665. h.h = appendArgBytes(h.h, s.key, s.value, argsHasValue)
  2666. }
  2667. if s.err != nil && err == nil {
  2668. err = s.err
  2669. }
  2670. if err != nil {
  2671. h.connectionClose = true
  2672. return 0, err
  2673. }
  2674. if h.contentLength < 0 {
  2675. h.contentLengthBytes = h.contentLengthBytes[:0]
  2676. }
  2677. if h.noHTTP11 && !h.connectionClose {
  2678. // close connection for non-http/1.1 request unless 'Connection: keep-alive' is set.
  2679. v := peekArgBytes(h.h, strConnection)
  2680. h.connectionClose = !hasHeaderValue(v, strKeepAlive)
  2681. }
  2682. return s.hLen, nil
  2683. }
  2684. func (h *RequestHeader) collectCookies() {
  2685. if h.cookiesCollected {
  2686. return
  2687. }
  2688. for i, n := 0, len(h.h); i < n; i++ {
  2689. kv := &h.h[i]
  2690. if caseInsensitiveCompare(kv.key, strCookie) {
  2691. h.cookies = parseRequestCookies(h.cookies, kv.value)
  2692. tmp := *kv
  2693. copy(h.h[i:], h.h[i+1:])
  2694. n--
  2695. i--
  2696. h.h[n] = tmp
  2697. h.h = h.h[:n]
  2698. }
  2699. }
  2700. h.cookiesCollected = true
  2701. }
  2702. var errNonNumericChars = errors.New("non-numeric chars found")
  2703. func parseContentLength(b []byte) (int, error) {
  2704. v, n, err := parseUintBuf(b)
  2705. if err != nil {
  2706. return -1, fmt.Errorf("cannot parse Content-Length: %w", err)
  2707. }
  2708. if n != len(b) {
  2709. return -1, fmt.Errorf("cannot parse Content-Length: %w", errNonNumericChars)
  2710. }
  2711. return v, nil
  2712. }
  2713. type headerScanner struct {
  2714. b []byte
  2715. key []byte
  2716. value []byte
  2717. err error
  2718. // hLen stores header subslice len
  2719. hLen int
  2720. disableNormalizing bool
  2721. // by checking whether the next line contains a colon or not to tell
  2722. // it's a header entry or a multi line value of current header entry.
  2723. // the side effect of this operation is that we know the index of the
  2724. // next colon and new line, so this can be used during next iteration,
  2725. // instead of find them again.
  2726. nextColon int
  2727. nextNewLine int
  2728. initialized bool
  2729. }
  2730. func (s *headerScanner) next() bool {
  2731. if !s.initialized {
  2732. s.nextColon = -1
  2733. s.nextNewLine = -1
  2734. s.initialized = true
  2735. }
  2736. bLen := len(s.b)
  2737. if bLen >= 2 && s.b[0] == rChar && s.b[1] == nChar {
  2738. s.b = s.b[2:]
  2739. s.hLen += 2
  2740. return false
  2741. }
  2742. if bLen >= 1 && s.b[0] == nChar {
  2743. s.b = s.b[1:]
  2744. s.hLen++
  2745. return false
  2746. }
  2747. var n int
  2748. if s.nextColon >= 0 {
  2749. n = s.nextColon
  2750. s.nextColon = -1
  2751. } else {
  2752. n = bytes.IndexByte(s.b, ':')
  2753. // There can't be a \n inside the header name, check for this.
  2754. x := bytes.IndexByte(s.b, nChar)
  2755. if x < 0 {
  2756. // A header name should always at some point be followed by a \n
  2757. // even if it's the one that terminates the header block.
  2758. s.err = errNeedMore
  2759. return false
  2760. }
  2761. if x < n {
  2762. // There was a \n before the :
  2763. s.err = errInvalidName
  2764. return false
  2765. }
  2766. }
  2767. if n < 0 {
  2768. s.err = errNeedMore
  2769. return false
  2770. }
  2771. s.key = s.b[:n]
  2772. normalizeHeaderKey(s.key, s.disableNormalizing)
  2773. n++
  2774. for len(s.b) > n && s.b[n] == ' ' {
  2775. n++
  2776. // the newline index is a relative index, and lines below trimmed `s.b` by `n`,
  2777. // so the relative newline index also shifted forward. it's safe to decrease
  2778. // to a minus value, it means it's invalid, and will find the newline again.
  2779. s.nextNewLine--
  2780. }
  2781. s.hLen += n
  2782. s.b = s.b[n:]
  2783. if s.nextNewLine >= 0 {
  2784. n = s.nextNewLine
  2785. s.nextNewLine = -1
  2786. } else {
  2787. n = bytes.IndexByte(s.b, nChar)
  2788. }
  2789. if n < 0 {
  2790. s.err = errNeedMore
  2791. return false
  2792. }
  2793. isMultiLineValue := false
  2794. for {
  2795. if n+1 >= len(s.b) {
  2796. break
  2797. }
  2798. if s.b[n+1] != ' ' && s.b[n+1] != '\t' {
  2799. break
  2800. }
  2801. d := bytes.IndexByte(s.b[n+1:], nChar)
  2802. if d <= 0 {
  2803. break
  2804. } else if d == 1 && s.b[n+1] == rChar {
  2805. break
  2806. }
  2807. e := n + d + 1
  2808. if c := bytes.IndexByte(s.b[n+1:e], ':'); c >= 0 {
  2809. s.nextColon = c
  2810. s.nextNewLine = d - c - 1
  2811. break
  2812. }
  2813. isMultiLineValue = true
  2814. n = e
  2815. }
  2816. if n >= len(s.b) {
  2817. s.err = errNeedMore
  2818. return false
  2819. }
  2820. oldB := s.b
  2821. s.value = s.b[:n]
  2822. s.hLen += n + 1
  2823. s.b = s.b[n+1:]
  2824. if n > 0 && s.value[n-1] == rChar {
  2825. n--
  2826. }
  2827. for n > 0 && s.value[n-1] == ' ' {
  2828. n--
  2829. }
  2830. s.value = s.value[:n]
  2831. if isMultiLineValue {
  2832. s.value, s.b, s.hLen = normalizeHeaderValue(s.value, oldB, s.hLen)
  2833. }
  2834. return true
  2835. }
  2836. type headerValueScanner struct {
  2837. b []byte
  2838. value []byte
  2839. }
  2840. func (s *headerValueScanner) next() bool {
  2841. b := s.b
  2842. if len(b) == 0 {
  2843. return false
  2844. }
  2845. n := bytes.IndexByte(b, ',')
  2846. if n < 0 {
  2847. s.value = stripSpace(b)
  2848. s.b = b[len(b):]
  2849. return true
  2850. }
  2851. s.value = stripSpace(b[:n])
  2852. s.b = b[n+1:]
  2853. return true
  2854. }
  2855. func stripSpace(b []byte) []byte {
  2856. for len(b) > 0 && b[0] == ' ' {
  2857. b = b[1:]
  2858. }
  2859. for len(b) > 0 && b[len(b)-1] == ' ' {
  2860. b = b[:len(b)-1]
  2861. }
  2862. return b
  2863. }
  2864. func hasHeaderValue(s, value []byte) bool {
  2865. var vs headerValueScanner
  2866. vs.b = s
  2867. for vs.next() {
  2868. if caseInsensitiveCompare(vs.value, value) {
  2869. return true
  2870. }
  2871. }
  2872. return false
  2873. }
  2874. func nextLine(b []byte) ([]byte, []byte, error) {
  2875. nNext := bytes.IndexByte(b, nChar)
  2876. if nNext < 0 {
  2877. return nil, nil, errNeedMore
  2878. }
  2879. n := nNext
  2880. if n > 0 && b[n-1] == rChar {
  2881. n--
  2882. }
  2883. return b[:n], b[nNext+1:], nil
  2884. }
  2885. func initHeaderKV(kv *argsKV, key, value string, disableNormalizing bool) {
  2886. kv.key = getHeaderKeyBytes(kv, key, disableNormalizing)
  2887. // https://tools.ietf.org/html/rfc7230#section-3.2.4
  2888. kv.value = append(kv.value[:0], value...)
  2889. kv.value = removeNewLines(kv.value)
  2890. }
  2891. func getHeaderKeyBytes(kv *argsKV, key string, disableNormalizing bool) []byte {
  2892. kv.key = append(kv.key[:0], key...)
  2893. normalizeHeaderKey(kv.key, disableNormalizing)
  2894. return kv.key
  2895. }
  2896. func normalizeHeaderValue(ov, ob []byte, headerLength int) (nv, nb []byte, nhl int) {
  2897. nv = ov
  2898. length := len(ov)
  2899. if length <= 0 {
  2900. return
  2901. }
  2902. write := 0
  2903. shrunk := 0
  2904. lineStart := false
  2905. for read := 0; read < length; read++ {
  2906. c := ov[read]
  2907. if c == rChar || c == nChar {
  2908. shrunk++
  2909. if c == nChar {
  2910. lineStart = true
  2911. }
  2912. continue
  2913. } else if lineStart && c == '\t' {
  2914. c = ' '
  2915. } else {
  2916. lineStart = false
  2917. }
  2918. nv[write] = c
  2919. write++
  2920. }
  2921. nv = nv[:write]
  2922. copy(ob[write:], ob[write+shrunk:])
  2923. // Check if we need to skip \r\n or just \n
  2924. skip := 0
  2925. if ob[write] == rChar {
  2926. if ob[write+1] == nChar {
  2927. skip += 2
  2928. } else {
  2929. skip++
  2930. }
  2931. } else if ob[write] == nChar {
  2932. skip++
  2933. }
  2934. nb = ob[write+skip : len(ob)-shrunk]
  2935. nhl = headerLength - shrunk
  2936. return
  2937. }
  2938. func normalizeHeaderKey(b []byte, disableNormalizing bool) {
  2939. if disableNormalizing {
  2940. return
  2941. }
  2942. n := len(b)
  2943. if n == 0 {
  2944. return
  2945. }
  2946. b[0] = toUpperTable[b[0]]
  2947. for i := 1; i < n; i++ {
  2948. p := &b[i]
  2949. if *p == '-' {
  2950. i++
  2951. if i < n {
  2952. b[i] = toUpperTable[b[i]]
  2953. }
  2954. continue
  2955. }
  2956. *p = toLowerTable[*p]
  2957. }
  2958. }
  2959. // removeNewLines will replace `\r` and `\n` with an empty space
  2960. func removeNewLines(raw []byte) []byte {
  2961. // check if a `\r` is present and save the position.
  2962. // if no `\r` is found, check if a `\n` is present.
  2963. foundR := bytes.IndexByte(raw, rChar)
  2964. foundN := bytes.IndexByte(raw, nChar)
  2965. start := 0
  2966. if foundN != -1 {
  2967. if foundR > foundN {
  2968. start = foundN
  2969. } else if foundR != -1 {
  2970. start = foundR
  2971. }
  2972. } else if foundR != -1 {
  2973. start = foundR
  2974. } else {
  2975. return raw
  2976. }
  2977. for i := start; i < len(raw); i++ {
  2978. switch raw[i] {
  2979. case rChar, nChar:
  2980. raw[i] = ' '
  2981. default:
  2982. continue
  2983. }
  2984. }
  2985. return raw
  2986. }
  2987. // AppendNormalizedHeaderKey appends normalized header key (name) to dst
  2988. // and returns the resulting dst.
  2989. //
  2990. // Normalized header key starts with uppercase letter. The first letters
  2991. // after dashes are also uppercased. All the other letters are lowercased.
  2992. // Examples:
  2993. //
  2994. // - coNTENT-TYPe -> Content-Type
  2995. // - HOST -> Host
  2996. // - foo-bar-baz -> Foo-Bar-Baz
  2997. func AppendNormalizedHeaderKey(dst []byte, key string) []byte {
  2998. dst = append(dst, key...)
  2999. normalizeHeaderKey(dst[len(dst)-len(key):], false)
  3000. return dst
  3001. }
  3002. // AppendNormalizedHeaderKeyBytes appends normalized header key (name) to dst
  3003. // and returns the resulting dst.
  3004. //
  3005. // Normalized header key starts with uppercase letter. The first letters
  3006. // after dashes are also uppercased. All the other letters are lowercased.
  3007. // Examples:
  3008. //
  3009. // - coNTENT-TYPe -> Content-Type
  3010. // - HOST -> Host
  3011. // - foo-bar-baz -> Foo-Bar-Baz
  3012. func AppendNormalizedHeaderKeyBytes(dst, key []byte) []byte {
  3013. return AppendNormalizedHeaderKey(dst, b2s(key))
  3014. }
  3015. func appendArgsKeyBytes(dst []byte, args []argsKV, sep []byte) []byte {
  3016. for i, n := 0, len(args); i < n; i++ {
  3017. kv := &args[i]
  3018. dst = append(dst, kv.key...)
  3019. if i+1 < n {
  3020. dst = append(dst, sep...)
  3021. }
  3022. }
  3023. return dst
  3024. }
  3025. var (
  3026. errNeedMore = errors.New("need more data: cannot find trailing lf")
  3027. errInvalidName = errors.New("invalid header name")
  3028. errSmallBuffer = errors.New("small read buffer. Increase ReadBufferSize")
  3029. )
  3030. // ErrNothingRead is returned when a keep-alive connection is closed,
  3031. // either because the remote closed it or because of a read timeout.
  3032. type ErrNothingRead struct {
  3033. error
  3034. }
  3035. // ErrSmallBuffer is returned when the provided buffer size is too small
  3036. // for reading request and/or response headers.
  3037. //
  3038. // ReadBufferSize value from Server or clients should reduce the number
  3039. // of such errors.
  3040. type ErrSmallBuffer struct {
  3041. error
  3042. }
  3043. func mustPeekBuffered(r *bufio.Reader) []byte {
  3044. buf, err := r.Peek(r.Buffered())
  3045. if len(buf) == 0 || err != nil {
  3046. panic(fmt.Sprintf("bufio.Reader.Peek() returned unexpected data (%q, %v)", buf, err))
  3047. }
  3048. return buf
  3049. }
  3050. func mustDiscard(r *bufio.Reader, n int) {
  3051. if _, err := r.Discard(n); err != nil {
  3052. panic(fmt.Sprintf("bufio.Reader.Discard(%d) failed: %v", n, err))
  3053. }
  3054. }