header_test.go 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789
  1. package fasthttp
  2. import (
  3. "bufio"
  4. "bytes"
  5. "encoding/base64"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "net/http"
  10. "reflect"
  11. "strings"
  12. "testing"
  13. )
  14. func TestResponseHeaderAddContentType(t *testing.T) {
  15. t.Parallel()
  16. var h ResponseHeader
  17. h.Add("Content-Type", "test")
  18. got := string(h.Peek("Content-Type"))
  19. expected := "test"
  20. if got != expected {
  21. t.Errorf("expected %q got %q", expected, got)
  22. }
  23. var buf bytes.Buffer
  24. h.WriteTo(&buf) //nolint:errcheck
  25. if n := strings.Count(buf.String(), "Content-Type: "); n != 1 {
  26. t.Errorf("Content-Type occurred %d times", n)
  27. }
  28. }
  29. func TestResponseHeaderMultiLineValue(t *testing.T) {
  30. t.Parallel()
  31. s := "HTTP/1.1 200 SuperOK\r\n" +
  32. "EmptyValue1:\r\n" +
  33. "Content-Type: foo/bar;\r\n\tnewline;\r\n another/newline\r\n" +
  34. "Foo: Bar\r\n" +
  35. "Multi-Line: one;\r\n two\r\n" +
  36. "Values: v1;\r\n v2; v3;\r\n v4;\tv5\r\n" +
  37. "\r\n"
  38. header := new(ResponseHeader)
  39. if _, err := header.parse([]byte(s)); err != nil {
  40. t.Fatalf("parse headers with multi-line values failed, %s", err)
  41. }
  42. response, err := http.ReadResponse(bufio.NewReader(strings.NewReader(s)), nil)
  43. if err != nil {
  44. t.Fatalf("parse response using net/http failed, %s", err)
  45. }
  46. if !bytes.Equal(header.StatusMessage(), []byte("SuperOK")) {
  47. t.Errorf("parse status line with non-default value failed, got: '%s' want: 'SuperOK'", header.StatusMessage())
  48. }
  49. header.SetProtocol([]byte("HTTP/3.3"))
  50. if !bytes.Equal(header.Protocol(), []byte("HTTP/3.3")) {
  51. t.Errorf("parse protocol with non-default value failed, got: '%s' want: 'HTTP/3.3'", header.Protocol())
  52. }
  53. if !bytes.Equal(header.appendStatusLine(nil), []byte("HTTP/3.3 200 SuperOK\r\n")) {
  54. t.Errorf("parse status line with non-default value failed, got: '%s' want: 'HTTP/3.3 200 SuperOK'", header.Protocol())
  55. }
  56. header.SetStatusMessage(nil)
  57. if !bytes.Equal(header.appendStatusLine(nil), []byte("HTTP/3.3 200 OK\r\n")) {
  58. t.Errorf("parse status line with default protocol value failed, got: '%s' want: 'HTTP/3.3 200 OK'", header.appendStatusLine(nil))
  59. }
  60. header.SetStatusMessage(s2b(StatusMessage(200)))
  61. if !bytes.Equal(header.appendStatusLine(nil), []byte("HTTP/3.3 200 OK\r\n")) {
  62. t.Errorf("parse status line with default protocol value failed, got: '%s' want: 'HTTP/3.3 200 OK'", header.appendStatusLine(nil))
  63. }
  64. for name, vals := range response.Header {
  65. got := string(header.Peek(name))
  66. want := vals[0]
  67. if got != want {
  68. t.Errorf("unexpected %s got: %q want: %q", name, got, want)
  69. }
  70. }
  71. }
  72. func TestResponseHeaderMultiLineName(t *testing.T) {
  73. t.Parallel()
  74. s := "HTTP/1.1 200 OK\r\n" +
  75. "Host: golang.org\r\n" +
  76. "Gopher-New-\r\n" +
  77. " Line: This is a header on multiple lines\r\n" +
  78. "\r\n"
  79. header := new(ResponseHeader)
  80. if _, err := header.parse([]byte(s)); err != errInvalidName {
  81. m := make(map[string]string)
  82. header.VisitAll(func(key, value []byte) {
  83. m[string(key)] = string(value)
  84. })
  85. t.Errorf("expected error, got %q (%v)", m, err)
  86. }
  87. if !bytes.Equal(header.StatusMessage(), []byte("OK")) {
  88. t.Errorf("expected default status line, got: %s", header.StatusMessage())
  89. }
  90. if !bytes.Equal(header.Protocol(), []byte("HTTP/1.1")) {
  91. t.Errorf("expected default protocol, got: %s", header.Protocol())
  92. }
  93. if !bytes.Equal(header.appendStatusLine(nil), []byte("HTTP/1.1 200 OK\r\n")) {
  94. t.Errorf("parse status line with non-default value failed, got: %s want: HTTP/1.1 200 OK", header.Protocol())
  95. }
  96. }
  97. func TestResponseHeaderMultiLinePaniced(t *testing.T) {
  98. t.Parallel()
  99. // Input generated by fuzz testing that caused the parser to panic.
  100. s, _ := base64.StdEncoding.DecodeString("aAEAIDoKKDoKICA6CgkKCiA6CiA6CgkpCiA6CiA6CiA6Cig6CiAgOgoJCgogOgogOgoJKQogOgogOgogOgogOgogOgoJOg86CiA6CiA6Cig6CiAyCg==")
  101. header := new(RequestHeader)
  102. header.parse(s) //nolint:errcheck
  103. }
  104. func TestResponseHeaderEmptyValueFromHeader(t *testing.T) {
  105. t.Parallel()
  106. var h1 ResponseHeader
  107. h1.SetContentType("foo/bar")
  108. h1.Set("EmptyValue1", "")
  109. h1.Set("EmptyValue2", " ")
  110. s := h1.String()
  111. var h ResponseHeader
  112. br := bufio.NewReader(bytes.NewBufferString(s))
  113. if err := h.Read(br); err != nil {
  114. t.Fatalf("unexpected error: %s", err)
  115. }
  116. if string(h.ContentType()) != string(h1.ContentType()) {
  117. t.Fatalf("unexpected content-type: %q. Expecting %q", h.ContentType(), h1.ContentType())
  118. }
  119. v1 := h.Peek("EmptyValue1")
  120. if len(v1) > 0 {
  121. t.Fatalf("expecting empty value. Got %q", v1)
  122. }
  123. v2 := h.Peek("EmptyValue2")
  124. if len(v2) > 0 {
  125. t.Fatalf("expecting empty value. Got %q", v2)
  126. }
  127. }
  128. func TestResponseHeaderEmptyValueFromString(t *testing.T) {
  129. t.Parallel()
  130. s := "HTTP/1.1 200 OK\r\n" +
  131. "EmptyValue1:\r\n" +
  132. "Content-Type: foo/bar\r\n" +
  133. "EmptyValue2: \r\n" +
  134. "\r\n"
  135. var h ResponseHeader
  136. br := bufio.NewReader(bytes.NewBufferString(s))
  137. if err := h.Read(br); err != nil {
  138. t.Fatalf("unexpected error: %s", err)
  139. }
  140. if string(h.ContentType()) != "foo/bar" {
  141. t.Fatalf("unexpected content-type: %q. Expecting %q", h.ContentType(), "foo/bar")
  142. }
  143. v1 := h.Peek("EmptyValue1")
  144. if len(v1) > 0 {
  145. t.Fatalf("expecting empty value. Got %q", v1)
  146. }
  147. v2 := h.Peek("EmptyValue2")
  148. if len(v2) > 0 {
  149. t.Fatalf("expecting empty value. Got %q", v2)
  150. }
  151. }
  152. func TestRequestHeaderEmptyValueFromHeader(t *testing.T) {
  153. t.Parallel()
  154. var h1 RequestHeader
  155. h1.SetRequestURI("/foo/bar")
  156. h1.SetHost("foobar")
  157. h1.Set("EmptyValue1", "")
  158. h1.Set("EmptyValue2", " ")
  159. s := h1.String()
  160. var h RequestHeader
  161. br := bufio.NewReader(bytes.NewBufferString(s))
  162. if err := h.Read(br); err != nil {
  163. t.Fatalf("unexpected error: %s", err)
  164. }
  165. if string(h.Host()) != string(h1.Host()) {
  166. t.Fatalf("unexpected host: %q. Expecting %q", h.Host(), h1.Host())
  167. }
  168. v1 := h.Peek("EmptyValue1")
  169. if len(v1) > 0 {
  170. t.Fatalf("expecting empty value. Got %q", v1)
  171. }
  172. v2 := h.Peek("EmptyValue2")
  173. if len(v2) > 0 {
  174. t.Fatalf("expecting empty value. Got %q", v2)
  175. }
  176. }
  177. func TestRequestHeaderEmptyValueFromString(t *testing.T) {
  178. t.Parallel()
  179. s := "GET / HTTP/1.1\r\n" +
  180. "EmptyValue1:\r\n" +
  181. "Host: foobar\r\n" +
  182. "EmptyValue2: \r\n" +
  183. "\r\n"
  184. var h RequestHeader
  185. br := bufio.NewReader(bytes.NewBufferString(s))
  186. if err := h.Read(br); err != nil {
  187. t.Fatalf("unexpected error: %s", err)
  188. }
  189. if string(h.Host()) != "foobar" {
  190. t.Fatalf("unexpected host: %q. Expecting %q", h.Host(), "foobar")
  191. }
  192. v1 := h.Peek("EmptyValue1")
  193. if len(v1) > 0 {
  194. t.Fatalf("expecting empty value. Got %q", v1)
  195. }
  196. v2 := h.Peek("EmptyValue2")
  197. if len(v2) > 0 {
  198. t.Fatalf("expecting empty value. Got %q", v2)
  199. }
  200. }
  201. func TestRequestRawHeaders(t *testing.T) {
  202. t.Parallel()
  203. kvs := "hOsT: foobar\r\n" +
  204. "value: b\r\n" +
  205. "\r\n"
  206. t.Run("normalized", func(t *testing.T) {
  207. s := "GET / HTTP/1.1\r\n" + kvs
  208. exp := kvs
  209. var h RequestHeader
  210. br := bufio.NewReader(bytes.NewBufferString(s))
  211. if err := h.Read(br); err != nil {
  212. t.Fatalf("unexpected error: %s", err)
  213. }
  214. if string(h.Host()) != "foobar" {
  215. t.Fatalf("unexpected host: %q. Expecting %q", h.Host(), "foobar")
  216. }
  217. v2 := h.Peek("Value")
  218. if !bytes.Equal(v2, []byte{'b'}) {
  219. t.Fatalf("expecting non empty value. Got %q", v2)
  220. }
  221. if raw := h.RawHeaders(); string(raw) != exp {
  222. t.Fatalf("expected header %q, got %q", exp, raw)
  223. }
  224. })
  225. for _, n := range []int{0, 1, 4, 8} {
  226. t.Run(fmt.Sprintf("post-%dk", n), func(t *testing.T) {
  227. l := 1024 * n
  228. body := make([]byte, l)
  229. for i := range body {
  230. body[i] = 'a'
  231. }
  232. cl := fmt.Sprintf("Content-Length: %d\r\n", l)
  233. s := "POST / HTTP/1.1\r\n" + cl + kvs + string(body)
  234. exp := cl + kvs
  235. var h RequestHeader
  236. br := bufio.NewReader(bytes.NewBufferString(s))
  237. if err := h.Read(br); err != nil {
  238. t.Fatalf("unexpected error: %s", err)
  239. }
  240. if string(h.Host()) != "foobar" {
  241. t.Fatalf("unexpected host: %q. Expecting %q", h.Host(), "foobar")
  242. }
  243. v2 := h.Peek("Value")
  244. if !bytes.Equal(v2, []byte{'b'}) {
  245. t.Fatalf("expecting non empty value. Got %q", v2)
  246. }
  247. if raw := h.RawHeaders(); string(raw) != exp {
  248. t.Fatalf("expected header %q, got %q", exp, raw)
  249. }
  250. })
  251. }
  252. t.Run("http10", func(t *testing.T) {
  253. s := "GET / HTTP/1.0\r\n" + kvs
  254. exp := kvs
  255. var h RequestHeader
  256. br := bufio.NewReader(bytes.NewBufferString(s))
  257. if err := h.Read(br); err != nil {
  258. t.Fatalf("unexpected error: %s", err)
  259. }
  260. if string(h.Host()) != "foobar" {
  261. t.Fatalf("unexpected host: %q. Expecting %q", h.Host(), "foobar")
  262. }
  263. v2 := h.Peek("Value")
  264. if !bytes.Equal(v2, []byte{'b'}) {
  265. t.Fatalf("expecting non empty value. Got %q", v2)
  266. }
  267. if raw := h.RawHeaders(); string(raw) != exp {
  268. t.Fatalf("expected header %q, got %q", exp, raw)
  269. }
  270. })
  271. t.Run("no-kvs", func(t *testing.T) {
  272. s := "GET / HTTP/1.1\r\n\r\n"
  273. exp := ""
  274. var h RequestHeader
  275. h.DisableNormalizing()
  276. br := bufio.NewReader(bytes.NewBufferString(s))
  277. if err := h.Read(br); err != nil {
  278. t.Fatalf("unexpected error: %s", err)
  279. }
  280. if string(h.Host()) != "" {
  281. t.Fatalf("unexpected host: %q. Expecting %q", h.Host(), "")
  282. }
  283. v1 := h.Peek("NoKey")
  284. if len(v1) > 0 {
  285. t.Fatalf("expecting empty value. Got %q", v1)
  286. }
  287. if raw := h.RawHeaders(); string(raw) != exp {
  288. t.Fatalf("expected header %q, got %q", exp, raw)
  289. }
  290. })
  291. }
  292. func TestRequestHeaderSetCookieWithSpecialChars(t *testing.T) {
  293. t.Parallel()
  294. var h RequestHeader
  295. h.Set("Cookie", "ID&14")
  296. s := h.String()
  297. if !strings.Contains(s, "Cookie: ID&14") {
  298. t.Fatalf("Missing cookie in request header: [%s]", s)
  299. }
  300. var h1 RequestHeader
  301. br := bufio.NewReader(bytes.NewBufferString(s))
  302. if err := h1.Read(br); err != nil {
  303. t.Fatalf("unexpected error: %s", err)
  304. }
  305. cookie := h1.Peek(HeaderCookie)
  306. if string(cookie) != "ID&14" {
  307. t.Fatalf("unexpected cooke: %q. Expecting %q", cookie, "ID&14")
  308. }
  309. cookie = h1.Cookie("")
  310. if string(cookie) != "ID&14" {
  311. t.Fatalf("unexpected cooke: %q. Expecting %q", cookie, "ID&14")
  312. }
  313. }
  314. func TestResponseHeaderDefaultStatusCode(t *testing.T) {
  315. t.Parallel()
  316. var h ResponseHeader
  317. statusCode := h.StatusCode()
  318. if statusCode != StatusOK {
  319. t.Fatalf("unexpected status code: %d. Expecting %d", statusCode, StatusOK)
  320. }
  321. }
  322. func TestResponseHeaderDelClientCookie(t *testing.T) {
  323. t.Parallel()
  324. cookieName := "foobar"
  325. var h ResponseHeader
  326. c := AcquireCookie()
  327. c.SetKey(cookieName)
  328. c.SetValue("aasdfsdaf")
  329. h.SetCookie(c)
  330. h.DelClientCookieBytes([]byte(cookieName))
  331. if !h.Cookie(c) {
  332. t.Fatalf("expecting cookie %q", c.Key())
  333. }
  334. if !c.Expire().Equal(CookieExpireDelete) {
  335. t.Fatalf("unexpected cookie expiration time: %s. Expecting %s", c.Expire(), CookieExpireDelete)
  336. }
  337. if len(c.Value()) > 0 {
  338. t.Fatalf("unexpected cookie value: %q. Expecting empty value", c.Value())
  339. }
  340. ReleaseCookie(c)
  341. }
  342. func TestResponseHeaderAdd(t *testing.T) {
  343. t.Parallel()
  344. m := make(map[string]struct{})
  345. var h ResponseHeader
  346. h.Add("aaa", "bbb")
  347. h.Add("content-type", "xxx")
  348. m["bbb"] = struct{}{}
  349. m["xxx"] = struct{}{}
  350. for i := 0; i < 10; i++ {
  351. v := fmt.Sprintf("%d", i)
  352. h.Add("Foo-Bar", v)
  353. m[v] = struct{}{}
  354. }
  355. if h.Len() != 12 {
  356. t.Fatalf("unexpected header len %d. Expecting 12", h.Len())
  357. }
  358. h.VisitAll(func(k, v []byte) {
  359. switch string(k) {
  360. case "Aaa", "Foo-Bar", "Content-Type":
  361. if _, ok := m[string(v)]; !ok {
  362. t.Fatalf("unexpected value found %q. key %q", v, k)
  363. }
  364. delete(m, string(v))
  365. default:
  366. t.Fatalf("unexpected key found: %q", k)
  367. }
  368. })
  369. if len(m) > 0 {
  370. t.Fatalf("%d headers are missed", len(m))
  371. }
  372. s := h.String()
  373. br := bufio.NewReader(bytes.NewBufferString(s))
  374. var h1 ResponseHeader
  375. if err := h1.Read(br); err != nil {
  376. t.Fatalf("unexpected error: %s", err)
  377. }
  378. h.VisitAll(func(k, v []byte) {
  379. switch string(k) {
  380. case "Aaa", "Foo-Bar", "Content-Type":
  381. m[string(v)] = struct{}{}
  382. default:
  383. t.Fatalf("unexpected key found: %q", k)
  384. }
  385. })
  386. if len(m) != 12 {
  387. t.Fatalf("unexpected number of headers: %d. Expecting 12", len(m))
  388. }
  389. }
  390. func TestRequestHeaderAdd(t *testing.T) {
  391. t.Parallel()
  392. m := make(map[string]struct{})
  393. var h RequestHeader
  394. h.Add("aaa", "bbb")
  395. h.Add("user-agent", "xxx")
  396. m["bbb"] = struct{}{}
  397. m["xxx"] = struct{}{}
  398. for i := 0; i < 10; i++ {
  399. v := fmt.Sprintf("%d", i)
  400. h.Add("Foo-Bar", v)
  401. m[v] = struct{}{}
  402. }
  403. if h.Len() != 12 {
  404. t.Fatalf("unexpected header len %d. Expecting 12", h.Len())
  405. }
  406. h.VisitAll(func(k, v []byte) {
  407. switch string(k) {
  408. case "Aaa", "Foo-Bar", "User-Agent":
  409. if _, ok := m[string(v)]; !ok {
  410. t.Fatalf("unexpected value found %q. key %q", v, k)
  411. }
  412. delete(m, string(v))
  413. default:
  414. t.Fatalf("unexpected key found: %q", k)
  415. }
  416. })
  417. if len(m) > 0 {
  418. t.Fatalf("%d headers are missed", len(m))
  419. }
  420. s := h.String()
  421. br := bufio.NewReader(bytes.NewBufferString(s))
  422. var h1 RequestHeader
  423. if err := h1.Read(br); err != nil {
  424. t.Fatalf("unexpected error: %s", err)
  425. }
  426. h.VisitAll(func(k, v []byte) {
  427. switch string(k) {
  428. case "Aaa", "Foo-Bar", "User-Agent":
  429. m[string(v)] = struct{}{}
  430. default:
  431. t.Fatalf("unexpected key found: %q", k)
  432. }
  433. })
  434. if len(m) != 12 {
  435. t.Fatalf("unexpected number of headers: %d. Expecting 12", len(m))
  436. }
  437. s1 := h1.String()
  438. if s != s1 {
  439. t.Fatalf("unexpected headers %q. Expecting %q", s1, s)
  440. }
  441. }
  442. func TestHasHeaderValue(t *testing.T) {
  443. t.Parallel()
  444. testHasHeaderValue(t, "foobar", "foobar", true)
  445. testHasHeaderValue(t, "foobar", "foo", false)
  446. testHasHeaderValue(t, "foobar", "bar", false)
  447. testHasHeaderValue(t, "keep-alive, Upgrade", "keep-alive", true)
  448. testHasHeaderValue(t, "keep-alive , Upgrade", "Upgrade", true)
  449. testHasHeaderValue(t, "keep-alive, Upgrade", "Upgrade-foo", false)
  450. testHasHeaderValue(t, "keep-alive, Upgrade", "Upgr", false)
  451. testHasHeaderValue(t, "foo , bar, baz ,", "foo", true)
  452. testHasHeaderValue(t, "foo , bar, baz ,", "bar", true)
  453. testHasHeaderValue(t, "foo , bar, baz ,", "baz", true)
  454. testHasHeaderValue(t, "foo , bar, baz ,", "ba", false)
  455. testHasHeaderValue(t, "foo, ", "", true)
  456. testHasHeaderValue(t, "foo", "", false)
  457. }
  458. func testHasHeaderValue(t *testing.T, s, value string, has bool) {
  459. ok := hasHeaderValue([]byte(s), []byte(value))
  460. if ok != has {
  461. t.Fatalf("unexpected hasHeaderValue(%q, %q)=%v. Expecting %v", s, value, ok, has)
  462. }
  463. }
  464. func TestRequestHeaderDel(t *testing.T) {
  465. t.Parallel()
  466. var h RequestHeader
  467. h.Set("Foo-Bar", "baz")
  468. h.Set("aaa", "bbb")
  469. h.Set(HeaderConnection, "keep-alive")
  470. h.Set("Content-Type", "aaa")
  471. h.Set(HeaderHost, "aaabbb")
  472. h.Set("User-Agent", "asdfas")
  473. h.Set("Content-Length", "1123")
  474. h.Set("Cookie", "foobar=baz")
  475. h.Set(HeaderTrailer, "foo, bar")
  476. h.Del("foo-bar")
  477. h.Del("connection")
  478. h.DelBytes([]byte("content-type"))
  479. h.Del("Host")
  480. h.Del("user-agent")
  481. h.Del("content-length")
  482. h.Del("cookie")
  483. h.Del("trailer")
  484. hv := h.Peek("aaa")
  485. if string(hv) != "bbb" {
  486. t.Fatalf("unexpected header value: %q. Expecting %q", hv, "bbb")
  487. }
  488. hv = h.Peek("Foo-Bar")
  489. if len(hv) > 0 {
  490. t.Fatalf("non-zero value: %q", hv)
  491. }
  492. hv = h.Peek(HeaderConnection)
  493. if len(hv) > 0 {
  494. t.Fatalf("non-zero value: %q", hv)
  495. }
  496. hv = h.Peek(HeaderContentType)
  497. if len(hv) > 0 {
  498. t.Fatalf("non-zero value: %q", hv)
  499. }
  500. hv = h.Peek(HeaderHost)
  501. if len(hv) > 0 {
  502. t.Fatalf("non-zero value: %q", hv)
  503. }
  504. hv = h.Peek(HeaderUserAgent)
  505. if len(hv) > 0 {
  506. t.Fatalf("non-zero value: %q", hv)
  507. }
  508. hv = h.Peek(HeaderContentLength)
  509. if len(hv) > 0 {
  510. t.Fatalf("non-zero value: %q", hv)
  511. }
  512. hv = h.Peek(HeaderCookie)
  513. if len(hv) > 0 {
  514. t.Fatalf("non-zero value: %q", hv)
  515. }
  516. hv = h.Peek(HeaderTrailer)
  517. if len(hv) > 0 {
  518. t.Fatalf("non-zero value: %q", hv)
  519. }
  520. cv := h.Cookie("foobar")
  521. if len(cv) > 0 {
  522. t.Fatalf("unexpected cookie obtianed: %q", cv)
  523. }
  524. if h.ContentLength() != 0 {
  525. t.Fatalf("unexpected content-length: %d. Expecting 0", h.ContentLength())
  526. }
  527. }
  528. func TestResponseHeaderDel(t *testing.T) {
  529. t.Parallel()
  530. var h ResponseHeader
  531. h.Set("Foo-Bar", "baz")
  532. h.Set("aaa", "bbb")
  533. h.Set(HeaderConnection, "keep-alive")
  534. h.Set(HeaderContentType, "aaa")
  535. h.Set(HeaderServer, "aaabbb")
  536. h.Set(HeaderContentLength, "1123")
  537. h.Set(HeaderTrailer, "foo, bar")
  538. var c Cookie
  539. c.SetKey("foo")
  540. c.SetValue("bar")
  541. h.SetCookie(&c)
  542. h.Del("foo-bar")
  543. h.Del("connection")
  544. h.DelBytes([]byte("content-type"))
  545. h.Del(HeaderServer)
  546. h.Del("content-length")
  547. h.Del("set-cookie")
  548. h.Del("trailer")
  549. hv := h.Peek("aaa")
  550. if string(hv) != "bbb" {
  551. t.Fatalf("unexpected header value: %q. Expecting %q", hv, "bbb")
  552. }
  553. hv = h.Peek("Foo-Bar")
  554. if len(hv) > 0 {
  555. t.Fatalf("non-zero header value: %q", hv)
  556. }
  557. hv = h.Peek(HeaderConnection)
  558. if len(hv) > 0 {
  559. t.Fatalf("non-zero value: %q", hv)
  560. }
  561. hv = h.Peek(HeaderContentType)
  562. if string(hv) != string(defaultContentType) {
  563. t.Fatalf("unexpected content-type: %q. Expecting %q", hv, defaultContentType)
  564. }
  565. hv = h.Peek(HeaderServer)
  566. if len(hv) > 0 {
  567. t.Fatalf("non-zero value: %q", hv)
  568. }
  569. hv = h.Peek(HeaderContentLength)
  570. if len(hv) > 0 {
  571. t.Fatalf("non-zero value: %q", hv)
  572. }
  573. hv = h.Peek(HeaderTrailer)
  574. if len(hv) > 0 {
  575. t.Fatalf("non-zero value: %q", hv)
  576. }
  577. if h.Cookie(&c) {
  578. t.Fatalf("unexpected cookie obtianed: %q", &c)
  579. }
  580. if h.ContentLength() != 0 {
  581. t.Fatalf("unexpected content-length: %d. Expecting 0", h.ContentLength())
  582. }
  583. }
  584. func TestResponseHeaderSetTrailerGetBytes(t *testing.T) {
  585. t.Parallel()
  586. h := &ResponseHeader{}
  587. h.noDefaultDate = true
  588. h.Set("Foo", "bar")
  589. h.Set(HeaderTrailer, "Baz")
  590. h.Set("Baz", "test")
  591. headerBytes := h.Header()
  592. n, err := h.parseFirstLine(headerBytes)
  593. if err != nil {
  594. t.Fatalf("unexpected error: %s", err)
  595. }
  596. if string(headerBytes[n:]) != "Foo: bar\r\nTrailer: Baz\r\n\r\n" {
  597. t.Fatalf("Unexpected header: %q. Expected %s", headerBytes[n:], "Foo: bar\nTrailer: Baz\n\n")
  598. }
  599. if string(h.TrailerHeader()) != "Baz: test\r\n\r\n" {
  600. t.Fatalf("Unexpected trailer header: %q. Expected %s", h.TrailerHeader(), "Baz: test\r\n\r\n")
  601. }
  602. }
  603. func TestRequestHeaderSetTrailerGetBytes(t *testing.T) {
  604. t.Parallel()
  605. h := &RequestHeader{}
  606. h.Set("Foo", "bar")
  607. h.Set(HeaderTrailer, "Baz")
  608. h.Set("Baz", "test")
  609. headerBytes := h.Header()
  610. n, err := h.parseFirstLine(headerBytes)
  611. if err != nil {
  612. t.Fatalf("unexpected error: %s", err)
  613. }
  614. if string(headerBytes[n:]) != "Foo: bar\r\nTrailer: Baz\r\n\r\n" {
  615. t.Fatalf("Unexpected header: %q. Expected %s", headerBytes[n:], "Foo: bar\nTrailer: Baz\n\n")
  616. }
  617. if string(h.TrailerHeader()) != "Baz: test\r\n\r\n" {
  618. t.Fatalf("Unexpected trailer header: %q. Expected %s", h.TrailerHeader(), "Baz: test\r\n\r\n")
  619. }
  620. }
  621. func TestAppendNormalizedHeaderKeyBytes(t *testing.T) {
  622. t.Parallel()
  623. testAppendNormalizedHeaderKeyBytes(t, "", "")
  624. testAppendNormalizedHeaderKeyBytes(t, "Content-Type", "Content-Type")
  625. testAppendNormalizedHeaderKeyBytes(t, "foO-bAr-BAZ", "Foo-Bar-Baz")
  626. }
  627. func testAppendNormalizedHeaderKeyBytes(t *testing.T, key, expectedKey string) {
  628. buf := []byte("foobar")
  629. result := AppendNormalizedHeaderKeyBytes(buf, []byte(key))
  630. normalizedKey := result[len(buf):]
  631. if string(normalizedKey) != expectedKey {
  632. t.Fatalf("unexpected normalized key %q. Expecting %q", normalizedKey, expectedKey)
  633. }
  634. }
  635. func TestRequestHeaderHTTP10ConnectionClose(t *testing.T) {
  636. t.Parallel()
  637. s := "GET / HTTP/1.0\r\nHost: foobar\r\n\r\n"
  638. var h RequestHeader
  639. br := bufio.NewReader(bytes.NewBufferString(s))
  640. if err := h.Read(br); err != nil {
  641. t.Fatalf("unexpected error: %s", err)
  642. }
  643. if !h.ConnectionClose() {
  644. t.Fatalf("expecting 'Connection: close' request header")
  645. }
  646. }
  647. func TestRequestHeaderHTTP10ConnectionKeepAlive(t *testing.T) {
  648. t.Parallel()
  649. s := "GET / HTTP/1.0\r\nHost: foobar\r\nConnection: keep-alive\r\n\r\n"
  650. var h RequestHeader
  651. br := bufio.NewReader(bytes.NewBufferString(s))
  652. if err := h.Read(br); err != nil {
  653. t.Fatalf("unexpected error: %s", err)
  654. }
  655. if h.ConnectionClose() {
  656. t.Fatalf("unexpected 'Connection: close' request header")
  657. }
  658. }
  659. func TestBufferSnippet(t *testing.T) {
  660. t.Parallel()
  661. testBufferSnippet(t, "", `""`)
  662. testBufferSnippet(t, "foobar", `"foobar"`)
  663. b := string(createFixedBody(199))
  664. bExpected := fmt.Sprintf("%q", b)
  665. testBufferSnippet(t, b, bExpected)
  666. for i := 0; i < 10; i++ {
  667. b += "foobar"
  668. bExpected = fmt.Sprintf("%q", b)
  669. testBufferSnippet(t, b, bExpected)
  670. }
  671. b = string(createFixedBody(400))
  672. bExpected = fmt.Sprintf("%q", b)
  673. testBufferSnippet(t, b, bExpected)
  674. for i := 0; i < 10; i++ {
  675. b += "sadfqwer"
  676. bExpected = fmt.Sprintf("%q...%q", b[:200], b[len(b)-200:])
  677. testBufferSnippet(t, b, bExpected)
  678. }
  679. }
  680. func testBufferSnippet(t *testing.T, buf, expectedSnippet string) {
  681. snippet := bufferSnippet([]byte(buf))
  682. if snippet != expectedSnippet {
  683. t.Fatalf("unexpected snippet %s. Expecting %s", snippet, expectedSnippet)
  684. }
  685. }
  686. func TestResponseHeaderTrailingCRLFSuccess(t *testing.T) {
  687. t.Parallel()
  688. trailingCRLF := "\r\n\r\n\r\n"
  689. s := "HTTP/1.1 200 OK\r\nContent-Type: aa\r\nContent-Length: 123\r\n\r\n" + trailingCRLF
  690. var r ResponseHeader
  691. br := bufio.NewReader(bytes.NewBufferString(s))
  692. if err := r.Read(br); err != nil {
  693. t.Fatalf("unexpected error: %s", err)
  694. }
  695. // try reading the trailing CRLF. It must return EOF
  696. err := r.Read(br)
  697. if err == nil {
  698. t.Fatalf("expecting error")
  699. }
  700. if err != io.EOF {
  701. t.Fatalf("unexpected error: %s. Expecting %s", err, io.EOF)
  702. }
  703. }
  704. func TestResponseHeaderTrailingCRLFError(t *testing.T) {
  705. t.Parallel()
  706. trailingCRLF := "\r\nerror\r\n\r\n"
  707. s := "HTTP/1.1 200 OK\r\nContent-Type: aa\r\nContent-Length: 123\r\n\r\n" + trailingCRLF
  708. var r ResponseHeader
  709. br := bufio.NewReader(bytes.NewBufferString(s))
  710. if err := r.Read(br); err != nil {
  711. t.Fatalf("unexpected error: %s", err)
  712. }
  713. // try reading the trailing CRLF. It must return EOF
  714. err := r.Read(br)
  715. if err == nil {
  716. t.Fatalf("expecting error")
  717. }
  718. if err == io.EOF {
  719. t.Fatalf("unexpected error: %s", err)
  720. }
  721. }
  722. func TestRequestHeaderTrailingCRLFSuccess(t *testing.T) {
  723. t.Parallel()
  724. trailingCRLF := "\r\n\r\n\r\n"
  725. s := "GET / HTTP/1.1\r\nHost: aaa.com\r\n\r\n" + trailingCRLF
  726. var r RequestHeader
  727. br := bufio.NewReader(bytes.NewBufferString(s))
  728. if err := r.Read(br); err != nil {
  729. t.Fatalf("unexpected error: %s", err)
  730. }
  731. // try reading the trailing CRLF. It must return EOF
  732. err := r.Read(br)
  733. if err == nil {
  734. t.Fatalf("expecting error")
  735. }
  736. if err != io.EOF {
  737. t.Fatalf("unexpected error: %s. Expecting %s", err, io.EOF)
  738. }
  739. }
  740. func TestRequestHeaderTrailingCRLFError(t *testing.T) {
  741. t.Parallel()
  742. trailingCRLF := "\r\nerror\r\n\r\n"
  743. s := "GET / HTTP/1.1\r\nHost: aaa.com\r\n\r\n" + trailingCRLF
  744. var r RequestHeader
  745. br := bufio.NewReader(bytes.NewBufferString(s))
  746. if err := r.Read(br); err != nil {
  747. t.Fatalf("unexpected error: %s", err)
  748. }
  749. // try reading the trailing CRLF. It must return EOF
  750. err := r.Read(br)
  751. if err == nil {
  752. t.Fatalf("expecting error")
  753. }
  754. if err == io.EOF {
  755. t.Fatalf("unexpected error: %s", err)
  756. }
  757. }
  758. func TestRequestHeaderReadEOF(t *testing.T) {
  759. t.Parallel()
  760. var r RequestHeader
  761. br := bufio.NewReader(&bytes.Buffer{})
  762. err := r.Read(br)
  763. if err == nil {
  764. t.Fatalf("expecting error")
  765. }
  766. if err != io.EOF {
  767. t.Fatalf("unexpected error: %s. Expecting %s", err, io.EOF)
  768. }
  769. // incomplete request header mustn't return io.EOF
  770. br = bufio.NewReader(bytes.NewBufferString("GET "))
  771. err = r.Read(br)
  772. if err == nil {
  773. t.Fatalf("expecting error")
  774. }
  775. if err == io.EOF {
  776. t.Fatalf("expecting non-EOF error")
  777. }
  778. }
  779. func TestResponseHeaderReadEOF(t *testing.T) {
  780. t.Parallel()
  781. var r ResponseHeader
  782. br := bufio.NewReader(&bytes.Buffer{})
  783. err := r.Read(br)
  784. if err == nil {
  785. t.Fatalf("expecting error")
  786. }
  787. if err != io.EOF {
  788. t.Fatalf("unexpected error: %s. Expecting %s", err, io.EOF)
  789. }
  790. // incomplete response header mustn't return io.EOF
  791. br = bufio.NewReader(bytes.NewBufferString("HTTP/1.1 "))
  792. err = r.Read(br)
  793. if err == nil {
  794. t.Fatalf("expecting error")
  795. }
  796. if err == io.EOF {
  797. t.Fatalf("expecting non-EOF error")
  798. }
  799. }
  800. func TestResponseHeaderOldVersion(t *testing.T) {
  801. t.Parallel()
  802. var h ResponseHeader
  803. s := "HTTP/1.0 200 OK\r\nContent-Length: 5\r\nContent-Type: aaa\r\n\r\n12345"
  804. s += "HTTP/1.0 200 OK\r\nContent-Length: 2\r\nContent-Type: ass\r\nConnection: keep-alive\r\n\r\n42"
  805. br := bufio.NewReader(bytes.NewBufferString(s))
  806. if err := h.Read(br); err != nil {
  807. t.Fatalf("unexpected error: %s", err)
  808. }
  809. if !h.ConnectionClose() {
  810. t.Fatalf("expecting 'Connection: close' for the response with old http protocol")
  811. }
  812. if err := h.Read(br); err != nil {
  813. t.Fatalf("unexpected error: %s", err)
  814. }
  815. if h.ConnectionClose() {
  816. t.Fatalf("unexpected 'Connection: close' for keep-alive response with old http protocol")
  817. }
  818. }
  819. func TestRequestHeaderSetByteRange(t *testing.T) {
  820. t.Parallel()
  821. testRequestHeaderSetByteRange(t, 0, 10, "bytes=0-10")
  822. testRequestHeaderSetByteRange(t, 123, -1, "bytes=123-")
  823. testRequestHeaderSetByteRange(t, -234, 58349, "bytes=-234")
  824. }
  825. func testRequestHeaderSetByteRange(t *testing.T, startPos, endPos int, expectedV string) {
  826. var h RequestHeader
  827. h.SetByteRange(startPos, endPos)
  828. v := h.Peek(HeaderRange)
  829. if string(v) != expectedV {
  830. t.Fatalf("unexpected range: %q. Expecting %q. startPos=%d, endPos=%d", v, expectedV, startPos, endPos)
  831. }
  832. }
  833. func TestResponseHeaderSetContentRange(t *testing.T) {
  834. t.Parallel()
  835. testResponseHeaderSetContentRange(t, 0, 0, 1, "bytes 0-0/1")
  836. testResponseHeaderSetContentRange(t, 123, 456, 789, "bytes 123-456/789")
  837. }
  838. func testResponseHeaderSetContentRange(t *testing.T, startPos, endPos, contentLength int, expectedV string) {
  839. var h ResponseHeader
  840. h.SetContentRange(startPos, endPos, contentLength)
  841. v := h.Peek(HeaderContentRange)
  842. if string(v) != expectedV {
  843. t.Fatalf("unexpected content-range: %q. Expecting %q. startPos=%d, endPos=%d, contentLength=%d",
  844. v, expectedV, startPos, endPos, contentLength)
  845. }
  846. }
  847. func TestRequestHeaderHasAcceptEncoding(t *testing.T) {
  848. t.Parallel()
  849. testRequestHeaderHasAcceptEncoding(t, "", "gzip", false)
  850. testRequestHeaderHasAcceptEncoding(t, "gzip", "sdhc", false)
  851. testRequestHeaderHasAcceptEncoding(t, "deflate", "deflate", true)
  852. testRequestHeaderHasAcceptEncoding(t, "gzip, deflate, sdhc", "gzi", false)
  853. testRequestHeaderHasAcceptEncoding(t, "gzip, deflate, sdhc", "dhc", false)
  854. testRequestHeaderHasAcceptEncoding(t, "gzip, deflate, sdhc", "sdh", false)
  855. testRequestHeaderHasAcceptEncoding(t, "gzip, deflate, sdhc", "zip", false)
  856. testRequestHeaderHasAcceptEncoding(t, "gzip, deflate, sdhc", "flat", false)
  857. testRequestHeaderHasAcceptEncoding(t, "gzip, deflate, sdhc", "flate", false)
  858. testRequestHeaderHasAcceptEncoding(t, "gzip, deflate, sdhc", "def", false)
  859. testRequestHeaderHasAcceptEncoding(t, "gzip, deflate, sdhc", "gzip", true)
  860. testRequestHeaderHasAcceptEncoding(t, "gzip, deflate, sdhc", "deflate", true)
  861. testRequestHeaderHasAcceptEncoding(t, "gzip, deflate, sdhc", "sdhc", true)
  862. }
  863. func testRequestHeaderHasAcceptEncoding(t *testing.T, ae, v string, resultExpected bool) {
  864. var h RequestHeader
  865. h.Set(HeaderAcceptEncoding, ae)
  866. result := h.HasAcceptEncoding(v)
  867. if result != resultExpected {
  868. t.Fatalf("unexpected result in HasAcceptEncoding(%q, %q): %v. Expecting %v", ae, v, result, resultExpected)
  869. }
  870. }
  871. func TestRequestMultipartFormBoundary(t *testing.T) {
  872. t.Parallel()
  873. testRequestMultipartFormBoundary(t, "POST / HTTP/1.1\r\nContent-Type: multipart/form-data; boundary=foobar\r\n\r\n", "foobar")
  874. // incorrect content-type
  875. testRequestMultipartFormBoundary(t, "POST / HTTP/1.1\r\nContent-Type: foo/bar\r\n\r\n", "")
  876. // empty boundary
  877. testRequestMultipartFormBoundary(t, "POST / HTTP/1.1\r\nContent-Type: multipart/form-data; boundary=\r\n\r\n", "")
  878. // missing boundary
  879. testRequestMultipartFormBoundary(t, "POST / HTTP/1.1\r\nContent-Type: multipart/form-data\r\n\r\n", "")
  880. // boundary after other content-type params
  881. testRequestMultipartFormBoundary(t, "POST / HTTP/1.1\r\nContent-Type: multipart/form-data; foo=bar; boundary=--aaabb \r\n\r\n", "--aaabb")
  882. // quoted boundary
  883. testRequestMultipartFormBoundary(t, "POST / HTTP/1.1\r\nContent-Type: multipart/form-data; boundary=\"foobar\"\r\n\r\n", "foobar")
  884. var h RequestHeader
  885. h.SetMultipartFormBoundary("foobarbaz")
  886. b := h.MultipartFormBoundary()
  887. if string(b) != "foobarbaz" {
  888. t.Fatalf("unexpected boundary %q. Expecting %q", b, "foobarbaz")
  889. }
  890. }
  891. func testRequestMultipartFormBoundary(t *testing.T, s, boundary string) {
  892. var h RequestHeader
  893. r := bytes.NewBufferString(s)
  894. br := bufio.NewReader(r)
  895. if err := h.Read(br); err != nil {
  896. t.Fatalf("unexpected error: %s. s=%q, boundary=%q", err, s, boundary)
  897. }
  898. b := h.MultipartFormBoundary()
  899. if string(b) != boundary {
  900. t.Fatalf("unexpected boundary %q. Expecting %q. s=%q", b, boundary, s)
  901. }
  902. }
  903. func TestResponseHeaderConnectionUpgrade(t *testing.T) {
  904. t.Parallel()
  905. testResponseHeaderConnectionUpgrade(t, "HTTP/1.1 200 OK\r\nContent-Length: 10\r\nConnection: Upgrade, HTTP2-Settings\r\n\r\n",
  906. true, true)
  907. testResponseHeaderConnectionUpgrade(t, "HTTP/1.1 200 OK\r\nContent-Length: 10\r\nConnection: keep-alive, Upgrade\r\n\r\n",
  908. true, true)
  909. // non-http/1.1 protocol has 'connection: close' by default, which also disables 'connection: upgrade'
  910. testResponseHeaderConnectionUpgrade(t, "HTTP/1.0 200 OK\r\nContent-Length: 10\r\nConnection: Upgrade, HTTP2-Settings\r\n\r\n",
  911. false, false)
  912. // explicit keep-alive for non-http/1.1, so 'connection: upgrade' works
  913. testResponseHeaderConnectionUpgrade(t, "HTTP/1.0 200 OK\r\nContent-Length: 10\r\nConnection: Upgrade, keep-alive\r\n\r\n",
  914. true, true)
  915. // implicit keep-alive for http/1.1
  916. testResponseHeaderConnectionUpgrade(t, "HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n", false, true)
  917. // no content-length, so 'connection: close' is assumed
  918. testResponseHeaderConnectionUpgrade(t, "HTTP/1.1 200 OK\r\n\r\n", false, false)
  919. }
  920. func testResponseHeaderConnectionUpgrade(t *testing.T, s string, isUpgrade, isKeepAlive bool) {
  921. var h ResponseHeader
  922. r := bytes.NewBufferString(s)
  923. br := bufio.NewReader(r)
  924. if err := h.Read(br); err != nil {
  925. t.Fatalf("unexpected error: %s. Response header %q", err, s)
  926. }
  927. upgrade := h.ConnectionUpgrade()
  928. if upgrade != isUpgrade {
  929. t.Fatalf("unexpected 'connection: upgrade' when parsing response header: %v. Expecting %v. header %q. v=%q",
  930. upgrade, isUpgrade, s, h.Peek("Connection"))
  931. }
  932. keepAlive := !h.ConnectionClose()
  933. if keepAlive != isKeepAlive {
  934. t.Fatalf("unexpected 'connection: keep-alive' when parsing response header: %v. Expecting %v. header %q. v=%q",
  935. keepAlive, isKeepAlive, s, &h)
  936. }
  937. }
  938. func TestRequestHeaderConnectionUpgrade(t *testing.T) {
  939. t.Parallel()
  940. testRequestHeaderConnectionUpgrade(t, "GET /foobar HTTP/1.1\r\nConnection: Upgrade, HTTP2-Settings\r\nHost: foobar.com\r\n\r\n",
  941. true, true)
  942. testRequestHeaderConnectionUpgrade(t, "GET /foobar HTTP/1.1\r\nConnection: keep-alive,Upgrade\r\nHost: foobar.com\r\n\r\n",
  943. true, true)
  944. // non-http/1.1 has 'connection: close' by default, which resets 'connection: upgrade'
  945. testRequestHeaderConnectionUpgrade(t, "GET /foobar HTTP/1.0\r\nConnection: Upgrade, HTTP2-Settings\r\nHost: foobar.com\r\n\r\n",
  946. false, false)
  947. // explicit 'connection: keep-alive' in non-http/1.1
  948. testRequestHeaderConnectionUpgrade(t, "GET /foobar HTTP/1.0\r\nConnection: foo, Upgrade, keep-alive\r\nHost: foobar.com\r\n\r\n",
  949. true, true)
  950. // no upgrade
  951. testRequestHeaderConnectionUpgrade(t, "GET /foobar HTTP/1.1\r\nConnection: Upgradess, foobar\r\nHost: foobar.com\r\n\r\n",
  952. false, true)
  953. testRequestHeaderConnectionUpgrade(t, "GET /foobar HTTP/1.1\r\nHost: foobar.com\r\n\r\n",
  954. false, true)
  955. // explicit connection close
  956. testRequestHeaderConnectionUpgrade(t, "GET /foobar HTTP/1.1\r\nConnection: close\r\nHost: foobar.com\r\n\r\n",
  957. false, false)
  958. }
  959. func testRequestHeaderConnectionUpgrade(t *testing.T, s string, isUpgrade, isKeepAlive bool) {
  960. var h RequestHeader
  961. r := bytes.NewBufferString(s)
  962. br := bufio.NewReader(r)
  963. if err := h.Read(br); err != nil {
  964. t.Fatalf("unexpected error: %s. Request header %q", err, s)
  965. }
  966. upgrade := h.ConnectionUpgrade()
  967. if upgrade != isUpgrade {
  968. t.Fatalf("unexpected 'connection: upgrade' when parsing request header: %v. Expecting %v. header %q",
  969. upgrade, isUpgrade, s)
  970. }
  971. keepAlive := !h.ConnectionClose()
  972. if keepAlive != isKeepAlive {
  973. t.Fatalf("unexpected 'connection: keep-alive' when parsing request header: %v. Expecting %v. header %q",
  974. keepAlive, isKeepAlive, s)
  975. }
  976. }
  977. func TestRequestHeaderProxyWithCookie(t *testing.T) {
  978. t.Parallel()
  979. // Proxy request header (read it, then write it without touching any headers).
  980. var h RequestHeader
  981. r := bytes.NewBufferString("GET /foo HTTP/1.1\r\nFoo: bar\r\nHost: aaa.com\r\nCookie: foo=bar; bazzz=aaaaaaa; x=y\r\nCookie: aqqqqq=123\r\n\r\n")
  982. br := bufio.NewReader(r)
  983. if err := h.Read(br); err != nil {
  984. t.Fatalf("unexpected error: %s", err)
  985. }
  986. w := &bytes.Buffer{}
  987. bw := bufio.NewWriter(w)
  988. if err := h.Write(bw); err != nil {
  989. t.Fatalf("unexpected error: %s", err)
  990. }
  991. if err := bw.Flush(); err != nil {
  992. t.Fatalf("unexpected error: %s", err)
  993. }
  994. var h1 RequestHeader
  995. br.Reset(w)
  996. if err := h1.Read(br); err != nil {
  997. t.Fatalf("unexpected error: %s", err)
  998. }
  999. if string(h1.RequestURI()) != "/foo" {
  1000. t.Fatalf("unexpected requestURI: %q. Expecting %q", h1.RequestURI(), "/foo")
  1001. }
  1002. if string(h1.Host()) != "aaa.com" {
  1003. t.Fatalf("unexpected host: %q. Expecting %q", h1.Host(), "aaa.com")
  1004. }
  1005. if string(h1.Peek("Foo")) != "bar" {
  1006. t.Fatalf("unexpected Foo: %q. Expecting %q", h1.Peek("Foo"), "bar")
  1007. }
  1008. if string(h1.Cookie("foo")) != "bar" {
  1009. t.Fatalf("unexpected coookie foo=%q. Expecting %q", h1.Cookie("foo"), "bar")
  1010. }
  1011. if string(h1.Cookie("bazzz")) != "aaaaaaa" {
  1012. t.Fatalf("unexpected cookie bazzz=%q. Expecting %q", h1.Cookie("bazzz"), "aaaaaaa")
  1013. }
  1014. if string(h1.Cookie("x")) != "y" {
  1015. t.Fatalf("unexpected cookie x=%q. Expecting %q", h1.Cookie("x"), "y")
  1016. }
  1017. if string(h1.Cookie("aqqqqq")) != "123" {
  1018. t.Fatalf("unexpected cookie aqqqqq=%q. Expecting %q", h1.Cookie("aqqqqq"), "123")
  1019. }
  1020. }
  1021. func TestResponseHeaderFirstByteReadEOF(t *testing.T) {
  1022. t.Parallel()
  1023. var h ResponseHeader
  1024. r := &errorReader{fmt.Errorf("non-eof error")}
  1025. br := bufio.NewReader(r)
  1026. err := h.Read(br)
  1027. if err == nil {
  1028. t.Fatalf("expecting error")
  1029. }
  1030. if err != io.EOF {
  1031. t.Fatalf("unexpected error %s. Expecting %s", err, io.EOF)
  1032. }
  1033. }
  1034. type errorReader struct {
  1035. err error
  1036. }
  1037. func (r *errorReader) Read(p []byte) (int, error) {
  1038. return 0, r.err
  1039. }
  1040. func TestRequestHeaderEmptyMethod(t *testing.T) {
  1041. t.Parallel()
  1042. var h RequestHeader
  1043. if !h.IsGet() {
  1044. t.Fatalf("empty method must be equivalent to GET")
  1045. }
  1046. }
  1047. func TestResponseHeaderHTTPVer(t *testing.T) {
  1048. t.Parallel()
  1049. // non-http/1.1
  1050. testResponseHeaderHTTPVer(t, "HTTP/1.0 200 OK\r\nContent-Type: aaa\r\nContent-Length: 123\r\n\r\n", true)
  1051. testResponseHeaderHTTPVer(t, "HTTP/0.9 200 OK\r\nContent-Type: aaa\r\nContent-Length: 123\r\n\r\n", true)
  1052. testResponseHeaderHTTPVer(t, "foobar 200 OK\r\nContent-Type: aaa\r\nContent-Length: 123\r\n\r\n", true)
  1053. // http/1.1
  1054. testResponseHeaderHTTPVer(t, "HTTP/1.1 200 OK\r\nContent-Type: aaa\r\nContent-Length: 123\r\n\r\n", false)
  1055. }
  1056. func TestRequestHeaderHTTPVer(t *testing.T) {
  1057. t.Parallel()
  1058. // non-http/1.1
  1059. testRequestHeaderHTTPVer(t, "GET / HTTP/1.0\r\nHost: aa.com\r\n\r\n", true)
  1060. testRequestHeaderHTTPVer(t, "GET / HTTP/0.9\r\nHost: aa.com\r\n\r\n", true)
  1061. testRequestHeaderHTTPVer(t, "GET / foobar\r\nHost: aa.com\r\n\r\n", true)
  1062. // empty http version
  1063. testRequestHeaderHTTPVer(t, "GET /\r\nHost: aaa.com\r\n\r\n", true)
  1064. testRequestHeaderHTTPVer(t, "GET / \r\nHost: aaa.com\r\n\r\n", true)
  1065. // http/1.1
  1066. testRequestHeaderHTTPVer(t, "GET / HTTP/1.1\r\nHost: a.com\r\n\r\n", false)
  1067. }
  1068. func testResponseHeaderHTTPVer(t *testing.T, s string, connectionClose bool) {
  1069. var h ResponseHeader
  1070. r := bytes.NewBufferString(s)
  1071. br := bufio.NewReader(r)
  1072. if err := h.Read(br); err != nil {
  1073. t.Fatalf("unexpected error: %s. response=%q", err, s)
  1074. }
  1075. if h.ConnectionClose() != connectionClose {
  1076. t.Fatalf("unexpected connectionClose %v. Expecting %v. response=%q", h.ConnectionClose(), connectionClose, s)
  1077. }
  1078. }
  1079. func testRequestHeaderHTTPVer(t *testing.T, s string, connectionClose bool) {
  1080. var h RequestHeader
  1081. r := bytes.NewBufferString(s)
  1082. br := bufio.NewReader(r)
  1083. if err := h.Read(br); err != nil {
  1084. t.Fatalf("unexpected error: %s. request=%q", err, s)
  1085. }
  1086. if h.ConnectionClose() != connectionClose {
  1087. t.Fatalf("unexpected connectionClose %v. Expecting %v. request=%q", h.ConnectionClose(), connectionClose, s)
  1088. }
  1089. }
  1090. func TestResponseHeaderCopyTo(t *testing.T) {
  1091. t.Parallel()
  1092. var h ResponseHeader
  1093. h.Set(HeaderSetCookie, "foo=bar")
  1094. h.Set(HeaderContentType, "foobar")
  1095. h.Set("AAA-BBB", "aaaa")
  1096. h.Set(HeaderTrailer, "foo, bar")
  1097. var h1 ResponseHeader
  1098. h.CopyTo(&h1)
  1099. if !bytes.Equal(h1.Peek("Set-cookie"), h.Peek("Set-Cookie")) {
  1100. t.Fatalf("unexpected cookie %q. Expected %q", h1.Peek("set-cookie"), h.Peek("set-cookie"))
  1101. }
  1102. if !bytes.Equal(h1.Peek(HeaderContentType), h.Peek(HeaderContentType)) {
  1103. t.Fatalf("unexpected content-type %q. Expected %q", h1.Peek("content-type"), h.Peek("content-type"))
  1104. }
  1105. if !bytes.Equal(h1.Peek("aaa-bbb"), h.Peek("AAA-BBB")) {
  1106. t.Fatalf("unexpected aaa-bbb %q. Expected %q", h1.Peek("aaa-bbb"), h.Peek("aaa-bbb"))
  1107. }
  1108. if !bytes.Equal(h1.Peek(HeaderTrailer), h.Peek(HeaderTrailer)) {
  1109. t.Fatalf("unexpected trailer %q. Expected %q", h1.Peek(HeaderTrailer), h.Peek(HeaderTrailer))
  1110. }
  1111. // flush buf
  1112. h.bufKV = argsKV{}
  1113. h1.bufKV = argsKV{}
  1114. if !reflect.DeepEqual(h, h1) { //nolint:govet
  1115. t.Fatalf("ResponseHeaderCopyTo fail, src: \n%+v\ndst: \n%+v\n", h, h1) //nolint:govet
  1116. }
  1117. }
  1118. func TestRequestHeaderCopyTo(t *testing.T) {
  1119. t.Parallel()
  1120. var h RequestHeader
  1121. h.Set(HeaderCookie, "aa=bb; cc=dd")
  1122. h.Set(HeaderContentType, "foobar")
  1123. h.Set(HeaderHost, "aaaa")
  1124. h.Set("aaaxxx", "123")
  1125. h.Set(HeaderTrailer, "foo, bar")
  1126. var h1 RequestHeader
  1127. h.CopyTo(&h1)
  1128. if !bytes.Equal(h1.Peek("cookie"), h.Peek(HeaderCookie)) {
  1129. t.Fatalf("unexpected cookie after copying: %q. Expected %q", h1.Peek("cookie"), h.Peek("cookie"))
  1130. }
  1131. if !bytes.Equal(h1.Peek("content-type"), h.Peek(HeaderContentType)) {
  1132. t.Fatalf("unexpected content-type %q. Expected %q", h1.Peek("content-type"), h.Peek("content-type"))
  1133. }
  1134. if !bytes.Equal(h1.Peek("host"), h.Peek("host")) {
  1135. t.Fatalf("unexpected host %q. Expected %q", h1.Peek("host"), h.Peek("host"))
  1136. }
  1137. if !bytes.Equal(h1.Peek("aaaxxx"), h.Peek("aaaxxx")) {
  1138. t.Fatalf("unexpected aaaxxx %q. Expected %q", h1.Peek("aaaxxx"), h.Peek("aaaxxx"))
  1139. }
  1140. if !bytes.Equal(h1.Peek(HeaderTrailer), h.Peek(HeaderTrailer)) {
  1141. t.Fatalf("unexpected trailer %q. Expected %q", h1.Peek(HeaderTrailer), h.Peek(HeaderTrailer))
  1142. }
  1143. // flush buf
  1144. h.bufKV = argsKV{}
  1145. h1.bufKV = argsKV{}
  1146. if !reflect.DeepEqual(h, h1) { //nolint:govet
  1147. t.Fatalf("RequestHeaderCopyTo fail, src: \n%+v\ndst: \n%+v\n", h, h1) //nolint:govet
  1148. }
  1149. }
  1150. func TestResponseContentTypeNoDefaultNotEmpty(t *testing.T) {
  1151. t.Parallel()
  1152. var h ResponseHeader
  1153. h.SetNoDefaultContentType(true)
  1154. h.SetContentLength(5)
  1155. headers := h.String()
  1156. if strings.Contains(headers, "Content-Type: \r\n") {
  1157. t.Fatalf("ResponseContentTypeNoDefaultNotEmpty fail, response: \n%+v\noutcome: \n%q\n", h, headers) //nolint:govet
  1158. }
  1159. }
  1160. func TestRequestContentTypeDefaultNotEmpty(t *testing.T) {
  1161. t.Parallel()
  1162. var h RequestHeader
  1163. h.SetMethod(MethodPost)
  1164. h.SetContentLength(5)
  1165. w := &bytes.Buffer{}
  1166. bw := bufio.NewWriter(w)
  1167. if err := h.Write(bw); err != nil {
  1168. t.Fatalf("Unexpected error: %s", err)
  1169. }
  1170. if err := bw.Flush(); err != nil {
  1171. t.Fatalf("Unexpected error: %s", err)
  1172. }
  1173. var h1 RequestHeader
  1174. br := bufio.NewReader(w)
  1175. if err := h1.Read(br); err != nil {
  1176. t.Fatalf("Unexpected error: %s", err)
  1177. }
  1178. if string(h1.contentType) != "application/octet-stream" {
  1179. t.Fatalf("unexpected Content-Type %q. Expecting %q", h1.contentType, "application/octet-stream")
  1180. }
  1181. }
  1182. func TestResponseDateNoDefaultNotEmpty(t *testing.T) {
  1183. t.Parallel()
  1184. var h ResponseHeader
  1185. h.noDefaultDate = true
  1186. headers := h.String()
  1187. if strings.Contains(headers, "\r\nDate: ") {
  1188. t.Fatalf("ResponseDateNoDefaultNotEmpty fail, response: \n%+v\noutcome: \n%q\n", h, headers) //nolint:govet
  1189. }
  1190. }
  1191. func TestRequestHeaderConnectionClose(t *testing.T) {
  1192. t.Parallel()
  1193. var h RequestHeader
  1194. h.Set(HeaderConnection, "close")
  1195. h.Set(HeaderHost, "foobar")
  1196. if !h.ConnectionClose() {
  1197. t.Fatalf("connection: close not set")
  1198. }
  1199. var w bytes.Buffer
  1200. bw := bufio.NewWriter(&w)
  1201. if err := h.Write(bw); err != nil {
  1202. t.Fatalf("unexpected error: %s", err)
  1203. }
  1204. if err := bw.Flush(); err != nil {
  1205. t.Fatalf("unexpected error: %s", err)
  1206. }
  1207. var h1 RequestHeader
  1208. br := bufio.NewReader(&w)
  1209. if err := h1.Read(br); err != nil {
  1210. t.Fatalf("error when reading request header: %s", err)
  1211. }
  1212. if !h1.ConnectionClose() {
  1213. t.Fatalf("unexpected connection: close value: %v", h1.ConnectionClose())
  1214. }
  1215. if string(h1.Peek(HeaderConnection)) != "close" {
  1216. t.Fatalf("unexpected connection value: %q. Expecting %q", h.Peek("Connection"), "close")
  1217. }
  1218. }
  1219. func TestRequestHeaderSetCookie(t *testing.T) {
  1220. t.Parallel()
  1221. var h RequestHeader
  1222. h.Set("Cookie", "foo=bar; baz=aaa")
  1223. h.Set("cOOkie", "xx=yyy")
  1224. if string(h.Cookie("foo")) != "bar" {
  1225. t.Fatalf("Unexpected cookie %q. Expecting %q", h.Cookie("foo"), "bar")
  1226. }
  1227. if string(h.Cookie("baz")) != "aaa" {
  1228. t.Fatalf("Unexpected cookie %q. Expecting %q", h.Cookie("baz"), "aaa")
  1229. }
  1230. if string(h.Cookie("xx")) != "yyy" {
  1231. t.Fatalf("unexpected cookie %q. Expecting %q", h.Cookie("xx"), "yyy")
  1232. }
  1233. }
  1234. func TestResponseHeaderSetCookie(t *testing.T) {
  1235. t.Parallel()
  1236. var h ResponseHeader
  1237. h.Set("set-cookie", "foo=bar; path=/aa/bb; domain=aaa.com")
  1238. h.Set(HeaderSetCookie, "aaaaa=bxx")
  1239. var c Cookie
  1240. c.SetKey("foo")
  1241. if !h.Cookie(&c) {
  1242. t.Fatalf("cannot obtain %q cookie", c.Key())
  1243. }
  1244. if string(c.Value()) != "bar" {
  1245. t.Fatalf("unexpected cookie value %q. Expected %q", c.Value(), "bar")
  1246. }
  1247. if string(c.Path()) != "/aa/bb" {
  1248. t.Fatalf("unexpected cookie path %q. Expected %q", c.Path(), "/aa/bb")
  1249. }
  1250. if string(c.Domain()) != "aaa.com" {
  1251. t.Fatalf("unexpected cookie domain %q. Expected %q", c.Domain(), "aaa.com")
  1252. }
  1253. c.SetKey("aaaaa")
  1254. if !h.Cookie(&c) {
  1255. t.Fatalf("cannot obtain %q cookie", c.Key())
  1256. }
  1257. if string(c.Value()) != "bxx" {
  1258. t.Fatalf("unexpected cookie value %q. Expecting %q", c.Value(), "bxx")
  1259. }
  1260. }
  1261. func TestResponseHeaderVisitAll(t *testing.T) {
  1262. t.Parallel()
  1263. var h ResponseHeader
  1264. r := bytes.NewBufferString("HTTP/1.1 200 OK\r\nContent-Type: aa\r\nContent-Length: 123\r\nSet-Cookie: aa=bb; path=/foo/bar\r\nSet-Cookie: ccc\r\nTrailer: Foo, Bar\r\n\r\n")
  1265. br := bufio.NewReader(r)
  1266. if err := h.Read(br); err != nil {
  1267. t.Fatalf("Unexpected error: %s", err)
  1268. }
  1269. if h.Len() != 5 {
  1270. t.Fatalf("Unexpected number of headers: %d. Expected 5", h.Len())
  1271. }
  1272. contentLengthCount := 0
  1273. contentTypeCount := 0
  1274. cookieCount := 0
  1275. h.VisitAll(func(key, value []byte) {
  1276. k := string(key)
  1277. v := string(value)
  1278. switch k {
  1279. case HeaderContentLength:
  1280. if v != string(h.Peek(k)) {
  1281. t.Fatalf("unexpected content-length: %q. Expecting %q", v, h.Peek(k))
  1282. }
  1283. contentLengthCount++
  1284. case HeaderContentType:
  1285. if v != string(h.Peek(k)) {
  1286. t.Fatalf("Unexpected content-type: %q. Expected %q", v, h.Peek(k))
  1287. }
  1288. contentTypeCount++
  1289. case HeaderSetCookie:
  1290. if cookieCount == 0 && v != "aa=bb; path=/foo/bar" {
  1291. t.Fatalf("unexpected cookie header: %q. Expected %q", v, "aa=bb; path=/foo/bar")
  1292. }
  1293. if cookieCount == 1 && v != "ccc" {
  1294. t.Fatalf("unexpected cookie header: %q. Expected %q", v, "ccc")
  1295. }
  1296. cookieCount++
  1297. case HeaderTrailer:
  1298. if v != "Foo, Bar" {
  1299. t.Fatalf("Unexpected trailer header %q. Expected %q", v, "Foo, Bar")
  1300. }
  1301. default:
  1302. t.Fatalf("unexpected header %q=%q", k, v)
  1303. }
  1304. })
  1305. if contentLengthCount != 1 {
  1306. t.Fatalf("unexpected number of content-length headers: %d. Expected 1", contentLengthCount)
  1307. }
  1308. if contentTypeCount != 1 {
  1309. t.Fatalf("unexpected number of content-type headers: %d. Expected 1", contentTypeCount)
  1310. }
  1311. if cookieCount != 2 {
  1312. t.Fatalf("unexpected number of cookie header: %d. Expected 2", cookieCount)
  1313. }
  1314. }
  1315. func TestRequestHeaderVisitAll(t *testing.T) {
  1316. t.Parallel()
  1317. var h RequestHeader
  1318. r := bytes.NewBufferString("GET / HTTP/1.1\r\nHost: aa.com\r\nXX: YYY\r\nXX: ZZ\r\nCookie: a=b; c=d\r\nTrailer: Foo, Bar\r\n\r\n")
  1319. br := bufio.NewReader(r)
  1320. if err := h.Read(br); err != nil {
  1321. t.Fatalf("Unexpected error: %s", err)
  1322. }
  1323. if h.Len() != 5 {
  1324. t.Fatalf("Unexpected number of header: %d. Expected 5", h.Len())
  1325. }
  1326. hostCount := 0
  1327. xxCount := 0
  1328. cookieCount := 0
  1329. h.VisitAll(func(key, value []byte) {
  1330. k := string(key)
  1331. v := string(value)
  1332. switch k {
  1333. case HeaderHost:
  1334. if v != string(h.Peek(k)) {
  1335. t.Fatalf("Unexpected host value %q. Expected %q", v, h.Peek(k))
  1336. }
  1337. hostCount++
  1338. case "Xx":
  1339. if xxCount == 0 && v != "YYY" {
  1340. t.Fatalf("Unexpected value %q. Expected %q", v, "YYY")
  1341. }
  1342. if xxCount == 1 && v != "ZZ" {
  1343. t.Fatalf("Unexpected value %q. Expected %q", v, "ZZ")
  1344. }
  1345. xxCount++
  1346. case HeaderCookie:
  1347. if v != "a=b; c=d" {
  1348. t.Fatalf("Unexpected cookie %q. Expected %q", v, "a=b; c=d")
  1349. }
  1350. cookieCount++
  1351. case HeaderTrailer:
  1352. if v != "Foo, Bar" {
  1353. t.Fatalf("Unexpected trailer header %q. Expected %q", v, "Foo, Bar")
  1354. }
  1355. default:
  1356. t.Fatalf("Unexpected header %q=%q", k, v)
  1357. }
  1358. })
  1359. if hostCount != 1 {
  1360. t.Fatalf("Unexpected number of host headers detected %d. Expected 1", hostCount)
  1361. }
  1362. if xxCount != 2 {
  1363. t.Fatalf("Unexpected number of xx headers detected %d. Expected 2", xxCount)
  1364. }
  1365. if cookieCount != 1 {
  1366. t.Fatalf("Unexpected number of cookie headers %d. Expected 1", cookieCount)
  1367. }
  1368. }
  1369. func TestRequestHeaderVisitAllInOrder(t *testing.T) {
  1370. t.Parallel()
  1371. var h RequestHeader
  1372. r := bytes.NewBufferString("GET / HTTP/1.1\r\nContent-Type: aa\r\nCookie: a=b\r\nHost: example.com\r\nUser-Agent: xxx\r\n\r\n")
  1373. br := bufio.NewReader(r)
  1374. if err := h.Read(br); err != nil {
  1375. t.Fatalf("Unexpected error: %s", err)
  1376. }
  1377. if h.Len() != 4 {
  1378. t.Fatalf("Unexpected number of headers: %d. Expected 4", h.Len())
  1379. }
  1380. order := []string{
  1381. HeaderContentType,
  1382. HeaderCookie,
  1383. HeaderHost,
  1384. HeaderUserAgent,
  1385. }
  1386. values := []string{
  1387. "aa",
  1388. "a=b",
  1389. "example.com",
  1390. "xxx",
  1391. }
  1392. h.VisitAllInOrder(func(key, value []byte) {
  1393. if len(order) == 0 {
  1394. t.Fatalf("no more headers expected, got %q", key)
  1395. }
  1396. if order[0] != string(key) {
  1397. t.Fatalf("expected header %q got %q", order[0], key)
  1398. }
  1399. if values[0] != string(value) {
  1400. t.Fatalf("expected header value %q got %q", values[0], value)
  1401. }
  1402. order = order[1:]
  1403. values = values[1:]
  1404. })
  1405. }
  1406. func TestResponseHeaderAddTrailerError(t *testing.T) {
  1407. t.Parallel()
  1408. var h ResponseHeader
  1409. err := h.AddTrailer("Foo, Content-Length , Bar,Transfer-Encoding,")
  1410. expectedTrailer := "Foo, Bar"
  1411. if !errors.Is(err, ErrBadTrailer) {
  1412. t.Fatalf("unexpected err %q. Expected %q", err, ErrBadTrailer)
  1413. }
  1414. if trailer := string(h.Peek(HeaderTrailer)); trailer != expectedTrailer {
  1415. t.Fatalf("unexpected trailer %q. Expected %q", trailer, expectedTrailer)
  1416. }
  1417. }
  1418. func TestRequestHeaderAddTrailerError(t *testing.T) {
  1419. t.Parallel()
  1420. var h RequestHeader
  1421. err := h.AddTrailer("Foo, Content-Length , Bar,Transfer-Encoding,")
  1422. expectedTrailer := "Foo, Bar"
  1423. if !errors.Is(err, ErrBadTrailer) {
  1424. t.Fatalf("unexpected err %q. Expected %q", err, ErrBadTrailer)
  1425. }
  1426. if trailer := string(h.Peek(HeaderTrailer)); trailer != expectedTrailer {
  1427. t.Fatalf("unexpected trailer %q. Expected %q", trailer, expectedTrailer)
  1428. }
  1429. }
  1430. func TestResponseHeaderCookie(t *testing.T) {
  1431. t.Parallel()
  1432. var h ResponseHeader
  1433. var c Cookie
  1434. c.SetKey("foobar")
  1435. c.SetValue("aaa")
  1436. h.SetCookie(&c)
  1437. c.SetKey("йцук")
  1438. c.SetDomain("foobar.com")
  1439. h.SetCookie(&c)
  1440. c.Reset()
  1441. c.SetKey("foobar")
  1442. if !h.Cookie(&c) {
  1443. t.Fatalf("Cannot find cookie %q", c.Key())
  1444. }
  1445. var expectedC1 Cookie
  1446. expectedC1.SetKey("foobar")
  1447. expectedC1.SetValue("aaa")
  1448. if !equalCookie(&expectedC1, &c) {
  1449. t.Fatalf("unexpected cookie\n%#v\nExpected\n%#v\n", &c, &expectedC1)
  1450. }
  1451. c.SetKey("йцук")
  1452. if !h.Cookie(&c) {
  1453. t.Fatalf("cannot find cookie %q", c.Key())
  1454. }
  1455. var expectedC2 Cookie
  1456. expectedC2.SetKey("йцук")
  1457. expectedC2.SetValue("aaa")
  1458. expectedC2.SetDomain("foobar.com")
  1459. if !equalCookie(&expectedC2, &c) {
  1460. t.Fatalf("unexpected cookie\n%v\nExpected\n%v\n", &c, &expectedC2)
  1461. }
  1462. h.VisitAllCookie(func(key, value []byte) {
  1463. var cc Cookie
  1464. if err := cc.ParseBytes(value); err != nil {
  1465. t.Fatal(err)
  1466. }
  1467. if !bytes.Equal(key, cc.Key()) {
  1468. t.Fatalf("Unexpected cookie key %q. Expected %q", key, cc.Key())
  1469. }
  1470. switch {
  1471. case bytes.Equal(key, []byte("foobar")):
  1472. if !equalCookie(&expectedC1, &cc) {
  1473. t.Fatalf("unexpected cookie\n%v\nExpected\n%v\n", &cc, &expectedC1)
  1474. }
  1475. case bytes.Equal(key, []byte("йцук")):
  1476. if !equalCookie(&expectedC2, &cc) {
  1477. t.Fatalf("unexpected cookie\n%v\nExpected\n%v\n", &cc, &expectedC2)
  1478. }
  1479. default:
  1480. t.Fatalf("unexpected cookie key %q", key)
  1481. }
  1482. })
  1483. w := &bytes.Buffer{}
  1484. bw := bufio.NewWriter(w)
  1485. if err := h.Write(bw); err != nil {
  1486. t.Fatalf("unexpected error: %s", err)
  1487. }
  1488. if err := bw.Flush(); err != nil {
  1489. t.Fatalf("unexpected error: %s", err)
  1490. }
  1491. h.DelAllCookies()
  1492. var h1 ResponseHeader
  1493. br := bufio.NewReader(w)
  1494. if err := h1.Read(br); err != nil {
  1495. t.Fatalf("unexpected error: %s", err)
  1496. }
  1497. c.SetKey("foobar")
  1498. if !h1.Cookie(&c) {
  1499. t.Fatalf("Cannot find cookie %q", c.Key())
  1500. }
  1501. if !equalCookie(&expectedC1, &c) {
  1502. t.Fatalf("unexpected cookie\n%v\nExpected\n%v\n", &c, &expectedC1)
  1503. }
  1504. h1.DelCookie("foobar")
  1505. if h.Cookie(&c) {
  1506. t.Fatalf("Unexpected cookie found: %v", &c)
  1507. }
  1508. if h1.Cookie(&c) {
  1509. t.Fatalf("Unexpected cookie found: %v", &c)
  1510. }
  1511. c.SetKey("йцук")
  1512. if !h1.Cookie(&c) {
  1513. t.Fatalf("cannot find cookie %q", c.Key())
  1514. }
  1515. if !equalCookie(&expectedC2, &c) {
  1516. t.Fatalf("unexpected cookie\n%v\nExpected\n%v\n", &c, &expectedC2)
  1517. }
  1518. h1.DelCookie("йцук")
  1519. if h.Cookie(&c) {
  1520. t.Fatalf("Unexpected cookie found: %v", &c)
  1521. }
  1522. if h1.Cookie(&c) {
  1523. t.Fatalf("Unexpected cookie found: %v", &c)
  1524. }
  1525. }
  1526. func equalCookie(c1, c2 *Cookie) bool {
  1527. if !bytes.Equal(c1.Key(), c2.Key()) {
  1528. return false
  1529. }
  1530. if !bytes.Equal(c1.Value(), c2.Value()) {
  1531. return false
  1532. }
  1533. if !c1.Expire().Equal(c2.Expire()) {
  1534. return false
  1535. }
  1536. if !bytes.Equal(c1.Domain(), c2.Domain()) {
  1537. return false
  1538. }
  1539. if !bytes.Equal(c1.Path(), c2.Path()) {
  1540. return false
  1541. }
  1542. return true
  1543. }
  1544. func TestRequestHeaderCookie(t *testing.T) {
  1545. t.Parallel()
  1546. var h RequestHeader
  1547. h.SetRequestURI("/foobar")
  1548. h.Set(HeaderHost, "foobar.com")
  1549. h.SetCookie("foo", "bar")
  1550. h.SetCookie("привет", "мир")
  1551. if string(h.Cookie("foo")) != "bar" {
  1552. t.Fatalf("Unexpected cookie value %q. Exepcted %q", h.Cookie("foo"), "bar")
  1553. }
  1554. if string(h.Cookie("привет")) != "мир" {
  1555. t.Fatalf("Unexpected cookie value %q. Expected %q", h.Cookie("привет"), "мир")
  1556. }
  1557. w := &bytes.Buffer{}
  1558. bw := bufio.NewWriter(w)
  1559. if err := h.Write(bw); err != nil {
  1560. t.Fatalf("Unexpected error: %s", err)
  1561. }
  1562. if err := bw.Flush(); err != nil {
  1563. t.Fatalf("Unexpected error: %s", err)
  1564. }
  1565. var h1 RequestHeader
  1566. br := bufio.NewReader(w)
  1567. if err := h1.Read(br); err != nil {
  1568. t.Fatalf("Unexpected error: %s", err)
  1569. }
  1570. if !bytes.Equal(h1.Cookie("foo"), h.Cookie("foo")) {
  1571. t.Fatalf("Unexpected cookie value %q. Exepcted %q", h1.Cookie("foo"), h.Cookie("foo"))
  1572. }
  1573. h1.DelCookie("foo")
  1574. if len(h1.Cookie("foo")) > 0 {
  1575. t.Fatalf("Unexpected cookie found: %q", h1.Cookie("foo"))
  1576. }
  1577. if !bytes.Equal(h1.Cookie("привет"), h.Cookie("привет")) {
  1578. t.Fatalf("Unexpected cookie value %q. Expected %q", h1.Cookie("привет"), h.Cookie("привет"))
  1579. }
  1580. h1.DelCookie("привет")
  1581. if len(h1.Cookie("привет")) > 0 {
  1582. t.Fatalf("Unexpected cookie found: %q", h1.Cookie("привет"))
  1583. }
  1584. h.DelAllCookies()
  1585. if len(h.Cookie("foo")) > 0 {
  1586. t.Fatalf("Unexpected cookie found: %q", h.Cookie("foo"))
  1587. }
  1588. if len(h.Cookie("привет")) > 0 {
  1589. t.Fatalf("Unexpected cookie found: %q", h.Cookie("привет"))
  1590. }
  1591. }
  1592. func TestResponseHeaderCookieIssue4(t *testing.T) {
  1593. t.Parallel()
  1594. var h ResponseHeader
  1595. c := AcquireCookie()
  1596. c.SetKey("foo")
  1597. c.SetValue("bar")
  1598. h.SetCookie(c)
  1599. if string(h.Peek(HeaderSetCookie)) != "foo=bar" {
  1600. t.Fatalf("Unexpected Set-Cookie header %q. Expected %q", h.Peek(HeaderSetCookie), "foo=bar")
  1601. }
  1602. cookieSeen := false
  1603. h.VisitAll(func(key, value []byte) {
  1604. switch string(key) {
  1605. case HeaderSetCookie:
  1606. cookieSeen = true
  1607. }
  1608. })
  1609. if !cookieSeen {
  1610. t.Fatalf("Set-Cookie not present in VisitAll")
  1611. }
  1612. c = AcquireCookie()
  1613. c.SetKey("foo")
  1614. h.Cookie(c)
  1615. if string(c.Value()) != "bar" {
  1616. t.Fatalf("Unexpected cookie value %q. Exepcted %q", c.Value(), "bar")
  1617. }
  1618. if string(h.Peek(HeaderSetCookie)) != "foo=bar" {
  1619. t.Fatalf("Unexpected Set-Cookie header %q. Expected %q", h.Peek(HeaderSetCookie), "foo=bar")
  1620. }
  1621. cookieSeen = false
  1622. h.VisitAll(func(key, value []byte) {
  1623. switch string(key) {
  1624. case HeaderSetCookie:
  1625. cookieSeen = true
  1626. }
  1627. })
  1628. if !cookieSeen {
  1629. t.Fatalf("Set-Cookie not present in VisitAll")
  1630. }
  1631. }
  1632. func TestRequestHeaderCookieIssue313(t *testing.T) {
  1633. t.Parallel()
  1634. var h RequestHeader
  1635. h.SetRequestURI("/")
  1636. h.Set(HeaderHost, "foobar.com")
  1637. h.SetCookie("foo", "bar")
  1638. if string(h.Peek(HeaderCookie)) != "foo=bar" {
  1639. t.Fatalf("Unexpected Cookie header %q. Expected %q", h.Peek(HeaderCookie), "foo=bar")
  1640. }
  1641. cookieSeen := false
  1642. h.VisitAll(func(key, value []byte) {
  1643. switch string(key) {
  1644. case HeaderCookie:
  1645. cookieSeen = true
  1646. }
  1647. })
  1648. if !cookieSeen {
  1649. t.Fatalf("Cookie not present in VisitAll")
  1650. }
  1651. if string(h.Cookie("foo")) != "bar" {
  1652. t.Fatalf("Unexpected cookie value %q. Exepcted %q", h.Cookie("foo"), "bar")
  1653. }
  1654. if string(h.Peek(HeaderCookie)) != "foo=bar" {
  1655. t.Fatalf("Unexpected Cookie header %q. Expected %q", h.Peek(HeaderCookie), "foo=bar")
  1656. }
  1657. cookieSeen = false
  1658. h.VisitAll(func(key, value []byte) {
  1659. switch string(key) {
  1660. case HeaderCookie:
  1661. cookieSeen = true
  1662. }
  1663. })
  1664. if !cookieSeen {
  1665. t.Fatalf("Cookie not present in VisitAll")
  1666. }
  1667. }
  1668. func TestRequestHeaderMethod(t *testing.T) {
  1669. t.Parallel()
  1670. // common http methods
  1671. testRequestHeaderMethod(t, MethodGet)
  1672. testRequestHeaderMethod(t, MethodPost)
  1673. testRequestHeaderMethod(t, MethodHead)
  1674. testRequestHeaderMethod(t, MethodDelete)
  1675. // non-http methods
  1676. testRequestHeaderMethod(t, "foobar")
  1677. testRequestHeaderMethod(t, "ABC")
  1678. }
  1679. func testRequestHeaderMethod(t *testing.T, expectedMethod string) {
  1680. var h RequestHeader
  1681. h.SetMethod(expectedMethod)
  1682. m := h.Method()
  1683. if string(m) != expectedMethod {
  1684. t.Fatalf("unexpected method: %q. Expecting %q", m, expectedMethod)
  1685. }
  1686. s := h.String()
  1687. var h1 RequestHeader
  1688. br := bufio.NewReader(bytes.NewBufferString(s))
  1689. if err := h1.Read(br); err != nil {
  1690. t.Fatalf("unexpected error: %s", err)
  1691. }
  1692. m1 := h1.Method()
  1693. if string(m) != string(m1) {
  1694. t.Fatalf("unexpected method: %q. Expecting %q", m, m1)
  1695. }
  1696. }
  1697. func TestRequestHeaderSetGet(t *testing.T) {
  1698. t.Parallel()
  1699. h := &RequestHeader{}
  1700. h.SetRequestURI("/aa/bbb")
  1701. h.SetMethod(MethodPost)
  1702. h.Set("foo", "bar")
  1703. h.Set("host", "12345")
  1704. h.Set("content-type", "aaa/bbb")
  1705. h.Set("content-length", "1234")
  1706. h.Set("user-agent", "aaabbb")
  1707. h.Set("referer", "axcv")
  1708. h.Set("baz", "xxxxx")
  1709. h.Set("transfer-encoding", "chunked")
  1710. h.Set("connection", "close")
  1711. expectRequestHeaderGet(t, h, "Foo", "bar")
  1712. expectRequestHeaderGet(t, h, HeaderHost, "12345")
  1713. expectRequestHeaderGet(t, h, HeaderContentType, "aaa/bbb")
  1714. expectRequestHeaderGet(t, h, HeaderContentLength, "1234")
  1715. expectRequestHeaderGet(t, h, "USER-AGent", "aaabbb")
  1716. expectRequestHeaderGet(t, h, HeaderReferer, "axcv")
  1717. expectRequestHeaderGet(t, h, "baz", "xxxxx")
  1718. expectRequestHeaderGet(t, h, HeaderTransferEncoding, "")
  1719. expectRequestHeaderGet(t, h, "connecTION", "close")
  1720. if !h.ConnectionClose() {
  1721. t.Fatalf("unset connection: close")
  1722. }
  1723. if h.ContentLength() != 1234 {
  1724. t.Fatalf("Unexpected content-length %d. Expected %d", h.ContentLength(), 1234)
  1725. }
  1726. w := &bytes.Buffer{}
  1727. bw := bufio.NewWriter(w)
  1728. err := h.Write(bw)
  1729. if err != nil {
  1730. t.Fatalf("Unexpected error when writing request header: %s", err)
  1731. }
  1732. if err := bw.Flush(); err != nil {
  1733. t.Fatalf("Unexpected error when flushing request header: %s", err)
  1734. }
  1735. var h1 RequestHeader
  1736. br := bufio.NewReader(w)
  1737. if err = h1.Read(br); err != nil {
  1738. t.Fatalf("Unexpected error when reading request header: %s", err)
  1739. }
  1740. if h1.ContentLength() != h.ContentLength() {
  1741. t.Fatalf("Unexpected Content-Length %d. Expected %d", h1.ContentLength(), h.ContentLength())
  1742. }
  1743. expectRequestHeaderGet(t, &h1, "Foo", "bar")
  1744. expectRequestHeaderGet(t, &h1, "HOST", "12345")
  1745. expectRequestHeaderGet(t, &h1, HeaderContentType, "aaa/bbb")
  1746. expectRequestHeaderGet(t, &h1, HeaderContentLength, "1234")
  1747. expectRequestHeaderGet(t, &h1, "USER-AGent", "aaabbb")
  1748. expectRequestHeaderGet(t, &h1, HeaderReferer, "axcv")
  1749. expectRequestHeaderGet(t, &h1, "baz", "xxxxx")
  1750. expectRequestHeaderGet(t, &h1, HeaderTransferEncoding, "")
  1751. expectRequestHeaderGet(t, &h1, HeaderConnection, "close")
  1752. if !h1.ConnectionClose() {
  1753. t.Fatalf("unset connection: close")
  1754. }
  1755. }
  1756. func TestResponseHeaderSetGet(t *testing.T) {
  1757. t.Parallel()
  1758. h := &ResponseHeader{}
  1759. h.Set("foo", "bar")
  1760. h.Set("content-type", "aaa/bbb")
  1761. h.Set("connection", "close")
  1762. h.Set("content-length", "1234")
  1763. h.Set(HeaderServer, "aaaa")
  1764. h.Set("baz", "xxxxx")
  1765. h.Set(HeaderTransferEncoding, "chunked")
  1766. expectResponseHeaderGet(t, h, "Foo", "bar")
  1767. expectResponseHeaderGet(t, h, HeaderContentType, "aaa/bbb")
  1768. expectResponseHeaderGet(t, h, HeaderConnection, "close")
  1769. expectResponseHeaderGet(t, h, HeaderContentLength, "1234")
  1770. expectResponseHeaderGet(t, h, "seRVer", "aaaa")
  1771. expectResponseHeaderGet(t, h, "baz", "xxxxx")
  1772. expectResponseHeaderGet(t, h, HeaderTransferEncoding, "")
  1773. if h.ContentLength() != 1234 {
  1774. t.Fatalf("Unexpected content-length %d. Expected %d", h.ContentLength(), 1234)
  1775. }
  1776. if !h.ConnectionClose() {
  1777. t.Fatalf("Unexpected Connection: close value %v. Expected %v", h.ConnectionClose(), true)
  1778. }
  1779. w := &bytes.Buffer{}
  1780. bw := bufio.NewWriter(w)
  1781. err := h.Write(bw)
  1782. if err != nil {
  1783. t.Fatalf("Unexpected error when writing response header: %s", err)
  1784. }
  1785. if err := bw.Flush(); err != nil {
  1786. t.Fatalf("Unexpected error when flushing response header: %s", err)
  1787. }
  1788. var h1 ResponseHeader
  1789. br := bufio.NewReader(w)
  1790. if err = h1.Read(br); err != nil {
  1791. t.Fatalf("Unexpected error when reading response header: %s", err)
  1792. }
  1793. if h1.ContentLength() != h.ContentLength() {
  1794. t.Fatalf("Unexpected Content-Length %d. Expected %d", h1.ContentLength(), h.ContentLength())
  1795. }
  1796. if h1.ConnectionClose() != h.ConnectionClose() {
  1797. t.Fatalf("unexpected connection: close %v. Expected %v", h1.ConnectionClose(), h.ConnectionClose())
  1798. }
  1799. expectResponseHeaderGet(t, &h1, "Foo", "bar")
  1800. expectResponseHeaderGet(t, &h1, HeaderContentType, "aaa/bbb")
  1801. expectResponseHeaderGet(t, &h1, HeaderConnection, "close")
  1802. expectResponseHeaderGet(t, &h1, "seRVer", "aaaa")
  1803. expectResponseHeaderGet(t, &h1, "baz", "xxxxx")
  1804. }
  1805. func expectRequestHeaderGet(t *testing.T, h *RequestHeader, key, expectedValue string) {
  1806. if string(h.Peek(key)) != expectedValue {
  1807. t.Fatalf("Unexpected value for key %q: %q. Expected %q", key, h.Peek(key), expectedValue)
  1808. }
  1809. }
  1810. func expectResponseHeaderGet(t *testing.T, h *ResponseHeader, key, expectedValue string) {
  1811. if string(h.Peek(key)) != expectedValue {
  1812. t.Fatalf("Unexpected value for key %q: %q. Expected %q", key, h.Peek(key), expectedValue)
  1813. }
  1814. }
  1815. func TestResponseHeaderConnectionClose(t *testing.T) {
  1816. t.Parallel()
  1817. testResponseHeaderConnectionClose(t, true)
  1818. testResponseHeaderConnectionClose(t, false)
  1819. }
  1820. func testResponseHeaderConnectionClose(t *testing.T, connectionClose bool) {
  1821. h := &ResponseHeader{}
  1822. if connectionClose {
  1823. h.SetConnectionClose()
  1824. }
  1825. h.SetContentLength(123)
  1826. w := &bytes.Buffer{}
  1827. bw := bufio.NewWriter(w)
  1828. err := h.Write(bw)
  1829. if err != nil {
  1830. t.Fatalf("Unexpected error when writing response header: %s", err)
  1831. }
  1832. if err := bw.Flush(); err != nil {
  1833. t.Fatalf("Unexpected error when flushing response header: %s", err)
  1834. }
  1835. var h1 ResponseHeader
  1836. br := bufio.NewReader(w)
  1837. err = h1.Read(br)
  1838. if err != nil {
  1839. t.Fatalf("Unexpected error when reading response header: %s", err)
  1840. }
  1841. if h1.ConnectionClose() != h.ConnectionClose() {
  1842. t.Fatalf("Unexpected value for ConnectionClose: %v. Expected %v", h1.ConnectionClose(), h.ConnectionClose())
  1843. }
  1844. }
  1845. func TestRequestHeaderTooBig(t *testing.T) {
  1846. t.Parallel()
  1847. s := "GET / HTTP/1.1\r\nHost: aaa.com\r\n" + getHeaders(10500) + "\r\n"
  1848. r := bytes.NewBufferString(s)
  1849. br := bufio.NewReaderSize(r, 4096)
  1850. h := &RequestHeader{}
  1851. err := h.Read(br)
  1852. if err == nil {
  1853. t.Fatalf("Expecting error when reading too big header")
  1854. }
  1855. }
  1856. func TestResponseHeaderTooBig(t *testing.T) {
  1857. t.Parallel()
  1858. s := "HTTP/1.1 200 OK\r\nContent-Type: sss\r\nContent-Length: 0\r\n" + getHeaders(100500) + "\r\n"
  1859. r := bytes.NewBufferString(s)
  1860. br := bufio.NewReaderSize(r, 4096)
  1861. h := &ResponseHeader{}
  1862. err := h.Read(br)
  1863. if err == nil {
  1864. t.Fatalf("Expecting error when reading too big header")
  1865. }
  1866. }
  1867. type bufioPeekReader struct {
  1868. s string
  1869. n int
  1870. }
  1871. func (r *bufioPeekReader) Read(b []byte) (int, error) {
  1872. if len(r.s) == 0 {
  1873. return 0, io.EOF
  1874. }
  1875. r.n++
  1876. n := r.n
  1877. if len(r.s) < n {
  1878. n = len(r.s)
  1879. }
  1880. src := []byte(r.s[:n])
  1881. r.s = r.s[n:]
  1882. n = copy(b, src)
  1883. return n, nil
  1884. }
  1885. func TestRequestHeaderBufioPeek(t *testing.T) {
  1886. t.Parallel()
  1887. r := &bufioPeekReader{
  1888. s: "GET / HTTP/1.1\r\nHost: foobar.com\r\n" + getHeaders(10) + "\r\naaaa",
  1889. }
  1890. br := bufio.NewReaderSize(r, 4096)
  1891. h := &RequestHeader{}
  1892. if err := h.Read(br); err != nil {
  1893. t.Fatalf("Unexpected error when reading request: %s", err)
  1894. }
  1895. verifyRequestHeader(t, h, -2, "/", "foobar.com", "", "")
  1896. }
  1897. func TestResponseHeaderBufioPeek(t *testing.T) {
  1898. t.Parallel()
  1899. r := &bufioPeekReader{
  1900. s: "HTTP/1.1 200 OK\r\nContent-Length: 10\r\nContent-Type: aaa\r\n" + getHeaders(10) + "\r\n0123456789",
  1901. }
  1902. br := bufio.NewReaderSize(r, 4096)
  1903. h := &ResponseHeader{}
  1904. if err := h.Read(br); err != nil {
  1905. t.Fatalf("Unexpected error when reading response: %s", err)
  1906. }
  1907. verifyResponseHeader(t, h, 200, 10, "aaa")
  1908. }
  1909. func getHeaders(n int) string {
  1910. var h []string
  1911. for i := 0; i < n; i++ {
  1912. h = append(h, fmt.Sprintf("Header_%d: Value_%d\r\n", i, i))
  1913. }
  1914. return strings.Join(h, "")
  1915. }
  1916. func TestResponseHeaderReadSuccess(t *testing.T) {
  1917. t.Parallel()
  1918. h := &ResponseHeader{}
  1919. // straight order of content-length and content-type
  1920. testResponseHeaderReadSuccess(t, h, "HTTP/1.1 200 OK\r\nContent-Length: 123\r\nContent-Type: text/html\r\n\r\n",
  1921. 200, 123, "text/html")
  1922. if h.ConnectionClose() {
  1923. t.Fatalf("unexpected connection: close")
  1924. }
  1925. // reverse order of content-length and content-type
  1926. testResponseHeaderReadSuccess(t, h, "HTTP/1.1 202 OK\r\nContent-Type: text/plain; encoding=utf-8\r\nContent-Length: 543\r\nConnection: close\r\n\r\n",
  1927. 202, 543, "text/plain; encoding=utf-8")
  1928. if !h.ConnectionClose() {
  1929. t.Fatalf("expecting connection: close")
  1930. }
  1931. // tranfer-encoding: chunked
  1932. testResponseHeaderReadSuccess(t, h, "HTTP/1.1 505 Internal error\r\nContent-Type: text/html\r\nTransfer-Encoding: chunked\r\n\r\n",
  1933. 505, -1, "text/html")
  1934. if h.ConnectionClose() {
  1935. t.Fatalf("unexpected connection: close")
  1936. }
  1937. // reverse order of content-type and tranfer-encoding
  1938. testResponseHeaderReadSuccess(t, h, "HTTP/1.1 343 foobar\r\nTransfer-Encoding: chunked\r\nContent-Type: text/json\r\n\r\n",
  1939. 343, -1, "text/json")
  1940. // additional headers
  1941. testResponseHeaderReadSuccess(t, h, "HTTP/1.1 100 Continue\r\nFoobar: baz\r\nContent-Type: aaa/bbb\r\nUser-Agent: x\r\nContent-Length: 123\r\nZZZ: werer\r\n\r\n",
  1942. 100, 123, "aaa/bbb")
  1943. // ancient http protocol
  1944. testResponseHeaderReadSuccess(t, h, "HTTP/0.9 300 OK\r\nContent-Length: 123\r\nContent-Type: text/html\r\n\r\nqqqq",
  1945. 300, 123, "text/html")
  1946. // lf instead of crlf
  1947. testResponseHeaderReadSuccess(t, h, "HTTP/1.1 200 OK\nContent-Length: 123\nContent-Type: text/html\n\n",
  1948. 200, 123, "text/html")
  1949. // Zero-length headers with mixed crlf and lf
  1950. testResponseHeaderReadSuccess(t, h, "HTTP/1.1 400 OK\nContent-Length: 345\nZero-Value: \r\nContent-Type: aaa\n: zero-key\r\n\r\nooa",
  1951. 400, 345, "aaa")
  1952. // No space after colon
  1953. testResponseHeaderReadSuccess(t, h, "HTTP/1.1 200 OK\nContent-Length:34\nContent-Type: sss\n\naaaa",
  1954. 200, 34, "sss")
  1955. // invalid case
  1956. testResponseHeaderReadSuccess(t, h, "HTTP/1.1 400 OK\nconTEnt-leNGTH: 123\nConTENT-TYPE: ass\n\n",
  1957. 400, 123, "ass")
  1958. // duplicate content-length
  1959. testResponseHeaderReadSuccess(t, h, "HTTP/1.1 200 OK\r\nContent-Length: 456\r\nContent-Type: foo/bar\r\nContent-Length: 321\r\n\r\n",
  1960. 200, 321, "foo/bar")
  1961. // duplicate content-type
  1962. testResponseHeaderReadSuccess(t, h, "HTTP/1.1 200 OK\r\nContent-Length: 234\r\nContent-Type: foo/bar\r\nContent-Type: baz/bar\r\n\r\n",
  1963. 200, 234, "baz/bar")
  1964. testResponseHeaderReadSuccess(t, h, "HTTP/1.1 300 OK\r\nContent-Type: foo/barr\r\nTransfer-Encoding: chunked\r\nContent-Length: 354\r\n\r\n",
  1965. 300, -1, "foo/barr")
  1966. // duplicate transfer-encoding: chunked
  1967. testResponseHeaderReadSuccess(t, h, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nTransfer-Encoding: chunked\r\nTransfer-Encoding: chunked\r\n\r\n",
  1968. 200, -1, "text/html")
  1969. // no reason string in the first line
  1970. testResponseHeaderReadSuccess(t, h, "HTTP/1.1 456\r\nContent-Type: xxx/yyy\r\nContent-Length: 134\r\n\r\naaaxxx",
  1971. 456, 134, "xxx/yyy")
  1972. // blank lines before the first line
  1973. testResponseHeaderReadSuccess(t, h, "\r\nHTTP/1.1 200 OK\r\nContent-Type: aa\r\nContent-Length: 0\r\n\r\nsss",
  1974. 200, 0, "aa")
  1975. if h.ConnectionClose() {
  1976. t.Fatalf("unexpected connection: close")
  1977. }
  1978. // no content-length (informational responses)
  1979. testResponseHeaderReadSuccess(t, h, "HTTP/1.1 101 OK\r\n\r\n",
  1980. 101, -2, "text/plain; charset=utf-8")
  1981. if h.ConnectionClose() {
  1982. t.Fatalf("expecting connection: keep-alive for informational response")
  1983. }
  1984. // no content-length (no-content responses)
  1985. testResponseHeaderReadSuccess(t, h, "HTTP/1.1 204 OK\r\n\r\n",
  1986. 204, -2, "text/plain; charset=utf-8")
  1987. if h.ConnectionClose() {
  1988. t.Fatalf("expecting connection: keep-alive for no-content response")
  1989. }
  1990. // no content-length (not-modified responses)
  1991. testResponseHeaderReadSuccess(t, h, "HTTP/1.1 304 OK\r\n\r\n",
  1992. 304, -2, "text/plain; charset=utf-8")
  1993. if h.ConnectionClose() {
  1994. t.Fatalf("expecting connection: keep-alive for not-modified response")
  1995. }
  1996. // no content-length (identity transfer-encoding)
  1997. testResponseHeaderReadSuccess(t, h, "HTTP/1.1 200 OK\r\nContent-Type: foo/bar\r\n\r\nabcdefg",
  1998. 200, -2, "foo/bar")
  1999. if !h.ConnectionClose() {
  2000. t.Fatalf("expecting connection: close for identity response")
  2001. }
  2002. // no content-type
  2003. testResponseHeaderReadSuccess(t, h, "HTTP/1.1 400 OK\r\nContent-Length: 123\r\n\r\nfoiaaa",
  2004. 400, 123, string(defaultContentType))
  2005. // no content-type and no default
  2006. h.SetNoDefaultContentType(true)
  2007. testResponseHeaderReadSuccess(t, h, "HTTP/1.1 400 OK\r\nContent-Length: 123\r\n\r\nfoiaaa",
  2008. 400, 123, "")
  2009. h.SetNoDefaultContentType(false)
  2010. // no headers
  2011. testResponseHeaderReadSuccess(t, h, "HTTP/1.1 200 OK\r\n\r\naaaabbb",
  2012. 200, -2, string(defaultContentType))
  2013. if !h.IsHTTP11() {
  2014. t.Fatalf("expecting http/1.1 protocol")
  2015. }
  2016. // ancient http protocol
  2017. testResponseHeaderReadSuccess(t, h, "HTTP/1.0 203 OK\r\nContent-Length: 123\r\nContent-Type: foobar\r\n\r\naaa",
  2018. 203, 123, "foobar")
  2019. if h.IsHTTP11() {
  2020. t.Fatalf("ancient protocol must be non-http/1.1")
  2021. }
  2022. if !h.ConnectionClose() {
  2023. t.Fatalf("expecting connection: close for ancient protocol")
  2024. }
  2025. // ancient http protocol with 'Connection: keep-alive' header.
  2026. testResponseHeaderReadSuccess(t, h, "HTTP/1.0 403 aa\r\nContent-Length: 0\r\nContent-Type: 2\r\nConnection: Keep-Alive\r\n\r\nww",
  2027. 403, 0, "2")
  2028. if h.IsHTTP11() {
  2029. t.Fatalf("ancient protocol must be non-http/1.1")
  2030. }
  2031. if h.ConnectionClose() {
  2032. t.Fatalf("expecting connection: keep-alive for ancient protocol")
  2033. }
  2034. }
  2035. func TestRequestHeaderReadSuccess(t *testing.T) {
  2036. t.Parallel()
  2037. h := &RequestHeader{}
  2038. // simple headers
  2039. testRequestHeaderReadSuccess(t, h, "GET /foo/bar HTTP/1.1\r\nHost: google.com\r\n\r\n",
  2040. -2, "/foo/bar", "google.com", "", "", nil)
  2041. if h.ConnectionClose() {
  2042. t.Fatalf("unexpected connection: close header")
  2043. }
  2044. // simple headers with body
  2045. testRequestHeaderReadSuccess(t, h, "GET /a/bar HTTP/1.1\r\nHost: gole.com\r\nconneCTION: close\r\n\r\nfoobar",
  2046. -2, "/a/bar", "gole.com", "", "", nil)
  2047. if !h.ConnectionClose() {
  2048. t.Fatalf("connection: close unset")
  2049. }
  2050. // ancient http protocol
  2051. testRequestHeaderReadSuccess(t, h, "GET /bar HTTP/1.0\r\nHost: gole\r\n\r\npppp",
  2052. -2, "/bar", "gole", "", "", nil)
  2053. if h.IsHTTP11() {
  2054. t.Fatalf("ancient http protocol cannot be http/1.1")
  2055. }
  2056. if !h.ConnectionClose() {
  2057. t.Fatalf("expecting connectionClose for ancient http protocol")
  2058. }
  2059. // ancient http protocol with 'Connection: keep-alive' header
  2060. testRequestHeaderReadSuccess(t, h, "GET /aa HTTP/1.0\r\nHost: bb\r\nConnection: keep-alive\r\n\r\nxxx",
  2061. -2, "/aa", "bb", "", "", nil)
  2062. if h.IsHTTP11() {
  2063. t.Fatalf("ancient http protocol cannot be http/1.1")
  2064. }
  2065. if h.ConnectionClose() {
  2066. t.Fatalf("unexpected 'connection: close' for ancient http protocol")
  2067. }
  2068. // complex headers with body
  2069. testRequestHeaderReadSuccess(t, h, "GET /aabar HTTP/1.1\r\nAAA: bbb\r\nHost: ole.com\r\nAA: bb\r\n\r\nzzz",
  2070. -2, "/aabar", "ole.com", "", "", nil)
  2071. if !h.IsHTTP11() {
  2072. t.Fatalf("expecting http/1.1 protocol")
  2073. }
  2074. if h.ConnectionClose() {
  2075. t.Fatalf("unexpected connection: close")
  2076. }
  2077. // lf instead of crlf
  2078. testRequestHeaderReadSuccess(t, h, "GET /foo/bar HTTP/1.1\nHost: google.com\n\n",
  2079. -2, "/foo/bar", "google.com", "", "", nil)
  2080. // post method
  2081. testRequestHeaderReadSuccess(t, h, "POST /aaa?bbb HTTP/1.1\r\nHost: foobar.com\r\nContent-Length: 1235\r\nContent-Type: aaa\r\n\r\nabcdef",
  2082. 1235, "/aaa?bbb", "foobar.com", "", "aaa", nil)
  2083. // zero-length headers with mixed crlf and lf
  2084. testRequestHeaderReadSuccess(t, h, "GET /a HTTP/1.1\nHost: aaa\r\nZero: \n: Zero-Value\n\r\nxccv",
  2085. -2, "/a", "aaa", "", "", nil)
  2086. // no space after colon
  2087. testRequestHeaderReadSuccess(t, h, "GET /a HTTP/1.1\nHost:aaaxd\n\nsdfds",
  2088. -2, "/a", "aaaxd", "", "", nil)
  2089. // get with zero content-length
  2090. testRequestHeaderReadSuccess(t, h, "GET /xxx HTTP/1.1\nHost: aaa.com\nContent-Length: 0\n\n",
  2091. 0, "/xxx", "aaa.com", "", "", nil)
  2092. // get with non-zero content-length
  2093. testRequestHeaderReadSuccess(t, h, "GET /xxx HTTP/1.1\nHost: aaa.com\nContent-Length: 123\n\n",
  2094. 123, "/xxx", "aaa.com", "", "", nil)
  2095. // invalid case
  2096. testRequestHeaderReadSuccess(t, h, "GET /aaa HTTP/1.1\nhoST: bbb.com\n\naas",
  2097. -2, "/aaa", "bbb.com", "", "", nil)
  2098. // referer
  2099. testRequestHeaderReadSuccess(t, h, "GET /asdf HTTP/1.1\nHost: aaa.com\nReferer: bb.com\n\naaa",
  2100. -2, "/asdf", "aaa.com", "bb.com", "", nil)
  2101. // duplicate host
  2102. testRequestHeaderReadSuccess(t, h, "GET /aa HTTP/1.1\r\nHost: aaaaaa.com\r\nHost: bb.com\r\n\r\n",
  2103. -2, "/aa", "bb.com", "", "", nil)
  2104. // post with duplicate content-type
  2105. testRequestHeaderReadSuccess(t, h, "POST /a HTTP/1.1\r\nHost: aa\r\nContent-Type: ab\r\nContent-Length: 123\r\nContent-Type: xx\r\n\r\n",
  2106. 123, "/a", "aa", "", "xx", nil)
  2107. // post with duplicate content-length
  2108. testRequestHeaderReadSuccess(t, h, "POST /xx HTTP/1.1\r\nHost: aa\r\nContent-Type: s\r\nContent-Length: 13\r\nContent-Length: 1\r\n\r\n",
  2109. 1, "/xx", "aa", "", "s", nil)
  2110. // non-post with content-type
  2111. testRequestHeaderReadSuccess(t, h, "GET /aaa HTTP/1.1\r\nHost: bbb.com\r\nContent-Type: aaab\r\n\r\n",
  2112. -2, "/aaa", "bbb.com", "", "aaab", nil)
  2113. // non-post with content-length
  2114. testRequestHeaderReadSuccess(t, h, "HEAD / HTTP/1.1\r\nHost: aaa.com\r\nContent-Length: 123\r\n\r\n",
  2115. 123, "/", "aaa.com", "", "", nil)
  2116. // non-post with content-type and content-length
  2117. testRequestHeaderReadSuccess(t, h, "GET /aa HTTP/1.1\r\nHost: aa.com\r\nContent-Type: abd/test\r\nContent-Length: 123\r\n\r\n",
  2118. 123, "/aa", "aa.com", "", "abd/test", nil)
  2119. // request uri with hostname
  2120. testRequestHeaderReadSuccess(t, h, "GET http://gooGle.com/foO/%20bar?xxx#aaa HTTP/1.1\r\nHost: aa.cOM\r\n\r\ntrail",
  2121. -2, "http://gooGle.com/foO/%20bar?xxx#aaa", "aa.cOM", "", "", nil)
  2122. // no protocol in the first line
  2123. testRequestHeaderReadSuccess(t, h, "GET /foo/bar\r\nHost: google.com\r\n\r\nisdD",
  2124. -2, "/foo/bar", "google.com", "", "", nil)
  2125. // blank lines before the first line
  2126. testRequestHeaderReadSuccess(t, h, "\r\n\n\r\nGET /aaa HTTP/1.1\r\nHost: aaa.com\r\n\r\nsss",
  2127. -2, "/aaa", "aaa.com", "", "", nil)
  2128. // request uri with spaces
  2129. testRequestHeaderReadSuccess(t, h, "GET /foo/ bar baz HTTP/1.1\r\nHost: aa.com\r\n\r\nxxx",
  2130. -2, "/foo/ bar baz", "aa.com", "", "", nil)
  2131. // no host
  2132. testRequestHeaderReadSuccess(t, h, "GET /foo/bar HTTP/1.1\r\nFOObar: assdfd\r\n\r\naaa",
  2133. -2, "/foo/bar", "", "", "", nil)
  2134. // no host, no headers
  2135. testRequestHeaderReadSuccess(t, h, "GET /foo/bar HTTP/1.1\r\n\r\nfoobar",
  2136. -2, "/foo/bar", "", "", "", nil)
  2137. // post without content-length and content-type
  2138. testRequestHeaderReadSuccess(t, h, "POST /aaa HTTP/1.1\r\nHost: aaa.com\r\n\r\nzxc",
  2139. -2, "/aaa", "aaa.com", "", "", nil)
  2140. // post without content-type
  2141. testRequestHeaderReadSuccess(t, h, "POST /abc HTTP/1.1\r\nHost: aa.com\r\nContent-Length: 123\r\n\r\npoiuy",
  2142. 123, "/abc", "aa.com", "", "", nil)
  2143. // post without content-length
  2144. testRequestHeaderReadSuccess(t, h, "POST /abc HTTP/1.1\r\nHost: aa.com\r\nContent-Type: adv\r\n\r\n123456",
  2145. -2, "/abc", "aa.com", "", "adv", nil)
  2146. // invalid method
  2147. testRequestHeaderReadSuccess(t, h, "POST /foo/bar HTTP/1.1\r\nHost: google.com\r\n\r\nmnbv",
  2148. -2, "/foo/bar", "google.com", "", "", nil)
  2149. // put request
  2150. testRequestHeaderReadSuccess(t, h, "PUT /faa HTTP/1.1\r\nHost: aaa.com\r\nContent-Length: 123\r\nContent-Type: aaa\r\n\r\nxwwere",
  2151. 123, "/faa", "aaa.com", "", "aaa", nil)
  2152. }
  2153. func TestResponseHeaderReadError(t *testing.T) {
  2154. t.Parallel()
  2155. h := &ResponseHeader{}
  2156. // incorrect first line
  2157. testResponseHeaderReadError(t, h, "")
  2158. testResponseHeaderReadError(t, h, "fo")
  2159. testResponseHeaderReadError(t, h, "foobarbaz")
  2160. testResponseHeaderReadError(t, h, "HTTP/1.1")
  2161. testResponseHeaderReadError(t, h, "HTTP/1.1 ")
  2162. testResponseHeaderReadError(t, h, "HTTP/1.1 s")
  2163. // non-numeric status code
  2164. testResponseHeaderReadError(t, h, "HTTP/1.1 foobar OK\r\nContent-Length: 123\r\nContent-Type: text/html\r\n\r\n")
  2165. testResponseHeaderReadError(t, h, "HTTP/1.1 123foobar OK\r\nContent-Length: 123\r\nContent-Type: text/html\r\n\r\n")
  2166. testResponseHeaderReadError(t, h, "HTTP/1.1 foobar344 OK\r\nContent-Length: 123\r\nContent-Type: text/html\r\n\r\n")
  2167. // non-numeric content-length
  2168. testResponseHeaderReadError(t, h, "HTTP/1.1 200 OK\r\nContent-Length: faaa\r\nContent-Type: text/html\r\n\r\nfoobar")
  2169. testResponseHeaderReadError(t, h, "HTTP/1.1 201 OK\r\nContent-Length: 123aa\r\nContent-Type: text/ht\r\n\r\naaa")
  2170. testResponseHeaderReadError(t, h, "HTTP/1.1 200 OK\r\nContent-Length: aa124\r\nContent-Type: html\r\n\r\nxx")
  2171. // no headers
  2172. testResponseHeaderReadError(t, h, "HTTP/1.1 200 OK\r\n")
  2173. // no trailing crlf
  2174. testResponseHeaderReadError(t, h, "HTTP/1.1 200 OK\r\nContent-Length: 123\r\nContent-Type: text/html\r\n")
  2175. // forbidden trailer
  2176. testResponseHeaderReadError(t, h, "HTTP/1.1 200 OK\r\nContent-Length: -1\r\nTrailer: Foo, Content-Length\r\n\r\n")
  2177. }
  2178. func TestResponseHeaderReadErrorSecureLog(t *testing.T) {
  2179. t.Parallel()
  2180. h := &ResponseHeader{
  2181. secureErrorLogMessage: true,
  2182. }
  2183. // incorrect first line
  2184. testResponseHeaderReadSecuredError(t, h, "fo")
  2185. testResponseHeaderReadSecuredError(t, h, "foobarbaz")
  2186. testResponseHeaderReadSecuredError(t, h, "HTTP/1.1")
  2187. testResponseHeaderReadSecuredError(t, h, "HTTP/1.1 ")
  2188. testResponseHeaderReadSecuredError(t, h, "HTTP/1.1 s")
  2189. // non-numeric status code
  2190. testResponseHeaderReadSecuredError(t, h, "HTTP/1.1 foobar OK\r\nContent-Length: 123\r\nContent-Type: text/html\r\n\r\n")
  2191. testResponseHeaderReadSecuredError(t, h, "HTTP/1.1 123foobar OK\r\nContent-Length: 123\r\nContent-Type: text/html\r\n\r\n")
  2192. testResponseHeaderReadSecuredError(t, h, "HTTP/1.1 foobar344 OK\r\nContent-Length: 123\r\nContent-Type: text/html\r\n\r\n")
  2193. // no headers
  2194. testResponseHeaderReadSecuredError(t, h, "HTTP/1.1 200 OK\r\n")
  2195. // no trailing crlf
  2196. testResponseHeaderReadSecuredError(t, h, "HTTP/1.1 200 OK\r\nContent-Length: 123\r\nContent-Type: text/html\r\n")
  2197. }
  2198. func TestRequestHeaderReadError(t *testing.T) {
  2199. t.Parallel()
  2200. h := &RequestHeader{}
  2201. // incorrect first line
  2202. testRequestHeaderReadError(t, h, "")
  2203. testRequestHeaderReadError(t, h, "fo")
  2204. testRequestHeaderReadError(t, h, "GET ")
  2205. testRequestHeaderReadError(t, h, "GET / HTTP/1.1\r")
  2206. // missing RequestURI
  2207. testRequestHeaderReadError(t, h, "GET HTTP/1.1\r\nHost: google.com\r\n\r\n")
  2208. // post with invalid content-length
  2209. testRequestHeaderReadError(t, h, "POST /a HTTP/1.1\r\nHost: bb\r\nContent-Type: aa\r\nContent-Length: dff\r\n\r\nqwerty")
  2210. // forbidden trailer
  2211. testRequestHeaderReadError(t, h, "POST /a HTTP/1.1\r\nContent-Length: -1\r\nTrailer: Foo, Content-Length\r\n\r\n")
  2212. }
  2213. func TestRequestHeaderReadSecuredError(t *testing.T) {
  2214. t.Parallel()
  2215. h := &RequestHeader{
  2216. secureErrorLogMessage: true,
  2217. }
  2218. // incorrect first line
  2219. testRequestHeaderReadSecuredError(t, h, "fo")
  2220. testRequestHeaderReadSecuredError(t, h, "GET ")
  2221. testRequestHeaderReadSecuredError(t, h, "GET / HTTP/1.1\r")
  2222. // missing RequestURI
  2223. testRequestHeaderReadSecuredError(t, h, "GET HTTP/1.1\r\nHost: google.com\r\n\r\n")
  2224. // post with invalid content-length
  2225. testRequestHeaderReadSecuredError(t, h, "POST /a HTTP/1.1\r\nHost: bb\r\nContent-Type: aa\r\nContent-Length: dff\r\n\r\nqwerty")
  2226. }
  2227. func testResponseHeaderReadError(t *testing.T, h *ResponseHeader, headers string) {
  2228. r := bytes.NewBufferString(headers)
  2229. br := bufio.NewReader(r)
  2230. err := h.Read(br)
  2231. if err == nil {
  2232. t.Fatalf("Expecting error when reading response header %q", headers)
  2233. }
  2234. // make sure response header works after error
  2235. testResponseHeaderReadSuccess(t, h, "HTTP/1.1 200 OK\r\nContent-Type: foo/bar\r\nContent-Length: 12345\r\n\r\nsss",
  2236. 200, 12345, "foo/bar")
  2237. }
  2238. func testResponseHeaderReadSecuredError(t *testing.T, h *ResponseHeader, headers string) {
  2239. r := bytes.NewBufferString(headers)
  2240. br := bufio.NewReader(r)
  2241. err := h.Read(br)
  2242. if err == nil {
  2243. t.Fatalf("Expecting error when reading response header %q", headers)
  2244. }
  2245. if strings.Contains(err.Error(), headers) {
  2246. t.Fatalf("Not expecting header content in err %q", err)
  2247. }
  2248. // make sure response header works after error
  2249. testResponseHeaderReadSuccess(t, h, "HTTP/1.1 200 OK\r\nContent-Type: foo/bar\r\nContent-Length: 12345\r\n\r\nsss",
  2250. 200, 12345, "foo/bar")
  2251. }
  2252. func testRequestHeaderReadError(t *testing.T, h *RequestHeader, headers string) {
  2253. r := bytes.NewBufferString(headers)
  2254. br := bufio.NewReader(r)
  2255. err := h.Read(br)
  2256. if err == nil {
  2257. t.Fatalf("Expecting error when reading request header %q", headers)
  2258. }
  2259. // make sure request header works after error
  2260. testRequestHeaderReadSuccess(t, h, "GET /foo/bar HTTP/1.1\r\nHost: aaaa\r\n\r\nxxx",
  2261. -2, "/foo/bar", "aaaa", "", "", nil)
  2262. }
  2263. func testRequestHeaderReadSecuredError(t *testing.T, h *RequestHeader, headers string) {
  2264. r := bytes.NewBufferString(headers)
  2265. br := bufio.NewReader(r)
  2266. err := h.Read(br)
  2267. if err == nil {
  2268. t.Fatalf("Expecting error when reading request header %q", headers)
  2269. }
  2270. if strings.Contains(err.Error(), headers) {
  2271. t.Fatalf("Not expecting header content in err %q", err)
  2272. }
  2273. // make sure request header works after error
  2274. testRequestHeaderReadSuccess(t, h, "GET /foo/bar HTTP/1.1\r\nHost: aaaa\r\n\r\nxxx",
  2275. -2, "/foo/bar", "aaaa", "", "", nil)
  2276. }
  2277. func testResponseHeaderReadSuccess(t *testing.T, h *ResponseHeader, headers string, expectedStatusCode, expectedContentLength int,
  2278. expectedContentType string) {
  2279. r := bytes.NewBufferString(headers)
  2280. br := bufio.NewReader(r)
  2281. err := h.Read(br)
  2282. if err != nil {
  2283. t.Fatalf("Unexpected error when parsing response headers: %s. headers=%q", err, headers)
  2284. }
  2285. verifyResponseHeader(t, h, expectedStatusCode, expectedContentLength, expectedContentType)
  2286. }
  2287. func testRequestHeaderReadSuccess(t *testing.T, h *RequestHeader, headers string, expectedContentLength int,
  2288. expectedRequestURI, expectedHost, expectedReferer, expectedContentType string, expectedTrailer map[string]string) {
  2289. r := bytes.NewBufferString(headers)
  2290. br := bufio.NewReader(r)
  2291. err := h.Read(br)
  2292. if err != nil {
  2293. t.Fatalf("Unexpected error when parsing request headers: %s. headers=%q", err, headers)
  2294. }
  2295. verifyRequestHeader(t, h, expectedContentLength, expectedRequestURI, expectedHost, expectedReferer, expectedContentType)
  2296. }
  2297. func verifyResponseHeader(t *testing.T, h *ResponseHeader, expectedStatusCode, expectedContentLength int, expectedContentType string) {
  2298. if h.StatusCode() != expectedStatusCode {
  2299. t.Fatalf("Unexpected status code %d. Expected %d", h.StatusCode(), expectedStatusCode)
  2300. }
  2301. if h.ContentLength() != expectedContentLength {
  2302. t.Fatalf("Unexpected content length %d. Expected %d", h.ContentLength(), expectedContentLength)
  2303. }
  2304. if string(h.Peek(HeaderContentType)) != expectedContentType {
  2305. t.Fatalf("Unexpected content type %q. Expected %q", h.Peek(HeaderContentType), expectedContentType)
  2306. }
  2307. }
  2308. func verifyResponseHeaderConnection(t *testing.T, h *ResponseHeader, expectConnection string) {
  2309. if string(h.Peek(HeaderConnection)) != expectConnection {
  2310. t.Fatalf("Unexpected Connection %q. Expected %q", h.Peek(HeaderConnection), expectConnection)
  2311. }
  2312. }
  2313. func verifyRequestHeader(t *testing.T, h *RequestHeader, expectedContentLength int,
  2314. expectedRequestURI, expectedHost, expectedReferer, expectedContentType string) {
  2315. if h.ContentLength() != expectedContentLength {
  2316. t.Fatalf("Unexpected Content-Length %d. Expected %d", h.ContentLength(), expectedContentLength)
  2317. }
  2318. if string(h.RequestURI()) != expectedRequestURI {
  2319. t.Fatalf("Unexpected RequestURI %q. Expected %q", h.RequestURI(), expectedRequestURI)
  2320. }
  2321. if string(h.Peek(HeaderHost)) != expectedHost {
  2322. t.Fatalf("Unexpected host %q. Expected %q", h.Peek(HeaderHost), expectedHost)
  2323. }
  2324. if string(h.Peek(HeaderReferer)) != expectedReferer {
  2325. t.Fatalf("Unexpected referer %q. Expected %q", h.Peek(HeaderReferer), expectedReferer)
  2326. }
  2327. if string(h.Peek(HeaderContentType)) != expectedContentType {
  2328. t.Fatalf("Unexpected content-type %q. Expected %q", h.Peek(HeaderContentType), expectedContentType)
  2329. }
  2330. }
  2331. func verifyResponseTrailer(t *testing.T, h *ResponseHeader, expectedTrailers map[string]string) {
  2332. for k, v := range expectedTrailers {
  2333. got := h.Peek(k)
  2334. if !bytes.Equal(got, []byte(v)) {
  2335. t.Fatalf("Unexpected trailer %s. Expected %s. Got %q", k, v, got)
  2336. }
  2337. }
  2338. }
  2339. func verifyRequestTrailer(t *testing.T, h *RequestHeader, expectedTrailers map[string]string) {
  2340. for k, v := range expectedTrailers {
  2341. got := h.Peek(k)
  2342. if !bytes.Equal(got, []byte(v)) {
  2343. t.Fatalf("Unexpected trailer %s. Expected %s. Got %q", k, v, got)
  2344. }
  2345. }
  2346. }
  2347. func verifyTrailer(t *testing.T, r *bufio.Reader, expectedTrailers map[string]string, isReq bool) {
  2348. if isReq {
  2349. req := Request{}
  2350. err := req.Header.ReadTrailer(r)
  2351. if err == io.EOF && expectedTrailers == nil {
  2352. return
  2353. }
  2354. if err != nil {
  2355. t.Fatalf("Cannot read trailer: %s", err)
  2356. }
  2357. verifyRequestTrailer(t, &req.Header, expectedTrailers)
  2358. return
  2359. }
  2360. resp := Response{}
  2361. err := resp.Header.ReadTrailer(r)
  2362. if err == io.EOF && expectedTrailers == nil {
  2363. return
  2364. }
  2365. if err != nil {
  2366. t.Fatalf("Cannot read trailer: %s", err)
  2367. }
  2368. verifyResponseTrailer(t, &resp.Header, expectedTrailers)
  2369. }