server_test.go 96 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950
  1. // go:build !windows || !race
  2. package fasthttp
  3. import (
  4. "bufio"
  5. "bytes"
  6. "context"
  7. "crypto/tls"
  8. "fmt"
  9. "io"
  10. "io/ioutil"
  11. "mime/multipart"
  12. "net"
  13. "os"
  14. "reflect"
  15. "regexp"
  16. "strings"
  17. "sync"
  18. "testing"
  19. "time"
  20. "github.com/valyala/fasthttp/fasthttputil"
  21. )
  22. // Make sure RequestCtx implements context.Context
  23. var _ context.Context = &RequestCtx{}
  24. type closerWithRequestCtx struct {
  25. ctx *RequestCtx
  26. closeFunc func(ctx *RequestCtx) error
  27. }
  28. func (c *closerWithRequestCtx) Close() error {
  29. return c.closeFunc(c.ctx)
  30. }
  31. func TestServerCRNLAfterPost_Pipeline(t *testing.T) {
  32. t.Parallel()
  33. s := &Server{
  34. Handler: func(ctx *RequestCtx) {
  35. },
  36. Logger: &testLogger{},
  37. }
  38. ln := fasthttputil.NewInmemoryListener()
  39. defer ln.Close()
  40. go func() {
  41. if err := s.Serve(ln); err != nil {
  42. t.Errorf("unexpected error: %s", err)
  43. }
  44. }()
  45. c, err := ln.Dial()
  46. if err != nil {
  47. t.Fatalf("unexpected error: %s", err)
  48. }
  49. defer c.Close()
  50. if _, err = c.Write([]byte("POST / HTTP/1.1\r\nHost: golang.org\r\nContent-Length: 3\r\n\r\nABC" +
  51. "\r\n\r\n" + // <-- this stuff is bogus, but we'll ignore it
  52. "GET / HTTP/1.1\r\nHost: golang.org\r\n\r\n")); err != nil {
  53. t.Fatal(err)
  54. }
  55. br := bufio.NewReader(c)
  56. var resp Response
  57. if err := resp.Read(br); err != nil {
  58. t.Fatalf("unexpected error: %s", err)
  59. }
  60. if resp.StatusCode() != StatusOK {
  61. t.Fatalf("unexpected status code: %d. Expecting %d", resp.StatusCode(), StatusOK)
  62. }
  63. if err := resp.Read(br); err != nil {
  64. t.Fatalf("unexpected error: %s", err)
  65. }
  66. if resp.StatusCode() != StatusOK {
  67. t.Fatalf("unexpected status code: %d. Expecting %d", resp.StatusCode(), StatusOK)
  68. }
  69. }
  70. func TestServerCRNLAfterPost(t *testing.T) {
  71. t.Parallel()
  72. s := &Server{
  73. Handler: func(ctx *RequestCtx) {
  74. },
  75. Logger: &testLogger{},
  76. ReadTimeout: time.Millisecond * 100,
  77. }
  78. ln := fasthttputil.NewInmemoryListener()
  79. defer ln.Close()
  80. go func() {
  81. if err := s.Serve(ln); err != nil {
  82. t.Errorf("unexpected error: %s", err)
  83. }
  84. }()
  85. c, err := ln.Dial()
  86. if err != nil {
  87. t.Fatalf("unexpected error: %s", err)
  88. }
  89. defer c.Close()
  90. if _, err = c.Write([]byte("POST / HTTP/1.1\r\nHost: golang.org\r\nContent-Length: 3\r\n\r\nABC" +
  91. "\r\n\r\n", // <-- this stuff is bogus, but we'll ignore it
  92. )); err != nil {
  93. t.Fatal(err)
  94. }
  95. br := bufio.NewReader(c)
  96. var resp Response
  97. if err := resp.Read(br); err != nil {
  98. t.Fatalf("unexpected error: %s", err)
  99. }
  100. if resp.StatusCode() != StatusOK {
  101. t.Fatalf("unexpected status code: %d. Expecting %d", resp.StatusCode(), StatusOK)
  102. }
  103. if err := resp.Read(br); err == nil {
  104. t.Fatal("expected error") // We didn't send a request so we should get an error here.
  105. }
  106. }
  107. func TestServerPipelineFlush(t *testing.T) {
  108. t.Parallel()
  109. s := &Server{
  110. Handler: func(ctx *RequestCtx) {
  111. },
  112. }
  113. ln := fasthttputil.NewInmemoryListener()
  114. go func() {
  115. if err := s.Serve(ln); err != nil {
  116. t.Errorf("unexpected error: %s", err)
  117. }
  118. }()
  119. c, err := ln.Dial()
  120. if err != nil {
  121. t.Fatalf("unexpected error: %s", err)
  122. }
  123. if _, err = c.Write([]byte("GET /foo1 HTTP/1.1\r\nHost: google.com\r\n\r\n")); err != nil {
  124. t.Fatal(err)
  125. }
  126. // Write a partial request.
  127. if _, err = c.Write([]byte("GET /foo1 HTTP/1.1\r\nHost: ")); err != nil {
  128. t.Fatal(err)
  129. }
  130. go func() {
  131. // Wait for 200ms to finish the request
  132. time.Sleep(time.Millisecond * 200)
  133. if _, err = c.Write([]byte("google.com\r\n\r\n")); err != nil {
  134. t.Error(err)
  135. }
  136. }()
  137. start := time.Now()
  138. br := bufio.NewReader(c)
  139. var resp Response
  140. if err := resp.Read(br); err != nil {
  141. t.Fatalf("unexpected error: %s", err)
  142. }
  143. if resp.StatusCode() != StatusOK {
  144. t.Fatalf("unexpected status code: %d. Expecting %d", resp.StatusCode(), StatusOK)
  145. }
  146. // Since the second request takes 200ms to finish we expect the first one to be flushed earlier.
  147. d := time.Since(start)
  148. if d > time.Millisecond*100 {
  149. t.Fatalf("had to wait for %v", d)
  150. }
  151. if err := resp.Read(br); err != nil {
  152. t.Fatalf("unexpected error: %s", err)
  153. }
  154. if resp.StatusCode() != StatusOK {
  155. t.Fatalf("unexpected status code: %d. Expecting %d", resp.StatusCode(), StatusOK)
  156. }
  157. }
  158. func TestServerInvalidHeader(t *testing.T) {
  159. t.Parallel()
  160. s := &Server{
  161. Handler: func(ctx *RequestCtx) {
  162. if ctx.Request.Header.Peek("Foo") != nil || ctx.Request.Header.Peek("Foo ") != nil {
  163. t.Error("expected Foo header")
  164. }
  165. },
  166. Logger: &testLogger{},
  167. }
  168. ln := fasthttputil.NewInmemoryListener()
  169. go func() {
  170. if err := s.Serve(ln); err != nil {
  171. t.Errorf("unexpected error: %s", err)
  172. }
  173. }()
  174. c, err := ln.Dial()
  175. if err != nil {
  176. t.Fatalf("unexpected error: %s", err)
  177. }
  178. if _, err = c.Write([]byte("POST /foo HTTP/1.1\r\nHost: gle.com\r\nFoo : bar\r\nContent-Length: 5\r\n\r\n12345")); err != nil {
  179. t.Fatal(err)
  180. }
  181. br := bufio.NewReader(c)
  182. var resp Response
  183. if err := resp.Read(br); err != nil {
  184. t.Fatalf("unexpected error: %s", err)
  185. }
  186. if resp.StatusCode() != StatusBadRequest {
  187. t.Fatalf("unexpected status code: %d. Expecting %d", resp.StatusCode(), StatusBadRequest)
  188. }
  189. c, err = ln.Dial()
  190. if err != nil {
  191. t.Fatalf("unexpected error: %s", err)
  192. }
  193. if _, err = c.Write([]byte("GET /foo HTTP/1.1\r\nHost: gle.com\r\nFoo : bar\r\n\r\n")); err != nil {
  194. t.Fatal(err)
  195. }
  196. br = bufio.NewReader(c)
  197. if err := resp.Read(br); err != nil {
  198. t.Fatalf("unexpected error: %s", err)
  199. }
  200. if resp.StatusCode() != StatusBadRequest {
  201. t.Fatalf("unexpected status code: %d. Expecting %d", resp.StatusCode(), StatusBadRequest)
  202. }
  203. if err := c.Close(); err != nil {
  204. t.Fatalf("unexpected error: %s", err)
  205. }
  206. if err := ln.Close(); err != nil {
  207. t.Fatalf("unexpected error: %s", err)
  208. }
  209. }
  210. func TestServerConnState(t *testing.T) {
  211. t.Parallel()
  212. states := make([]string, 0)
  213. s := &Server{
  214. Handler: func(ctx *RequestCtx) {},
  215. ConnState: func(conn net.Conn, state ConnState) {
  216. states = append(states, state.String())
  217. },
  218. }
  219. ln := fasthttputil.NewInmemoryListener()
  220. serverCh := make(chan struct{})
  221. go func() {
  222. if err := s.Serve(ln); err != nil {
  223. t.Errorf("unexpected error: %s", err)
  224. }
  225. close(serverCh)
  226. }()
  227. clientCh := make(chan struct{})
  228. go func() {
  229. c, err := ln.Dial()
  230. if err != nil {
  231. t.Errorf("unexpected error: %s", err)
  232. }
  233. br := bufio.NewReader(c)
  234. // Send 2 requests on the same connection.
  235. for i := 0; i < 2; i++ {
  236. if _, err = c.Write([]byte("GET / HTTP/1.1\r\nHost: aa\r\n\r\n")); err != nil {
  237. t.Errorf("unexpected error: %s", err)
  238. }
  239. var resp Response
  240. if err := resp.Read(br); err != nil {
  241. t.Errorf("unexpected error: %s", err)
  242. }
  243. if resp.StatusCode() != StatusOK {
  244. t.Errorf("unexpected status code: %d. Expecting %d", resp.StatusCode(), StatusOK)
  245. }
  246. }
  247. if err := c.Close(); err != nil {
  248. t.Errorf("unexpected error: %s", err)
  249. }
  250. // Give the server a little bit of time to transition the connection to the close state.
  251. time.Sleep(time.Millisecond * 100)
  252. close(clientCh)
  253. }()
  254. select {
  255. case <-clientCh:
  256. case <-time.After(time.Second):
  257. t.Fatal("timeout")
  258. }
  259. if err := ln.Close(); err != nil {
  260. t.Fatalf("unexpected error: %s", err)
  261. }
  262. select {
  263. case <-serverCh:
  264. case <-time.After(time.Second):
  265. t.Fatal("timeout")
  266. }
  267. // 2 requests so we go to active and idle twice.
  268. expected := []string{"new", "active", "idle", "active", "idle", "closed"}
  269. if !reflect.DeepEqual(expected, states) {
  270. t.Fatalf("wrong state, expected %s, got %s", expected, states)
  271. }
  272. }
  273. func TestSaveMultipartFile(t *testing.T) {
  274. t.Parallel()
  275. filea := "This is a test file."
  276. fileb := strings.Repeat("test", 64)
  277. mr := multipart.NewReader(strings.NewReader(""+
  278. "--foo\r\n"+
  279. "Content-Disposition: form-data; name=\"filea\"; filename=\"filea.txt\"\r\n"+
  280. "Content-Type: text/plain\r\n"+
  281. "\r\n"+
  282. filea+"\r\n"+
  283. "--foo\r\n"+
  284. "Content-Disposition: form-data; name=\"fileb\"; filename=\"fileb.txt\"\r\n"+
  285. "Content-Type: text/plain\r\n"+
  286. "\r\n"+
  287. fileb+"\r\n"+
  288. "--foo--\r\n",
  289. ), "foo")
  290. f, err := mr.ReadForm(64)
  291. if err != nil {
  292. t.Fatal(err)
  293. }
  294. if err := SaveMultipartFile(f.File["filea"][0], "filea.txt"); err != nil {
  295. t.Fatal(err)
  296. }
  297. defer os.Remove("filea.txt")
  298. if c, err := ioutil.ReadFile("filea.txt"); err != nil {
  299. t.Fatal(err)
  300. } else if string(c) != filea {
  301. t.Fatalf("filea changed expected %q got %q", filea, c)
  302. }
  303. // Make sure fileb was saved to a file.
  304. if ff, err := f.File["fileb"][0].Open(); err != nil {
  305. t.Fatal("expected FileHeader.Open to work")
  306. } else if _, ok := ff.(*os.File); !ok {
  307. t.Fatal("expected fileb to be an os.File")
  308. } else {
  309. ff.Close()
  310. }
  311. if err := SaveMultipartFile(f.File["fileb"][0], "fileb.txt"); err != nil {
  312. t.Fatal(err)
  313. }
  314. defer os.Remove("fileb.txt")
  315. if c, err := ioutil.ReadFile("fileb.txt"); err != nil {
  316. t.Fatal(err)
  317. } else if string(c) != fileb {
  318. t.Fatalf("fileb changed expected %q got %q", fileb, c)
  319. }
  320. }
  321. func TestServerName(t *testing.T) {
  322. t.Parallel()
  323. s := &Server{
  324. Handler: func(ctx *RequestCtx) {
  325. },
  326. }
  327. getReponse := func() []byte {
  328. rw := &readWriter{}
  329. rw.r.WriteString("GET / HTTP/1.1\r\nHost: google.com\r\n\r\n")
  330. if err := s.ServeConn(rw); err != nil {
  331. t.Fatalf("Unexpected error from serveConn: %s", err)
  332. }
  333. resp, err := ioutil.ReadAll(&rw.w)
  334. if err != nil {
  335. t.Fatalf("Unexpected error from ReadAll: %s", err)
  336. }
  337. return resp
  338. }
  339. resp := getReponse()
  340. if !bytes.Contains(resp, []byte("\r\nServer: "+string(defaultServerName)+"\r\n")) {
  341. t.Fatalf("Unexpected response %q expected Server: "+string(defaultServerName), resp)
  342. }
  343. // We can't just overwrite s.Name as fasthttp caches the name in an atomic.Value
  344. s = &Server{
  345. Handler: func(ctx *RequestCtx) {
  346. },
  347. Name: "foobar",
  348. }
  349. resp = getReponse()
  350. if !bytes.Contains(resp, []byte("\r\nServer: foobar\r\n")) {
  351. t.Fatalf("Unexpected response %q expected Server: foobar", resp)
  352. }
  353. s = &Server{
  354. Handler: func(ctx *RequestCtx) {
  355. },
  356. NoDefaultServerHeader: true,
  357. NoDefaultContentType: true,
  358. NoDefaultDate: true,
  359. }
  360. resp = getReponse()
  361. if bytes.Contains(resp, []byte("\r\nServer: ")) {
  362. t.Fatalf("Unexpected response %q expected no Server header", resp)
  363. }
  364. if bytes.Contains(resp, []byte("\r\nContent-Type: ")) {
  365. t.Fatalf("Unexpected response %q expected no Content-Type header", resp)
  366. }
  367. if bytes.Contains(resp, []byte("\r\nDate: ")) {
  368. t.Fatalf("Unexpected response %q expected no Date header", resp)
  369. }
  370. }
  371. func TestRequestCtxString(t *testing.T) {
  372. t.Parallel()
  373. var ctx RequestCtx
  374. s := ctx.String()
  375. expectedS := "#0000000000000000 - 0.0.0.0:0<->0.0.0.0:0 - GET http:///"
  376. if s != expectedS {
  377. t.Fatalf("unexpected ctx.String: %q. Expecting %q", s, expectedS)
  378. }
  379. ctx.Request.SetRequestURI("https://foobar.com/aaa?bb=c")
  380. s = ctx.String()
  381. expectedS = "#0000000000000000 - 0.0.0.0:0<->0.0.0.0:0 - GET https://foobar.com/aaa?bb=c"
  382. if s != expectedS {
  383. t.Fatalf("unexpected ctx.String: %q. Expecting %q", s, expectedS)
  384. }
  385. }
  386. func TestServerErrSmallBuffer(t *testing.T) {
  387. t.Parallel()
  388. s := &Server{
  389. Handler: func(ctx *RequestCtx) {
  390. ctx.WriteString("shouldn't be never called") //nolint:errcheck
  391. },
  392. ReadBufferSize: 20,
  393. }
  394. rw := &readWriter{}
  395. rw.r.WriteString("GET / HTTP/1.1\r\nHost: aabb.com\r\nVERY-long-Header: sdfdfsd dsf dsaf dsf df fsd\r\n\r\n")
  396. ch := make(chan error)
  397. go func() {
  398. ch <- s.ServeConn(rw)
  399. }()
  400. var serverErr error
  401. select {
  402. case serverErr = <-ch:
  403. case <-time.After(200 * time.Millisecond):
  404. t.Fatal("timeout")
  405. }
  406. if serverErr == nil {
  407. t.Fatal("expected error")
  408. }
  409. br := bufio.NewReader(&rw.w)
  410. var resp Response
  411. if err := resp.Read(br); err != nil {
  412. t.Fatalf("unexpected error: %s", err)
  413. }
  414. statusCode := resp.StatusCode()
  415. if statusCode != StatusRequestHeaderFieldsTooLarge {
  416. t.Fatalf("unexpected status code: %d. Expecting %d", statusCode, StatusRequestHeaderFieldsTooLarge)
  417. }
  418. if !resp.ConnectionClose() {
  419. t.Fatal("missing 'Connection: close' response header")
  420. }
  421. expectedErr := errSmallBuffer.Error()
  422. if !strings.Contains(serverErr.Error(), expectedErr) {
  423. t.Fatalf("unexpected log output: %v. Expecting %q", serverErr, expectedErr)
  424. }
  425. }
  426. func TestRequestCtxIsTLS(t *testing.T) {
  427. t.Parallel()
  428. var ctx RequestCtx
  429. // tls.Conn
  430. ctx.c = &tls.Conn{}
  431. if !ctx.IsTLS() {
  432. t.Fatal("IsTLS must return true")
  433. }
  434. // non-tls.Conn
  435. ctx.c = &readWriter{}
  436. if ctx.IsTLS() {
  437. t.Fatal("IsTLS must return false")
  438. }
  439. // overridden tls.Conn
  440. ctx.c = &struct {
  441. *tls.Conn
  442. fooBar bool
  443. }{}
  444. if !ctx.IsTLS() {
  445. t.Fatal("IsTLS must return true")
  446. }
  447. ctx.c = &perIPConn{Conn: &tls.Conn{}}
  448. if !ctx.IsTLS() {
  449. t.Fatal("IsTLS must return true")
  450. }
  451. }
  452. func TestRequestCtxRedirectHTTPSSchemeless(t *testing.T) {
  453. t.Parallel()
  454. var ctx RequestCtx
  455. s := "GET /foo/bar?baz HTTP/1.1\nHost: aaa.com\n\n"
  456. br := bufio.NewReader(bytes.NewBufferString(s))
  457. if err := ctx.Request.Read(br); err != nil {
  458. t.Fatalf("cannot read request: %s", err)
  459. }
  460. ctx.Request.isTLS = true
  461. ctx.Redirect("//foobar.com/aa/bbb", StatusFound)
  462. location := ctx.Response.Header.Peek(HeaderLocation)
  463. expectedLocation := "https://foobar.com/aa/bbb"
  464. if string(location) != expectedLocation {
  465. t.Fatalf("Unexpected location: %q. Expecting %q", location, expectedLocation)
  466. }
  467. }
  468. func TestRequestCtxRedirect(t *testing.T) {
  469. t.Parallel()
  470. testRequestCtxRedirect(t, "http://qqq/", "", "http://qqq/")
  471. testRequestCtxRedirect(t, "http://qqq/foo/bar?baz=111", "", "http://qqq/foo/bar?baz=111")
  472. testRequestCtxRedirect(t, "http://qqq/foo/bar?baz=111", "#aaa", "http://qqq/foo/bar?baz=111#aaa")
  473. testRequestCtxRedirect(t, "http://qqq/foo/bar?baz=111", "?abc=de&f", "http://qqq/foo/bar?abc=de&f")
  474. testRequestCtxRedirect(t, "http://qqq/foo/bar?baz=111", "?abc=de&f#sf", "http://qqq/foo/bar?abc=de&f#sf")
  475. testRequestCtxRedirect(t, "http://qqq/foo/bar?baz=111", "x.html", "http://qqq/foo/x.html")
  476. testRequestCtxRedirect(t, "http://qqq/foo/bar?baz=111", "x.html?a=1", "http://qqq/foo/x.html?a=1")
  477. testRequestCtxRedirect(t, "http://qqq/foo/bar?baz=111", "x.html#aaa=bbb&cc=ddd", "http://qqq/foo/x.html#aaa=bbb&cc=ddd")
  478. testRequestCtxRedirect(t, "http://qqq/foo/bar?baz=111", "x.html?b=1#aaa=bbb&cc=ddd", "http://qqq/foo/x.html?b=1#aaa=bbb&cc=ddd")
  479. testRequestCtxRedirect(t, "http://qqq/foo/bar?baz=111", "/x.html", "http://qqq/x.html")
  480. testRequestCtxRedirect(t, "http://qqq/foo/bar?baz=111", "/x.html#aaa=bbb&cc=ddd", "http://qqq/x.html#aaa=bbb&cc=ddd")
  481. testRequestCtxRedirect(t, "http://qqq/foo/bar?baz=111", "../x.html", "http://qqq/x.html")
  482. testRequestCtxRedirect(t, "http://qqq/foo/bar?baz=111", "../../x.html", "http://qqq/x.html")
  483. testRequestCtxRedirect(t, "http://qqq/foo/bar?baz=111", "./.././../x.html", "http://qqq/x.html")
  484. testRequestCtxRedirect(t, "http://qqq/foo/bar?baz=111", "http://foo.bar/baz", "http://foo.bar/baz")
  485. testRequestCtxRedirect(t, "http://qqq/foo/bar?baz=111", "https://foo.bar/baz", "https://foo.bar/baz")
  486. testRequestCtxRedirect(t, "https://foo.com/bar?aaa", "//google.com/aaa?bb", "https://google.com/aaa?bb")
  487. }
  488. func testRequestCtxRedirect(t *testing.T, origURL, redirectURL, expectedURL string) {
  489. var ctx RequestCtx
  490. var req Request
  491. req.SetRequestURI(origURL)
  492. ctx.Init(&req, nil, nil)
  493. ctx.Redirect(redirectURL, StatusFound)
  494. loc := ctx.Response.Header.Peek(HeaderLocation)
  495. if string(loc) != expectedURL {
  496. t.Fatalf("unexpected redirect url %q. Expecting %q. origURL=%q, redirectURL=%q", loc, expectedURL, origURL, redirectURL)
  497. }
  498. }
  499. func TestServerResponseServerHeader(t *testing.T) {
  500. t.Parallel()
  501. serverName := "foobar serv"
  502. s := &Server{
  503. Handler: func(ctx *RequestCtx) {
  504. name := ctx.Response.Header.Server()
  505. if string(name) != serverName {
  506. fmt.Fprintf(ctx, "unexpected server name: %q. Expecting %q", name, serverName)
  507. } else {
  508. ctx.WriteString("OK") //nolint:errcheck
  509. }
  510. // make sure the server name is sent to the client after ctx.Response.Reset()
  511. ctx.NotFound()
  512. },
  513. Name: serverName,
  514. }
  515. ln := fasthttputil.NewInmemoryListener()
  516. serverCh := make(chan struct{})
  517. go func() {
  518. if err := s.Serve(ln); err != nil {
  519. t.Errorf("unexpected error: %s", err)
  520. }
  521. close(serverCh)
  522. }()
  523. clientCh := make(chan struct{})
  524. go func() {
  525. c, err := ln.Dial()
  526. if err != nil {
  527. t.Errorf("unexpected error: %s", err)
  528. }
  529. if _, err = c.Write([]byte("GET / HTTP/1.1\r\nHost: aa\r\n\r\n")); err != nil {
  530. t.Errorf("unexpected error: %s", err)
  531. }
  532. br := bufio.NewReader(c)
  533. var resp Response
  534. if err = resp.Read(br); err != nil {
  535. t.Errorf("unexpected error: %s", err)
  536. }
  537. if resp.StatusCode() != StatusNotFound {
  538. t.Errorf("unexpected status code: %d. Expecting %d", resp.StatusCode(), StatusNotFound)
  539. }
  540. if string(resp.Body()) != "404 Page not found" {
  541. t.Errorf("unexpected body: %q. Expecting %q", resp.Body(), "404 Page not found")
  542. }
  543. if string(resp.Header.Server()) != serverName {
  544. t.Errorf("unexpected server header: %q. Expecting %q", resp.Header.Server(), serverName)
  545. }
  546. if err = c.Close(); err != nil {
  547. t.Errorf("unexpected error: %s", err)
  548. }
  549. close(clientCh)
  550. }()
  551. select {
  552. case <-clientCh:
  553. case <-time.After(time.Second):
  554. t.Fatal("timeout")
  555. }
  556. if err := ln.Close(); err != nil {
  557. t.Fatalf("unexpected error: %s", err)
  558. }
  559. select {
  560. case <-serverCh:
  561. case <-time.After(time.Second):
  562. t.Fatal("timeout")
  563. }
  564. }
  565. func TestServerResponseBodyStream(t *testing.T) {
  566. t.Parallel()
  567. ln := fasthttputil.NewInmemoryListener()
  568. readyCh := make(chan struct{})
  569. h := func(ctx *RequestCtx) {
  570. ctx.SetConnectionClose()
  571. if ctx.IsBodyStream() {
  572. t.Fatal("IsBodyStream must return false")
  573. }
  574. ctx.SetBodyStreamWriter(func(w *bufio.Writer) {
  575. fmt.Fprintf(w, "first")
  576. if err := w.Flush(); err != nil {
  577. return
  578. }
  579. <-readyCh
  580. fmt.Fprintf(w, "second")
  581. // there is no need to flush w here, since it will
  582. // be flushed automatically after returning from StreamWriter.
  583. })
  584. if !ctx.IsBodyStream() {
  585. t.Fatal("IsBodyStream must return true")
  586. }
  587. }
  588. serverCh := make(chan struct{})
  589. go func() {
  590. if err := Serve(ln, h); err != nil {
  591. t.Errorf("unexpected error: %s", err)
  592. }
  593. close(serverCh)
  594. }()
  595. clientCh := make(chan struct{})
  596. go func() {
  597. c, err := ln.Dial()
  598. if err != nil {
  599. t.Errorf("unexpected error: %s", err)
  600. }
  601. if _, err = c.Write([]byte("GET / HTTP/1.1\r\nHost: aa\r\n\r\n")); err != nil {
  602. t.Errorf("unexpected error: %s", err)
  603. }
  604. br := bufio.NewReader(c)
  605. var respH ResponseHeader
  606. if err = respH.Read(br); err != nil {
  607. t.Errorf("unexpected error: %s", err)
  608. }
  609. if respH.StatusCode() != StatusOK {
  610. t.Errorf("unexpected status code: %d. Expecting %d", respH.StatusCode(), StatusOK)
  611. }
  612. buf := make([]byte, 1024)
  613. n, err := br.Read(buf)
  614. if err != nil {
  615. t.Errorf("unexpected error: %s", err)
  616. }
  617. b := buf[:n]
  618. if string(b) != "5\r\nfirst\r\n" {
  619. t.Errorf("unexpected result %q. Expecting %q", b, "5\r\nfirst\r\n")
  620. }
  621. close(readyCh)
  622. tail, err := ioutil.ReadAll(br)
  623. if err != nil {
  624. t.Errorf("unexpected error: %s", err)
  625. }
  626. if string(tail) != "6\r\nsecond\r\n0\r\n\r\n" {
  627. t.Errorf("unexpected tail %q. Expecting %q", tail, "6\r\nsecond\r\n0\r\n\r\n")
  628. }
  629. close(clientCh)
  630. }()
  631. select {
  632. case <-clientCh:
  633. case <-time.After(time.Second):
  634. t.Fatal("timeout")
  635. }
  636. if err := ln.Close(); err != nil {
  637. t.Fatalf("unexpected error: %s", err)
  638. }
  639. select {
  640. case <-serverCh:
  641. case <-time.After(time.Second):
  642. t.Fatal("timeout")
  643. }
  644. }
  645. func TestServerDisableKeepalive(t *testing.T) {
  646. t.Parallel()
  647. s := &Server{
  648. Handler: func(ctx *RequestCtx) {
  649. ctx.WriteString("OK") //nolint:errcheck
  650. },
  651. DisableKeepalive: true,
  652. }
  653. ln := fasthttputil.NewInmemoryListener()
  654. serverCh := make(chan struct{})
  655. go func() {
  656. if err := s.Serve(ln); err != nil {
  657. t.Errorf("unexpected error: %s", err)
  658. }
  659. close(serverCh)
  660. }()
  661. clientCh := make(chan struct{})
  662. go func() {
  663. c, err := ln.Dial()
  664. if err != nil {
  665. t.Errorf("unexpected error: %s", err)
  666. }
  667. if _, err = c.Write([]byte("GET / HTTP/1.1\r\nHost: aa\r\n\r\n")); err != nil {
  668. t.Errorf("unexpected error: %s", err)
  669. }
  670. br := bufio.NewReader(c)
  671. var resp Response
  672. if err = resp.Read(br); err != nil {
  673. t.Errorf("unexpected error: %s", err)
  674. }
  675. if resp.StatusCode() != StatusOK {
  676. t.Errorf("unexpected status code: %d. Expecting %d", resp.StatusCode(), StatusOK)
  677. }
  678. if !resp.ConnectionClose() {
  679. t.Error("expecting 'Connection: close' response header")
  680. }
  681. if string(resp.Body()) != "OK" {
  682. t.Errorf("unexpected body: %q. Expecting %q", resp.Body(), "OK")
  683. }
  684. // make sure the connection is closed
  685. data, err := ioutil.ReadAll(br)
  686. if err != nil {
  687. t.Errorf("unexpected error: %s", err)
  688. }
  689. if len(data) > 0 {
  690. t.Errorf("unexpected data read from the connection: %q. Expecting empty data", data)
  691. }
  692. close(clientCh)
  693. }()
  694. select {
  695. case <-clientCh:
  696. case <-time.After(time.Second):
  697. t.Fatal("timeout")
  698. }
  699. if err := ln.Close(); err != nil {
  700. t.Fatalf("unexpected error: %s", err)
  701. }
  702. select {
  703. case <-serverCh:
  704. case <-time.After(time.Second):
  705. t.Fatal("timeout")
  706. }
  707. }
  708. func TestServerMaxConnsPerIPLimit(t *testing.T) {
  709. t.Parallel()
  710. s := &Server{
  711. Handler: func(ctx *RequestCtx) {
  712. ctx.WriteString("OK") //nolint:errcheck
  713. },
  714. MaxConnsPerIP: 1,
  715. Logger: &testLogger{},
  716. }
  717. ln := fasthttputil.NewInmemoryListener()
  718. serverCh := make(chan struct{})
  719. go func() {
  720. fakeLN := &fakeIPListener{
  721. Listener: ln,
  722. }
  723. if err := s.Serve(fakeLN); err != nil {
  724. t.Errorf("unexpected error: %s", err)
  725. }
  726. close(serverCh)
  727. }()
  728. clientCh := make(chan struct{})
  729. go func() {
  730. c1, err := ln.Dial()
  731. if err != nil {
  732. t.Errorf("unexpected error: %s", err)
  733. }
  734. c2, err := ln.Dial()
  735. if err != nil {
  736. t.Errorf("unexpected error: %s", err)
  737. }
  738. br := bufio.NewReader(c2)
  739. var resp Response
  740. if err = resp.Read(br); err != nil {
  741. t.Errorf("unexpected error: %s", err)
  742. }
  743. if resp.StatusCode() != StatusTooManyRequests {
  744. t.Errorf("unexpected status code for the second connection: %d. Expecting %d",
  745. resp.StatusCode(), StatusTooManyRequests)
  746. }
  747. if _, err = c1.Write([]byte("GET / HTTP/1.1\r\nHost: aa\r\n\r\n")); err != nil {
  748. t.Errorf("unexpected error when writing to the first connection: %s", err)
  749. }
  750. br = bufio.NewReader(c1)
  751. if err = resp.Read(br); err != nil {
  752. t.Errorf("unexpected error: %s", err)
  753. }
  754. if resp.StatusCode() != StatusOK {
  755. t.Errorf("unexpected status code for the first connection: %d. Expecting %d",
  756. resp.StatusCode(), StatusOK)
  757. }
  758. if string(resp.Body()) != "OK" {
  759. t.Errorf("unexpected body for the first connection: %q. Expecting %q", resp.Body(), "OK")
  760. }
  761. close(clientCh)
  762. }()
  763. select {
  764. case <-clientCh:
  765. case <-time.After(time.Second):
  766. t.Fatal("timeout")
  767. }
  768. if err := ln.Close(); err != nil {
  769. t.Fatalf("unexpected error: %s", err)
  770. }
  771. select {
  772. case <-serverCh:
  773. case <-time.After(time.Second):
  774. t.Fatal("timeout")
  775. }
  776. }
  777. type fakeIPListener struct {
  778. net.Listener
  779. }
  780. func (ln *fakeIPListener) Accept() (net.Conn, error) {
  781. conn, err := ln.Listener.Accept()
  782. if err != nil {
  783. return nil, err
  784. }
  785. return &fakeIPConn{
  786. Conn: conn,
  787. }, nil
  788. }
  789. type fakeIPConn struct {
  790. net.Conn
  791. }
  792. func (conn *fakeIPConn) RemoteAddr() net.Addr {
  793. addr, err := net.ResolveTCPAddr("tcp4", "1.2.3.4:5789")
  794. if err != nil {
  795. panic(fmt.Sprintf("BUG: unexpected error: %s", err))
  796. }
  797. return addr
  798. }
  799. func TestServerConcurrencyLimit(t *testing.T) {
  800. t.Parallel()
  801. s := &Server{
  802. Handler: func(ctx *RequestCtx) {
  803. ctx.WriteString("OK") //nolint:errcheck
  804. },
  805. Concurrency: 1,
  806. Logger: &testLogger{},
  807. }
  808. ln := fasthttputil.NewInmemoryListener()
  809. serverCh := make(chan struct{})
  810. go func() {
  811. if err := s.Serve(ln); err != nil {
  812. t.Errorf("unexpected error: %s", err)
  813. }
  814. close(serverCh)
  815. }()
  816. clientCh := make(chan struct{})
  817. go func() {
  818. c1, err := ln.Dial()
  819. if err != nil {
  820. t.Errorf("unexpected error: %s", err)
  821. }
  822. c2, err := ln.Dial()
  823. if err != nil {
  824. t.Errorf("unexpected error: %s", err)
  825. }
  826. br := bufio.NewReader(c2)
  827. var resp Response
  828. if err = resp.Read(br); err != nil {
  829. t.Errorf("unexpected error: %s", err)
  830. }
  831. if resp.StatusCode() != StatusServiceUnavailable {
  832. t.Errorf("unexpected status code for the second connection: %d. Expecting %d",
  833. resp.StatusCode(), StatusServiceUnavailable)
  834. }
  835. if _, err = c1.Write([]byte("GET / HTTP/1.1\r\nHost: aa\r\n\r\n")); err != nil {
  836. t.Errorf("unexpected error when writing to the first connection: %s", err)
  837. }
  838. br = bufio.NewReader(c1)
  839. if err = resp.Read(br); err != nil {
  840. t.Errorf("unexpected error: %s", err)
  841. }
  842. if resp.StatusCode() != StatusOK {
  843. t.Errorf("unexpected status code for the first connection: %d. Expecting %d",
  844. resp.StatusCode(), StatusOK)
  845. }
  846. if string(resp.Body()) != "OK" {
  847. t.Errorf("unexpected body for the first connection: %q. Expecting %q", resp.Body(), "OK")
  848. }
  849. close(clientCh)
  850. }()
  851. select {
  852. case <-clientCh:
  853. case <-time.After(time.Second):
  854. t.Fatal("timeout")
  855. }
  856. if err := ln.Close(); err != nil {
  857. t.Fatalf("unexpected error: %s", err)
  858. }
  859. select {
  860. case <-serverCh:
  861. case <-time.After(time.Second):
  862. t.Fatal("timeout")
  863. }
  864. }
  865. func TestServerWriteFastError(t *testing.T) {
  866. t.Parallel()
  867. s := &Server{
  868. Name: "foobar",
  869. }
  870. var buf bytes.Buffer
  871. expectedBody := "access denied"
  872. s.writeFastError(&buf, StatusForbidden, expectedBody)
  873. br := bufio.NewReader(&buf)
  874. var resp Response
  875. if err := resp.Read(br); err != nil {
  876. t.Fatalf("unexpected error: %s", err)
  877. }
  878. if resp.StatusCode() != StatusForbidden {
  879. t.Fatalf("unexpected status code: %d. Expecting %d", resp.StatusCode(), StatusForbidden)
  880. }
  881. body := resp.Body()
  882. if string(body) != expectedBody {
  883. t.Fatalf("unexpected body: %q. Expecting %q", body, expectedBody)
  884. }
  885. server := string(resp.Header.Server())
  886. if server != s.Name {
  887. t.Fatalf("unexpected server: %q. Expecting %q", server, s.Name)
  888. }
  889. contentType := string(resp.Header.ContentType())
  890. if contentType != "text/plain" {
  891. t.Fatalf("unexpected content-type: %q. Expecting %q", contentType, "text/plain")
  892. }
  893. if !resp.Header.ConnectionClose() {
  894. t.Fatal("expecting 'Connection: close' response header")
  895. }
  896. }
  897. func TestServerTLS(t *testing.T) {
  898. t.Parallel()
  899. text := []byte("Make fasthttp great again")
  900. ln := fasthttputil.NewInmemoryListener()
  901. s := &Server{
  902. Handler: func(ctx *RequestCtx) {
  903. ctx.Write(text) //nolint:errcheck
  904. },
  905. }
  906. certData, keyData, err := GenerateTestCertificate("localhost")
  907. if err != nil {
  908. t.Fatal(err)
  909. }
  910. err = s.AppendCertEmbed(certData, keyData)
  911. if err != nil {
  912. t.Fatal(err)
  913. }
  914. go func() {
  915. err = s.ServeTLS(ln, "", "")
  916. if err != nil {
  917. t.Error(err)
  918. }
  919. }()
  920. c := &Client{
  921. ReadTimeout: time.Second * 2,
  922. Dial: func(addr string) (net.Conn, error) {
  923. return ln.Dial()
  924. },
  925. TLSConfig: &tls.Config{
  926. InsecureSkipVerify: true,
  927. },
  928. }
  929. req, res := AcquireRequest(), AcquireResponse()
  930. req.SetRequestURI("https://some.url")
  931. err = c.Do(req, res)
  932. if err != nil {
  933. t.Fatal(err)
  934. }
  935. if !bytes.Equal(text, res.Body()) {
  936. t.Fatal("error transmitting information")
  937. }
  938. }
  939. func TestServerTLSReadTimeout(t *testing.T) {
  940. t.Parallel()
  941. ln := fasthttputil.NewInmemoryListener()
  942. s := &Server{
  943. ReadTimeout: time.Millisecond * 500,
  944. Logger: &testLogger{}, // Ignore log output.
  945. Handler: func(ctx *RequestCtx) {
  946. },
  947. }
  948. certData, keyData, err := GenerateTestCertificate("localhost")
  949. if err != nil {
  950. t.Fatal(err)
  951. }
  952. err = s.AppendCertEmbed(certData, keyData)
  953. if err != nil {
  954. t.Fatal(err)
  955. }
  956. go func() {
  957. err = s.ServeTLS(ln, "", "")
  958. if err != nil {
  959. t.Error(err)
  960. }
  961. }()
  962. c, err := ln.Dial()
  963. if err != nil {
  964. t.Error(err)
  965. }
  966. r := make(chan error)
  967. go func() {
  968. b := make([]byte, 1)
  969. _, err := c.Read(b)
  970. c.Close()
  971. r <- err
  972. }()
  973. select {
  974. case err = <-r:
  975. case <-time.After(time.Second * 2):
  976. }
  977. if err == nil {
  978. t.Error("server didn't close connection after timeout")
  979. }
  980. }
  981. func TestServerServeTLSEmbed(t *testing.T) {
  982. t.Parallel()
  983. ln := fasthttputil.NewInmemoryListener()
  984. certData, keyData, err := GenerateTestCertificate("localhost")
  985. if err != nil {
  986. t.Fatal(err)
  987. }
  988. // start the server
  989. ch := make(chan struct{})
  990. go func() {
  991. err := ServeTLSEmbed(ln, certData, keyData, func(ctx *RequestCtx) {
  992. if !ctx.IsTLS() {
  993. ctx.Error("expecting tls", StatusBadRequest)
  994. return
  995. }
  996. if !ctx.URI().isHttps() {
  997. ctx.Error(fmt.Sprintf("unexpected scheme=%q. Expecting %q", ctx.URI().Scheme(), "https"), StatusBadRequest)
  998. return
  999. }
  1000. ctx.WriteString("success") //nolint:errcheck
  1001. })
  1002. if err != nil {
  1003. t.Errorf("unexpected error: %s", err)
  1004. }
  1005. close(ch)
  1006. }()
  1007. // establish connection to the server
  1008. conn, err := ln.Dial()
  1009. if err != nil {
  1010. t.Fatalf("unexpected error: %s", err)
  1011. }
  1012. tlsConn := tls.Client(conn, &tls.Config{
  1013. InsecureSkipVerify: true,
  1014. })
  1015. // send request
  1016. if _, err = tlsConn.Write([]byte("GET / HTTP/1.1\r\nHost: aaa\r\n\r\n")); err != nil {
  1017. t.Fatalf("unexpected error: %s", err)
  1018. }
  1019. // read response
  1020. respCh := make(chan struct{})
  1021. go func() {
  1022. br := bufio.NewReader(tlsConn)
  1023. var resp Response
  1024. if err := resp.Read(br); err != nil {
  1025. t.Error("unexpected error")
  1026. }
  1027. body := resp.Body()
  1028. if string(body) != "success" {
  1029. t.Errorf("unexpected response body %q. Expecting %q", body, "success")
  1030. }
  1031. close(respCh)
  1032. }()
  1033. select {
  1034. case <-respCh:
  1035. case <-time.After(time.Second):
  1036. t.Fatal("timeout")
  1037. }
  1038. // close the server
  1039. if err = ln.Close(); err != nil {
  1040. t.Fatalf("unexpected error: %s", err)
  1041. }
  1042. select {
  1043. case <-ch:
  1044. case <-time.After(time.Second):
  1045. t.Fatal("timeout")
  1046. }
  1047. }
  1048. func TestServerMultipartFormDataRequest(t *testing.T) {
  1049. t.Parallel()
  1050. for _, test := range []struct {
  1051. StreamRequestBody bool
  1052. DisablePreParseMultipartForm bool
  1053. }{
  1054. {false, false},
  1055. {false, true},
  1056. {true, false},
  1057. {true, true},
  1058. } {
  1059. reqS := `POST /upload HTTP/1.1
  1060. Host: qwerty.com
  1061. Content-Length: 521
  1062. Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryJwfATyF8tmxSJnLg
  1063. ------WebKitFormBoundaryJwfATyF8tmxSJnLg
  1064. Content-Disposition: form-data; name="f1"
  1065. value1
  1066. ------WebKitFormBoundaryJwfATyF8tmxSJnLg
  1067. Content-Disposition: form-data; name="fileaaa"; filename="TODO"
  1068. Content-Type: application/octet-stream
  1069. - SessionClient with referer and cookies support.
  1070. - Client with requests' pipelining support.
  1071. - ProxyHandler similar to FSHandler.
  1072. - WebSockets. See https://tools.ietf.org/html/rfc6455 .
  1073. - HTTP/2.0. See https://tools.ietf.org/html/rfc7540 .
  1074. ------WebKitFormBoundaryJwfATyF8tmxSJnLg--
  1075. GET / HTTP/1.1
  1076. Host: asbd
  1077. Connection: close
  1078. `
  1079. ln := fasthttputil.NewInmemoryListener()
  1080. s := &Server{
  1081. StreamRequestBody: test.StreamRequestBody,
  1082. DisablePreParseMultipartForm: test.DisablePreParseMultipartForm,
  1083. Handler: func(ctx *RequestCtx) {
  1084. switch string(ctx.Path()) {
  1085. case "/upload":
  1086. f, err := ctx.MultipartForm()
  1087. if err != nil {
  1088. t.Errorf("unexpected error: %s", err)
  1089. }
  1090. if len(f.Value) != 1 {
  1091. t.Errorf("unexpected values %d. Expecting %d", len(f.Value), 1)
  1092. }
  1093. if len(f.File) != 1 {
  1094. t.Errorf("unexpected file values %d. Expecting %d", len(f.File), 1)
  1095. }
  1096. fv := ctx.FormValue("f1")
  1097. if string(fv) != "value1" {
  1098. t.Errorf("unexpected form value: %q. Expecting %q", fv, "value1")
  1099. }
  1100. ctx.Redirect("/", StatusSeeOther)
  1101. default:
  1102. ctx.WriteString("non-upload") //nolint:errcheck
  1103. }
  1104. },
  1105. }
  1106. ch := make(chan struct{})
  1107. go func() {
  1108. if err := s.Serve(ln); err != nil {
  1109. t.Errorf("unexpected error: %s", err)
  1110. }
  1111. close(ch)
  1112. }()
  1113. conn, err := ln.Dial()
  1114. if err != nil {
  1115. t.Fatalf("unexpected error: %s", err)
  1116. }
  1117. if _, err = conn.Write([]byte(reqS)); err != nil {
  1118. t.Fatalf("unexpected error: %s", err)
  1119. }
  1120. var resp Response
  1121. br := bufio.NewReader(conn)
  1122. respCh := make(chan struct{})
  1123. go func() {
  1124. if err := resp.Read(br); err != nil {
  1125. t.Errorf("error when reading response: %s", err)
  1126. }
  1127. if resp.StatusCode() != StatusSeeOther {
  1128. t.Errorf("unexpected status code %d. Expecting %d", resp.StatusCode(), StatusSeeOther)
  1129. }
  1130. loc := resp.Header.Peek(HeaderLocation)
  1131. if string(loc) != "http://qwerty.com/" {
  1132. t.Errorf("unexpected location %q. Expecting %q", loc, "http://qwerty.com/")
  1133. }
  1134. if err := resp.Read(br); err != nil {
  1135. t.Errorf("error when reading the second response: %s", err)
  1136. }
  1137. if resp.StatusCode() != StatusOK {
  1138. t.Errorf("unexpected status code: %d. Expecting %d", resp.StatusCode(), StatusOK)
  1139. }
  1140. body := resp.Body()
  1141. if string(body) != "non-upload" {
  1142. t.Errorf("unexpected body %q. Expecting %q", body, "non-upload")
  1143. }
  1144. close(respCh)
  1145. }()
  1146. select {
  1147. case <-respCh:
  1148. case <-time.After(time.Second):
  1149. t.Fatal("timeout")
  1150. }
  1151. if err := ln.Close(); err != nil {
  1152. t.Fatalf("error when closing listener: %s", err)
  1153. }
  1154. select {
  1155. case <-ch:
  1156. case <-time.After(time.Second):
  1157. t.Fatal("timeout when waiting for the server to stop")
  1158. }
  1159. }
  1160. }
  1161. func TestServerGetWithContent(t *testing.T) {
  1162. t.Parallel()
  1163. h := func(ctx *RequestCtx) {
  1164. ctx.Success("foo/bar", []byte("success"))
  1165. }
  1166. s := &Server{
  1167. Handler: h,
  1168. }
  1169. rw := &readWriter{}
  1170. rw.r.WriteString("GET / HTTP/1.1\r\nHost: mm.com\r\nContent-Length: 5\r\n\r\nabcde")
  1171. if err := s.ServeConn(rw); err != nil {
  1172. t.Fatalf("Unexpected error from serveConn: %s", err)
  1173. }
  1174. resp := rw.w.String()
  1175. if !strings.HasSuffix(resp, "success") {
  1176. t.Fatalf("unexpected response %s.", resp)
  1177. }
  1178. }
  1179. func TestServerDisableHeaderNamesNormalizing(t *testing.T) {
  1180. t.Parallel()
  1181. headerName := "CASE-senSITive-HEAder-NAME"
  1182. headerNameLower := strings.ToLower(headerName)
  1183. headerValue := "foobar baz"
  1184. s := &Server{
  1185. Handler: func(ctx *RequestCtx) {
  1186. hv := ctx.Request.Header.Peek(headerName)
  1187. if string(hv) != headerValue {
  1188. t.Errorf("unexpected header value for %q: %q. Expecting %q", headerName, hv, headerValue)
  1189. }
  1190. hv = ctx.Request.Header.Peek(headerNameLower)
  1191. if len(hv) > 0 {
  1192. t.Errorf("unexpected header value for %q: %q. Expecting empty value", headerNameLower, hv)
  1193. }
  1194. ctx.Response.Header.Set(headerName, headerValue)
  1195. ctx.WriteString("ok") //nolint:errcheck
  1196. ctx.SetContentType("aaa")
  1197. },
  1198. DisableHeaderNamesNormalizing: true,
  1199. }
  1200. rw := &readWriter{}
  1201. rw.r.WriteString(fmt.Sprintf("GET / HTTP/1.1\r\n%s: %s\r\nHost: google.com\r\n\r\n", headerName, headerValue))
  1202. if err := s.ServeConn(rw); err != nil {
  1203. t.Fatalf("Unexpected error from serveConn: %s", err)
  1204. }
  1205. br := bufio.NewReader(&rw.w)
  1206. var resp Response
  1207. resp.Header.DisableNormalizing()
  1208. if err := resp.Read(br); err != nil {
  1209. t.Fatalf("unexpected error: %s", err)
  1210. }
  1211. hv := resp.Header.Peek(headerName)
  1212. if string(hv) != headerValue {
  1213. t.Fatalf("unexpected header value for %q: %q. Expecting %q", headerName, hv, headerValue)
  1214. }
  1215. hv = resp.Header.Peek(headerNameLower)
  1216. if len(hv) > 0 {
  1217. t.Fatalf("unexpected header value for %q: %q. Expecting empty value", headerNameLower, hv)
  1218. }
  1219. }
  1220. func TestServerReduceMemoryUsageSerial(t *testing.T) {
  1221. t.Parallel()
  1222. ln := fasthttputil.NewInmemoryListener()
  1223. s := &Server{
  1224. Handler: func(ctx *RequestCtx) {},
  1225. ReduceMemoryUsage: true,
  1226. }
  1227. ch := make(chan struct{})
  1228. go func() {
  1229. if err := s.Serve(ln); err != nil {
  1230. t.Errorf("unexpected error: %s", err)
  1231. }
  1232. close(ch)
  1233. }()
  1234. testServerRequests(t, ln)
  1235. if err := ln.Close(); err != nil {
  1236. t.Fatalf("error when closing listener: %s", err)
  1237. }
  1238. select {
  1239. case <-ch:
  1240. case <-time.After(time.Second):
  1241. t.Fatal("timeout when waiting for the server to stop")
  1242. }
  1243. }
  1244. func TestServerReduceMemoryUsageConcurrent(t *testing.T) {
  1245. t.Parallel()
  1246. ln := fasthttputil.NewInmemoryListener()
  1247. s := &Server{
  1248. Handler: func(ctx *RequestCtx) {},
  1249. ReduceMemoryUsage: true,
  1250. }
  1251. ch := make(chan struct{})
  1252. go func() {
  1253. if err := s.Serve(ln); err != nil {
  1254. t.Errorf("unexpected error: %s", err)
  1255. }
  1256. close(ch)
  1257. }()
  1258. gCh := make(chan struct{})
  1259. for i := 0; i < 10; i++ {
  1260. go func() {
  1261. testServerRequests(t, ln)
  1262. gCh <- struct{}{}
  1263. }()
  1264. }
  1265. for i := 0; i < 10; i++ {
  1266. select {
  1267. case <-gCh:
  1268. case <-time.After(time.Second):
  1269. t.Fatalf("timeout on goroutine %d", i)
  1270. }
  1271. }
  1272. if err := ln.Close(); err != nil {
  1273. t.Fatalf("error when closing listener: %s", err)
  1274. }
  1275. select {
  1276. case <-ch:
  1277. case <-time.After(time.Second):
  1278. t.Fatal("timeout when waiting for the server to stop")
  1279. }
  1280. }
  1281. func testServerRequests(t *testing.T, ln *fasthttputil.InmemoryListener) {
  1282. conn, err := ln.Dial()
  1283. if err != nil {
  1284. t.Fatalf("unexpected error: %s", err)
  1285. }
  1286. br := bufio.NewReader(conn)
  1287. var resp Response
  1288. for i := 0; i < 10; i++ {
  1289. if _, err = fmt.Fprintf(conn, "GET / HTTP/1.1\r\nHost: aaa\r\n\r\n"); err != nil {
  1290. t.Fatalf("unexpected error on iteration %d: %s", i, err)
  1291. }
  1292. respCh := make(chan struct{})
  1293. go func() {
  1294. if err = resp.Read(br); err != nil {
  1295. t.Errorf("unexpected error when reading response on iteration %d: %s", i, err)
  1296. }
  1297. close(respCh)
  1298. }()
  1299. select {
  1300. case <-respCh:
  1301. case <-time.After(time.Second):
  1302. t.Fatalf("timeout on iteration %d", i)
  1303. }
  1304. }
  1305. if err = conn.Close(); err != nil {
  1306. t.Fatalf("error when closing the connection: %s", err)
  1307. }
  1308. }
  1309. func TestServerHTTP10ConnectionKeepAlive(t *testing.T) {
  1310. t.Parallel()
  1311. ln := fasthttputil.NewInmemoryListener()
  1312. ch := make(chan struct{})
  1313. go func() {
  1314. err := Serve(ln, func(ctx *RequestCtx) {
  1315. if string(ctx.Path()) == "/close" {
  1316. ctx.SetConnectionClose()
  1317. }
  1318. })
  1319. if err != nil {
  1320. t.Errorf("unexpected error: %s", err)
  1321. }
  1322. close(ch)
  1323. }()
  1324. conn, err := ln.Dial()
  1325. if err != nil {
  1326. t.Fatalf("unexpected error: %s", err)
  1327. }
  1328. _, err = fmt.Fprintf(conn, "%s", "GET / HTTP/1.0\r\nHost: aaa\r\nConnection: keep-alive\r\n\r\n")
  1329. if err != nil {
  1330. t.Fatalf("error when writing request: %s", err)
  1331. }
  1332. _, err = fmt.Fprintf(conn, "%s", "GET /close HTTP/1.0\r\nHost: aaa\r\nConnection: keep-alive\r\n\r\n")
  1333. if err != nil {
  1334. t.Fatalf("error when writing request: %s", err)
  1335. }
  1336. br := bufio.NewReader(conn)
  1337. var resp Response
  1338. if err = resp.Read(br); err != nil {
  1339. t.Fatalf("error when reading response: %s", err)
  1340. }
  1341. if resp.ConnectionClose() {
  1342. t.Fatal("response mustn't have 'Connection: close' header")
  1343. }
  1344. if err = resp.Read(br); err != nil {
  1345. t.Fatalf("error when reading response: %s", err)
  1346. }
  1347. if !resp.ConnectionClose() {
  1348. t.Fatal("response must have 'Connection: close' header")
  1349. }
  1350. tailCh := make(chan struct{})
  1351. go func() {
  1352. tail, err := ioutil.ReadAll(br)
  1353. if err != nil {
  1354. t.Errorf("error when reading tail: %s", err)
  1355. }
  1356. if len(tail) > 0 {
  1357. t.Errorf("unexpected non-zero tail %q", tail)
  1358. }
  1359. close(tailCh)
  1360. }()
  1361. select {
  1362. case <-tailCh:
  1363. case <-time.After(time.Second):
  1364. t.Fatal("timeout when reading tail")
  1365. }
  1366. if err = conn.Close(); err != nil {
  1367. t.Fatalf("error when closing the connection: %s", err)
  1368. }
  1369. if err = ln.Close(); err != nil {
  1370. t.Fatalf("error when closing listener: %s", err)
  1371. }
  1372. select {
  1373. case <-ch:
  1374. case <-time.After(time.Second):
  1375. t.Fatal("timeout when waiting for the server to stop")
  1376. }
  1377. }
  1378. func TestServerHTTP10ConnectionClose(t *testing.T) {
  1379. t.Parallel()
  1380. ln := fasthttputil.NewInmemoryListener()
  1381. ch := make(chan struct{})
  1382. go func() {
  1383. err := Serve(ln, func(ctx *RequestCtx) {
  1384. // The server must close the connection irregardless
  1385. // of request and response state set inside request
  1386. // handler, since the HTTP/1.0 request
  1387. // had no 'Connection: keep-alive' header.
  1388. ctx.Request.Header.ResetConnectionClose()
  1389. ctx.Request.Header.Set(HeaderConnection, "keep-alive")
  1390. ctx.Response.Header.ResetConnectionClose()
  1391. ctx.Response.Header.Set(HeaderConnection, "keep-alive")
  1392. })
  1393. if err != nil {
  1394. t.Errorf("unexpected error: %s", err)
  1395. }
  1396. close(ch)
  1397. }()
  1398. conn, err := ln.Dial()
  1399. if err != nil {
  1400. t.Fatalf("unexpected error: %s", err)
  1401. }
  1402. _, err = fmt.Fprintf(conn, "%s", "GET / HTTP/1.0\r\nHost: aaa\r\n\r\n")
  1403. if err != nil {
  1404. t.Fatalf("error when writing request: %s", err)
  1405. }
  1406. br := bufio.NewReader(conn)
  1407. var resp Response
  1408. if err = resp.Read(br); err != nil {
  1409. t.Fatalf("error when reading response: %s", err)
  1410. }
  1411. if !resp.ConnectionClose() {
  1412. t.Fatal("HTTP1.0 response must have 'Connection: close' header")
  1413. }
  1414. tailCh := make(chan struct{})
  1415. go func() {
  1416. tail, err := ioutil.ReadAll(br)
  1417. if err != nil {
  1418. t.Errorf("error when reading tail: %s", err)
  1419. }
  1420. if len(tail) > 0 {
  1421. t.Errorf("unexpected non-zero tail %q", tail)
  1422. }
  1423. close(tailCh)
  1424. }()
  1425. select {
  1426. case <-tailCh:
  1427. case <-time.After(time.Second):
  1428. t.Fatal("timeout when reading tail")
  1429. }
  1430. if err = conn.Close(); err != nil {
  1431. t.Fatalf("error when closing the connection: %s", err)
  1432. }
  1433. if err = ln.Close(); err != nil {
  1434. t.Fatalf("error when closing listener: %s", err)
  1435. }
  1436. select {
  1437. case <-ch:
  1438. case <-time.After(time.Second):
  1439. t.Fatal("timeout when waiting for the server to stop")
  1440. }
  1441. }
  1442. func TestRequestCtxFormValue(t *testing.T) {
  1443. t.Parallel()
  1444. var ctx RequestCtx
  1445. var req Request
  1446. req.SetRequestURI("/foo/bar?baz=123&aaa=bbb")
  1447. req.SetBodyString("qqq=port&mmm=sddd")
  1448. req.Header.SetContentType("application/x-www-form-urlencoded")
  1449. ctx.Init(&req, nil, nil)
  1450. v := ctx.FormValue("baz")
  1451. if string(v) != "123" {
  1452. t.Fatalf("unexpected value %q. Expecting %q", v, "123")
  1453. }
  1454. v = ctx.FormValue("mmm")
  1455. if string(v) != "sddd" {
  1456. t.Fatalf("unexpected value %q. Expecting %q", v, "sddd")
  1457. }
  1458. v = ctx.FormValue("aaaasdfsdf")
  1459. if len(v) > 0 {
  1460. t.Fatalf("unexpected value for unknown key %q", v)
  1461. }
  1462. }
  1463. func TestRequestCtxUserValue(t *testing.T) {
  1464. t.Parallel()
  1465. var ctx RequestCtx
  1466. for i := 0; i < 5; i++ {
  1467. k := fmt.Sprintf("key-%d", i)
  1468. ctx.SetUserValue(k, i)
  1469. }
  1470. for i := 5; i < 10; i++ {
  1471. k := fmt.Sprintf("key-%d", i)
  1472. ctx.SetUserValueBytes([]byte(k), i)
  1473. }
  1474. for i := 0; i < 10; i++ {
  1475. k := fmt.Sprintf("key-%d", i)
  1476. v := ctx.UserValue(k)
  1477. n, ok := v.(int)
  1478. if !ok || n != i {
  1479. t.Fatalf("unexpected value obtained for key %q: %v. Expecting %d", k, v, i)
  1480. }
  1481. }
  1482. vlen := 0
  1483. ctx.VisitUserValues(func(key []byte, value interface{}) {
  1484. vlen++
  1485. v := ctx.UserValueBytes(key)
  1486. if v != value {
  1487. t.Fatalf("unexpected value obtained from VisitUserValues for key: %q, expecting: %#v but got: %#v", key, v, value)
  1488. }
  1489. })
  1490. if len(ctx.userValues) != vlen {
  1491. t.Fatalf("the length of user values returned from VisitUserValues is not equal to the length of the userValues, expecting: %d but got: %d", len(ctx.userValues), vlen)
  1492. }
  1493. ctx.ResetUserValues()
  1494. for i := 0; i < 10; i++ {
  1495. k := fmt.Sprintf("key-%d", i)
  1496. v := ctx.UserValue(k)
  1497. if v != nil {
  1498. t.Fatalf("unexpected value obtained for key %q: %v. Expecting nil", k, v)
  1499. }
  1500. }
  1501. }
  1502. func TestServerHeadRequest(t *testing.T) {
  1503. t.Parallel()
  1504. s := &Server{
  1505. Handler: func(ctx *RequestCtx) {
  1506. fmt.Fprintf(ctx, "Request method is %q", ctx.Method())
  1507. ctx.SetContentType("aaa/bbb")
  1508. },
  1509. }
  1510. rw := &readWriter{}
  1511. rw.r.WriteString("HEAD /foobar HTTP/1.1\r\nHost: aaa.com\r\n\r\n")
  1512. if err := s.ServeConn(rw); err != nil {
  1513. t.Fatalf("Unexpected error from serveConn: %s", err)
  1514. }
  1515. br := bufio.NewReader(&rw.w)
  1516. var resp Response
  1517. resp.SkipBody = true
  1518. if err := resp.Read(br); err != nil {
  1519. t.Fatalf("Unexpected error when parsing response: %s", err)
  1520. }
  1521. if resp.Header.StatusCode() != StatusOK {
  1522. t.Fatalf("unexpected status code: %d. Expecting %d", resp.Header.StatusCode(), StatusOK)
  1523. }
  1524. if len(resp.Body()) > 0 {
  1525. t.Fatalf("Unexpected non-zero body %q", resp.Body())
  1526. }
  1527. if resp.Header.ContentLength() != 24 {
  1528. t.Fatalf("unexpected content-length %d. Expecting %d", resp.Header.ContentLength(), 24)
  1529. }
  1530. if string(resp.Header.ContentType()) != "aaa/bbb" {
  1531. t.Fatalf("unexpected content-type %q. Expecting %q", resp.Header.ContentType(), "aaa/bbb")
  1532. }
  1533. data, err := ioutil.ReadAll(br)
  1534. if err != nil {
  1535. t.Fatalf("Unexpected error when reading remaining data: %s", err)
  1536. }
  1537. if len(data) > 0 {
  1538. t.Fatalf("unexpected remaining data %q", data)
  1539. }
  1540. }
  1541. func TestServerExpect100Continue(t *testing.T) {
  1542. t.Parallel()
  1543. s := &Server{
  1544. Handler: func(ctx *RequestCtx) {
  1545. if !ctx.IsPost() {
  1546. t.Errorf("unexpected method %q. Expecting POST", ctx.Method())
  1547. }
  1548. if string(ctx.Path()) != "/foo" {
  1549. t.Errorf("unexpected path %q. Expecting %q", ctx.Path(), "/foo")
  1550. }
  1551. ct := ctx.Request.Header.ContentType()
  1552. if string(ct) != "a/b" {
  1553. t.Errorf("unexpectected content-type: %q. Expecting %q", ct, "a/b")
  1554. }
  1555. if string(ctx.PostBody()) != "12345" {
  1556. t.Errorf("unexpected body: %q. Expecting %q", ctx.PostBody(), "12345")
  1557. }
  1558. ctx.WriteString("foobar") //nolint:errcheck
  1559. },
  1560. }
  1561. rw := &readWriter{}
  1562. rw.r.WriteString("POST /foo HTTP/1.1\r\nHost: gle.com\r\nExpect: 100-continue\r\nContent-Length: 5\r\nContent-Type: a/b\r\n\r\n12345")
  1563. if err := s.ServeConn(rw); err != nil {
  1564. t.Fatalf("Unexpected error from serveConn: %s", err)
  1565. }
  1566. br := bufio.NewReader(&rw.w)
  1567. verifyResponse(t, br, StatusOK, string(defaultContentType), "foobar")
  1568. data, err := ioutil.ReadAll(br)
  1569. if err != nil {
  1570. t.Fatalf("Unexpected error when reading remaining data: %s", err)
  1571. }
  1572. if len(data) > 0 {
  1573. t.Fatalf("unexpected remaining data %q", data)
  1574. }
  1575. }
  1576. func TestServerContinueHandler(t *testing.T) {
  1577. t.Parallel()
  1578. acceptContentLength := 5
  1579. s := &Server{
  1580. ContinueHandler: func(headers *RequestHeader) bool {
  1581. if !headers.IsPost() {
  1582. t.Errorf("unexpected method %q. Expecting POST", headers.Method())
  1583. }
  1584. ct := headers.ContentType()
  1585. if string(ct) != "a/b" {
  1586. t.Errorf("unexpectected content-type: %q. Expecting %q", ct, "a/b")
  1587. }
  1588. // Pass on any request that isn't the accepted content length
  1589. return headers.contentLength == acceptContentLength
  1590. },
  1591. Handler: func(ctx *RequestCtx) {
  1592. if ctx.Request.Header.contentLength != acceptContentLength {
  1593. t.Errorf("all requests with content-length: other than %d, should be denied", acceptContentLength)
  1594. }
  1595. if !ctx.IsPost() {
  1596. t.Errorf("unexpected method %q. Expecting POST", ctx.Method())
  1597. }
  1598. if string(ctx.Path()) != "/foo" {
  1599. t.Errorf("unexpected path %q. Expecting %q", ctx.Path(), "/foo")
  1600. }
  1601. ct := ctx.Request.Header.ContentType()
  1602. if string(ct) != "a/b" {
  1603. t.Errorf("unexpectected content-type: %q. Expecting %q", ct, "a/b")
  1604. }
  1605. if string(ctx.PostBody()) != "12345" {
  1606. t.Errorf("unexpected body: %q. Expecting %q", ctx.PostBody(), "12345")
  1607. }
  1608. ctx.WriteString("foobar") //nolint:errcheck
  1609. },
  1610. }
  1611. sendRequest := func(rw *readWriter, expectedStatusCode int, expectedResponse string) {
  1612. if err := s.ServeConn(rw); err != nil {
  1613. t.Fatalf("Unexpected error from serveConn: %s", err)
  1614. }
  1615. br := bufio.NewReader(&rw.w)
  1616. verifyResponse(t, br, expectedStatusCode, string(defaultContentType), expectedResponse)
  1617. data, err := ioutil.ReadAll(br)
  1618. if err != nil {
  1619. t.Fatalf("Unexpected error when reading remaining data: %s", err)
  1620. }
  1621. if len(data) > 0 {
  1622. t.Fatalf("unexpected remaining data %q", data)
  1623. }
  1624. }
  1625. // The same server should not fail when handling the three different types of requests
  1626. // Regular requests
  1627. // Expect 100 continue accepted
  1628. // Exepect 100 continue denied
  1629. rw := &readWriter{}
  1630. for i := 0; i < 25; i++ {
  1631. // Regular requests without Expect 100 continue header
  1632. rw.r.Reset()
  1633. rw.r.WriteString("POST /foo HTTP/1.1\r\nHost: gle.com\r\nContent-Length: 5\r\nContent-Type: a/b\r\n\r\n12345")
  1634. sendRequest(rw, StatusOK, "foobar")
  1635. // Regular Expect 100 continue reqeuests that are accepted
  1636. rw.r.Reset()
  1637. rw.r.WriteString("POST /foo HTTP/1.1\r\nHost: gle.com\r\nExpect: 100-continue\r\nContent-Length: 5\r\nContent-Type: a/b\r\n\r\n12345")
  1638. sendRequest(rw, StatusOK, "foobar")
  1639. // Requests being denied
  1640. rw.r.Reset()
  1641. rw.r.WriteString("POST /foo HTTP/1.1\r\nHost: gle.com\r\nExpect: 100-continue\r\nContent-Length: 6\r\nContent-Type: a/b\r\n\r\n123456")
  1642. sendRequest(rw, StatusExpectationFailed, "")
  1643. }
  1644. }
  1645. func TestCompressHandler(t *testing.T) {
  1646. t.Parallel()
  1647. expectedBody := string(createFixedBody(2e4))
  1648. h := CompressHandler(func(ctx *RequestCtx) {
  1649. ctx.Write([]byte(expectedBody)) //nolint:errcheck
  1650. })
  1651. var ctx RequestCtx
  1652. var resp Response
  1653. // verify uncompressed response
  1654. h(&ctx)
  1655. s := ctx.Response.String()
  1656. br := bufio.NewReader(bytes.NewBufferString(s))
  1657. if err := resp.Read(br); err != nil {
  1658. t.Fatalf("unexpected error: %s", err)
  1659. }
  1660. ce := resp.Header.Peek(HeaderContentEncoding)
  1661. if string(ce) != "" {
  1662. t.Fatalf("unexpected Content-Encoding: %q. Expecting %q", ce, "")
  1663. }
  1664. body := resp.Body()
  1665. if string(body) != expectedBody {
  1666. t.Fatalf("unexpected body %q. Expecting %q", body, expectedBody)
  1667. }
  1668. // verify gzip-compressed response
  1669. ctx.Request.Reset()
  1670. ctx.Response.Reset()
  1671. ctx.Request.Header.Set("Accept-Encoding", "gzip, deflate, sdhc")
  1672. h(&ctx)
  1673. s = ctx.Response.String()
  1674. br = bufio.NewReader(bytes.NewBufferString(s))
  1675. if err := resp.Read(br); err != nil {
  1676. t.Fatalf("unexpected error: %s", err)
  1677. }
  1678. ce = resp.Header.Peek(HeaderContentEncoding)
  1679. if string(ce) != "gzip" {
  1680. t.Fatalf("unexpected Content-Encoding: %q. Expecting %q", ce, "gzip")
  1681. }
  1682. body, err := resp.BodyGunzip()
  1683. if err != nil {
  1684. t.Fatalf("unexpected error: %s", err)
  1685. }
  1686. if string(body) != expectedBody {
  1687. t.Fatalf("unexpected body %q. Expecting %q", body, expectedBody)
  1688. }
  1689. // an attempt to compress already compressed response
  1690. ctx.Request.Reset()
  1691. ctx.Response.Reset()
  1692. ctx.Request.Header.Set("Accept-Encoding", "gzip, deflate, sdhc")
  1693. hh := CompressHandler(h)
  1694. hh(&ctx)
  1695. s = ctx.Response.String()
  1696. br = bufio.NewReader(bytes.NewBufferString(s))
  1697. if err := resp.Read(br); err != nil {
  1698. t.Fatalf("unexpected error: %s", err)
  1699. }
  1700. ce = resp.Header.Peek(HeaderContentEncoding)
  1701. if string(ce) != "gzip" {
  1702. t.Fatalf("unexpected Content-Encoding: %q. Expecting %q", ce, "gzip")
  1703. }
  1704. body, err = resp.BodyGunzip()
  1705. if err != nil {
  1706. t.Fatalf("unexpected error: %s", err)
  1707. }
  1708. if string(body) != expectedBody {
  1709. t.Fatalf("unexpected body %q. Expecting %q", body, expectedBody)
  1710. }
  1711. // verify deflate-compressed response
  1712. ctx.Request.Reset()
  1713. ctx.Response.Reset()
  1714. ctx.Request.Header.Set(HeaderAcceptEncoding, "foobar, deflate, sdhc")
  1715. h(&ctx)
  1716. s = ctx.Response.String()
  1717. br = bufio.NewReader(bytes.NewBufferString(s))
  1718. if err := resp.Read(br); err != nil {
  1719. t.Fatalf("unexpected error: %s", err)
  1720. }
  1721. ce = resp.Header.Peek(HeaderContentEncoding)
  1722. if string(ce) != "deflate" {
  1723. t.Fatalf("unexpected Content-Encoding: %q. Expecting %q", ce, "deflate")
  1724. }
  1725. body, err = resp.BodyInflate()
  1726. if err != nil {
  1727. t.Fatalf("unexpected error: %s", err)
  1728. }
  1729. if string(body) != expectedBody {
  1730. t.Fatalf("unexpected body %q. Expecting %q", body, expectedBody)
  1731. }
  1732. }
  1733. func TestRequestCtxWriteString(t *testing.T) {
  1734. t.Parallel()
  1735. var ctx RequestCtx
  1736. n, err := ctx.WriteString("foo")
  1737. if err != nil {
  1738. t.Fatalf("unexpected error: %s", err)
  1739. }
  1740. if n != 3 {
  1741. t.Fatalf("unexpected n %d. Expecting 3", n)
  1742. }
  1743. n, err = ctx.WriteString("привет")
  1744. if err != nil {
  1745. t.Fatalf("unexpected error: %s", err)
  1746. }
  1747. if n != 12 {
  1748. t.Fatalf("unexpected n=%d. Expecting 12", n)
  1749. }
  1750. s := ctx.Response.Body()
  1751. if string(s) != "fooпривет" {
  1752. t.Fatalf("unexpected response body %q. Expecting %q", s, "fooпривет")
  1753. }
  1754. }
  1755. func TestServeConnKeepRequestAndResponseUntilResetUserValues(t *testing.T) {
  1756. t.Parallel()
  1757. reqStr := "POST /foo HTTP/1.0\r\nHost: google.com\r\nContent-Type: application/octet-stream\r\nContent-Length: 0\r\nConnection: keep-alive\r\n\r\n"
  1758. respRegex := regexp.MustCompile("HTTP/1.1 308 Permanent Redirect\r\nServer: fasthttp\r\nDate: (.*)\r\nContent-Length: 0\r\nConnection: keep-alive\r\n\r\n")
  1759. rw := &readWriter{}
  1760. rw.r.WriteString(reqStr)
  1761. var resultReqStr, resultRespStr string
  1762. ch := make(chan struct{})
  1763. go func() {
  1764. err := ServeConn(rw, func(ctx *RequestCtx) {
  1765. ctx.Response.SetStatusCode(StatusPermanentRedirect)
  1766. ctx.SetUserValue("myKey", &closerWithRequestCtx{
  1767. ctx: ctx,
  1768. closeFunc: func(closerCtx *RequestCtx) error {
  1769. resultReqStr = closerCtx.Request.String()
  1770. resultRespStr = closerCtx.Response.String()
  1771. return nil
  1772. }})
  1773. })
  1774. if err != nil {
  1775. t.Errorf("unexpected error in ServeConn: %s", err)
  1776. }
  1777. close(ch)
  1778. }()
  1779. select {
  1780. case <-ch:
  1781. case <-time.After(time.Second):
  1782. t.Fatal("timeout")
  1783. }
  1784. if resultReqStr != reqStr {
  1785. t.Errorf("Request == %s, want %s", resultReqStr, reqStr)
  1786. }
  1787. if !respRegex.MatchString(resultRespStr) {
  1788. t.Errorf("Response == %s, want regex %s", resultRespStr, respRegex)
  1789. }
  1790. }
  1791. func TestServeConnHijackResetUserValues(t *testing.T) {
  1792. t.Parallel()
  1793. rw := &readWriter{}
  1794. rw.r.WriteString("GET /foo HTTP/1.0\r\nConnection: keep-alive\r\nHost: google.com\r\n\r\n")
  1795. rw.r.WriteString("")
  1796. ch := make(chan struct{})
  1797. go func() {
  1798. err := ServeConn(rw, func(ctx *RequestCtx) {
  1799. ctx.Hijack(func(c net.Conn) {})
  1800. ctx.SetUserValue("myKey", &closerWithRequestCtx{
  1801. closeFunc: func(_ *RequestCtx) error {
  1802. close(ch)
  1803. return nil
  1804. }},
  1805. )
  1806. })
  1807. if err != nil {
  1808. t.Errorf("unexpected error in ServeConn: %s", err)
  1809. }
  1810. }()
  1811. select {
  1812. case <-ch:
  1813. case <-time.After(time.Second):
  1814. t.Errorf("Timeout: UserValues should be reset")
  1815. }
  1816. }
  1817. func TestServeConnNonHTTP11KeepAlive(t *testing.T) {
  1818. t.Parallel()
  1819. rw := &readWriter{}
  1820. rw.r.WriteString("GET /foo HTTP/1.0\r\nConnection: keep-alive\r\nHost: google.com\r\n\r\n")
  1821. rw.r.WriteString("GET /bar HTTP/1.0\r\nHost: google.com\r\n\r\n")
  1822. rw.r.WriteString("GET /must/be/ignored HTTP/1.0\r\nHost: google.com\r\n\r\n")
  1823. requestsServed := 0
  1824. ch := make(chan struct{})
  1825. go func() {
  1826. err := ServeConn(rw, func(ctx *RequestCtx) {
  1827. requestsServed++
  1828. ctx.SuccessString("aaa/bbb", "foobar")
  1829. })
  1830. if err != nil {
  1831. t.Errorf("unexpected error in ServeConn: %s", err)
  1832. }
  1833. close(ch)
  1834. }()
  1835. select {
  1836. case <-ch:
  1837. case <-time.After(time.Second):
  1838. t.Fatal("timeout")
  1839. }
  1840. br := bufio.NewReader(&rw.w)
  1841. var resp Response
  1842. // verify the first response
  1843. if err := resp.Read(br); err != nil {
  1844. t.Fatalf("Unexpected error when parsing response: %s", err)
  1845. }
  1846. if string(resp.Header.Peek(HeaderConnection)) != "keep-alive" {
  1847. t.Fatalf("unexpected Connection header %q. Expecting %q", resp.Header.Peek(HeaderConnection), "keep-alive")
  1848. }
  1849. if resp.Header.ConnectionClose() {
  1850. t.Fatal("unexpected Connection: close")
  1851. }
  1852. // verify the second response
  1853. if err := resp.Read(br); err != nil {
  1854. t.Fatalf("Unexpected error when parsing response: %s", err)
  1855. }
  1856. if string(resp.Header.Peek(HeaderConnection)) != "close" {
  1857. t.Fatalf("unexpected Connection header %q. Expecting %q", resp.Header.Peek(HeaderConnection), "close")
  1858. }
  1859. if !resp.Header.ConnectionClose() {
  1860. t.Fatal("expecting Connection: close")
  1861. }
  1862. data, err := ioutil.ReadAll(br)
  1863. if err != nil {
  1864. t.Fatalf("Unexpected error when reading remaining data: %s", err)
  1865. }
  1866. if len(data) != 0 {
  1867. t.Fatalf("Unexpected data read after responses %q", data)
  1868. }
  1869. if requestsServed != 2 {
  1870. t.Fatalf("unexpected number of requests served: %d. Expecting 2", requestsServed)
  1871. }
  1872. }
  1873. func TestRequestCtxSetBodyStreamWriter(t *testing.T) {
  1874. t.Parallel()
  1875. var ctx RequestCtx
  1876. var req Request
  1877. ctx.Init(&req, nil, defaultLogger)
  1878. if ctx.IsBodyStream() {
  1879. t.Fatal("IsBodyStream must return false")
  1880. }
  1881. ctx.SetBodyStreamWriter(func(w *bufio.Writer) {
  1882. fmt.Fprintf(w, "body writer line 1\n")
  1883. if err := w.Flush(); err != nil {
  1884. t.Errorf("unexpected error: %s", err)
  1885. }
  1886. fmt.Fprintf(w, "body writer line 2\n")
  1887. })
  1888. if !ctx.IsBodyStream() {
  1889. t.Fatal("IsBodyStream must return true")
  1890. }
  1891. s := ctx.Response.String()
  1892. br := bufio.NewReader(bytes.NewBufferString(s))
  1893. var resp Response
  1894. if err := resp.Read(br); err != nil {
  1895. t.Fatalf("Error when reading response: %s", err)
  1896. }
  1897. body := string(resp.Body())
  1898. expectedBody := "body writer line 1\nbody writer line 2\n"
  1899. if body != expectedBody {
  1900. t.Fatalf("unexpected body: %q. Expecting %q", body, expectedBody)
  1901. }
  1902. }
  1903. func TestRequestCtxIfModifiedSince(t *testing.T) {
  1904. t.Parallel()
  1905. var ctx RequestCtx
  1906. var req Request
  1907. ctx.Init(&req, nil, defaultLogger)
  1908. lastModified := time.Now().Add(-time.Hour)
  1909. if !ctx.IfModifiedSince(lastModified) {
  1910. t.Fatal("IfModifiedSince must return true for non-existing If-Modified-Since header")
  1911. }
  1912. ctx.Request.Header.Set("If-Modified-Since", string(AppendHTTPDate(nil, lastModified)))
  1913. if ctx.IfModifiedSince(lastModified) {
  1914. t.Fatal("If-Modified-Since current time must return false")
  1915. }
  1916. past := lastModified.Add(-time.Hour)
  1917. if ctx.IfModifiedSince(past) {
  1918. t.Fatal("If-Modified-Since past time must return false")
  1919. }
  1920. future := lastModified.Add(time.Hour)
  1921. if !ctx.IfModifiedSince(future) {
  1922. t.Fatal("If-Modified-Since future time must return true")
  1923. }
  1924. }
  1925. func TestRequestCtxSendFileNotModified(t *testing.T) {
  1926. t.Parallel()
  1927. var ctx RequestCtx
  1928. var req Request
  1929. ctx.Init(&req, nil, defaultLogger)
  1930. filePath := "./server_test.go"
  1931. lastModified, err := FileLastModified(filePath)
  1932. if err != nil {
  1933. t.Fatalf("unexpected error: %s", err)
  1934. }
  1935. ctx.Request.Header.Set("If-Modified-Since", string(AppendHTTPDate(nil, lastModified)))
  1936. ctx.SendFile(filePath)
  1937. s := ctx.Response.String()
  1938. var resp Response
  1939. br := bufio.NewReader(bytes.NewBufferString(s))
  1940. if err := resp.Read(br); err != nil {
  1941. t.Fatalf("error when reading response: %s", err)
  1942. }
  1943. if resp.StatusCode() != StatusNotModified {
  1944. t.Fatalf("unexpected status code: %d. Expecting %d", resp.StatusCode(), StatusNotModified)
  1945. }
  1946. if len(resp.Body()) > 0 {
  1947. t.Fatalf("unexpected non-zero response body: %q", resp.Body())
  1948. }
  1949. }
  1950. func TestRequestCtxSendFileModified(t *testing.T) {
  1951. t.Parallel()
  1952. var ctx RequestCtx
  1953. var req Request
  1954. ctx.Init(&req, nil, defaultLogger)
  1955. filePath := "./server_test.go"
  1956. lastModified, err := FileLastModified(filePath)
  1957. if err != nil {
  1958. t.Fatalf("unexpected error: %s", err)
  1959. }
  1960. lastModified = lastModified.Add(-time.Hour)
  1961. ctx.Request.Header.Set("If-Modified-Since", string(AppendHTTPDate(nil, lastModified)))
  1962. ctx.SendFile(filePath)
  1963. s := ctx.Response.String()
  1964. var resp Response
  1965. br := bufio.NewReader(bytes.NewBufferString(s))
  1966. if err := resp.Read(br); err != nil {
  1967. t.Fatalf("error when reading response: %s", err)
  1968. }
  1969. if resp.StatusCode() != StatusOK {
  1970. t.Fatalf("unexpected status code: %d. Expecting %d", resp.StatusCode(), StatusOK)
  1971. }
  1972. f, err := os.Open(filePath)
  1973. if err != nil {
  1974. t.Fatalf("cannot open file: %s", err)
  1975. }
  1976. body, err := ioutil.ReadAll(f)
  1977. f.Close()
  1978. if err != nil {
  1979. t.Fatalf("error when reading file: %s", err)
  1980. }
  1981. if !bytes.Equal(resp.Body(), body) {
  1982. t.Fatalf("unexpected response body: %q. Expecting %q", resp.Body(), body)
  1983. }
  1984. }
  1985. func TestRequestCtxSendFile(t *testing.T) {
  1986. t.Parallel()
  1987. var ctx RequestCtx
  1988. var req Request
  1989. ctx.Init(&req, nil, defaultLogger)
  1990. filePath := "./server_test.go"
  1991. ctx.SendFile(filePath)
  1992. w := &bytes.Buffer{}
  1993. bw := bufio.NewWriter(w)
  1994. if err := ctx.Response.Write(bw); err != nil {
  1995. t.Fatalf("error when writing response: %s", err)
  1996. }
  1997. if err := bw.Flush(); err != nil {
  1998. t.Fatalf("error when flushing response: %s", err)
  1999. }
  2000. var resp Response
  2001. br := bufio.NewReader(w)
  2002. if err := resp.Read(br); err != nil {
  2003. t.Fatalf("error when reading response: %s", err)
  2004. }
  2005. if resp.StatusCode() != StatusOK {
  2006. t.Fatalf("unexpected status code: %d. Expecting %d", resp.StatusCode(), StatusOK)
  2007. }
  2008. f, err := os.Open(filePath)
  2009. if err != nil {
  2010. t.Fatalf("cannot open file: %s", err)
  2011. }
  2012. body, err := ioutil.ReadAll(f)
  2013. f.Close()
  2014. if err != nil {
  2015. t.Fatalf("error when reading file: %s", err)
  2016. }
  2017. if !bytes.Equal(resp.Body(), body) {
  2018. t.Fatalf("unexpected response body: %q. Expecting %q", resp.Body(), body)
  2019. }
  2020. }
  2021. func TestRequestCtxHijack(t *testing.T) {
  2022. t.Parallel()
  2023. hijackStartCh := make(chan struct{})
  2024. hijackStopCh := make(chan struct{})
  2025. s := &Server{
  2026. Handler: func(ctx *RequestCtx) {
  2027. if ctx.Hijacked() {
  2028. t.Error("connection mustn't be hijacked")
  2029. }
  2030. ctx.Hijack(func(c net.Conn) {
  2031. <-hijackStartCh
  2032. b := make([]byte, 1)
  2033. // ping-pong echo via hijacked conn
  2034. for {
  2035. n, err := c.Read(b)
  2036. if n != 1 {
  2037. if err == io.EOF {
  2038. close(hijackStopCh)
  2039. return
  2040. }
  2041. if err != nil {
  2042. t.Errorf("unexpected error: %s", err)
  2043. }
  2044. t.Errorf("unexpected number of bytes read: %d. Expecting 1", n)
  2045. }
  2046. if _, err = c.Write(b); err != nil {
  2047. t.Errorf("unexpected error when writing data: %s", err)
  2048. }
  2049. }
  2050. })
  2051. if !ctx.Hijacked() {
  2052. t.Error("connection must be hijacked")
  2053. }
  2054. ctx.Success("foo/bar", []byte("hijack it!"))
  2055. },
  2056. }
  2057. hijackedString := "foobar baz hijacked!!!"
  2058. rw := &readWriter{}
  2059. rw.r.WriteString("GET /foo HTTP/1.1\r\nHost: google.com\r\n\r\n")
  2060. rw.r.WriteString(hijackedString)
  2061. if err := s.ServeConn(rw); err != nil {
  2062. t.Fatalf("Unexpected error from serveConn: %s", err)
  2063. }
  2064. br := bufio.NewReader(&rw.w)
  2065. verifyResponse(t, br, StatusOK, "foo/bar", "hijack it!")
  2066. close(hijackStartCh)
  2067. select {
  2068. case <-hijackStopCh:
  2069. case <-time.After(100 * time.Millisecond):
  2070. t.Fatal("timeout")
  2071. }
  2072. data, err := ioutil.ReadAll(br)
  2073. if err != nil {
  2074. t.Fatalf("Unexpected error when reading remaining data: %s", err)
  2075. }
  2076. if string(data) != hijackedString {
  2077. t.Fatalf("Unexpected data read after the first response %q. Expecting %q", data, hijackedString)
  2078. }
  2079. }
  2080. func TestRequestCtxHijackNoResponse(t *testing.T) {
  2081. t.Parallel()
  2082. hijackDone := make(chan error)
  2083. s := &Server{
  2084. Handler: func(ctx *RequestCtx) {
  2085. ctx.Hijack(func(c net.Conn) {
  2086. _, err := c.Write([]byte("test"))
  2087. hijackDone <- err
  2088. })
  2089. ctx.HijackSetNoResponse(true)
  2090. },
  2091. }
  2092. rw := &readWriter{}
  2093. rw.r.WriteString("GET /foo HTTP/1.1\r\nHost: google.com\r\nContent-Length: 0\r\n\r\n")
  2094. if err := s.ServeConn(rw); err != nil {
  2095. t.Fatalf("Unexpected error from serveConn: %s", err)
  2096. }
  2097. select {
  2098. case err := <-hijackDone:
  2099. if err != nil {
  2100. t.Fatalf("Unexpected error from hijack: %s", err)
  2101. }
  2102. case <-time.After(100 * time.Millisecond):
  2103. t.Fatal("timeout")
  2104. }
  2105. if got := rw.w.String(); got != "test" {
  2106. t.Errorf(`expected "test", got %q`, got)
  2107. }
  2108. }
  2109. func TestRequestCtxNoHijackNoResponse(t *testing.T) {
  2110. t.Parallel()
  2111. s := &Server{
  2112. Handler: func(ctx *RequestCtx) {
  2113. io.WriteString(ctx, "test") //nolint:errcheck
  2114. ctx.HijackSetNoResponse(true)
  2115. },
  2116. }
  2117. rw := &readWriter{}
  2118. rw.r.WriteString("GET /foo HTTP/1.1\r\nHost: google.com\r\nContent-Length: 0\r\n\r\n")
  2119. if err := s.ServeConn(rw); err != nil {
  2120. t.Fatalf("Unexpected error from serveConn: %s", err)
  2121. }
  2122. bf := bufio.NewReader(
  2123. strings.NewReader(rw.w.String()),
  2124. )
  2125. resp := AcquireResponse()
  2126. resp.Read(bf) //nolint:errcheck
  2127. if got := string(resp.Body()); got != "test" {
  2128. t.Errorf(`expected "test", got %q`, got)
  2129. }
  2130. }
  2131. func TestRequestCtxInit(t *testing.T) {
  2132. // This test can't run parallel as it modifies globalConnID.
  2133. var ctx RequestCtx
  2134. var logger testLogger
  2135. globalConnID = 0x123456
  2136. ctx.Init(&ctx.Request, zeroTCPAddr, &logger)
  2137. ip := ctx.RemoteIP()
  2138. if !ip.IsUnspecified() {
  2139. t.Fatalf("unexpected ip for bare RequestCtx: %q. Expected 0.0.0.0", ip)
  2140. }
  2141. ctx.Logger().Printf("foo bar %d", 10)
  2142. expectedLog := "#0012345700000000 - 0.0.0.0:0<->0.0.0.0:0 - GET http:/// - foo bar 10\n"
  2143. if logger.out != expectedLog {
  2144. t.Fatalf("Unexpected log output: %q. Expected %q", logger.out, expectedLog)
  2145. }
  2146. }
  2147. func TestTimeoutHandlerSuccess(t *testing.T) {
  2148. t.Parallel()
  2149. ln := fasthttputil.NewInmemoryListener()
  2150. h := func(ctx *RequestCtx) {
  2151. if string(ctx.Path()) == "/" {
  2152. ctx.Success("aaa/bbb", []byte("real response"))
  2153. }
  2154. }
  2155. s := &Server{
  2156. Handler: TimeoutHandler(h, 10*time.Second, "timeout!!!"),
  2157. }
  2158. serverCh := make(chan struct{})
  2159. go func() {
  2160. if err := s.Serve(ln); err != nil {
  2161. t.Errorf("unexepcted error: %s", err)
  2162. }
  2163. close(serverCh)
  2164. }()
  2165. concurrency := 20
  2166. clientCh := make(chan struct{}, concurrency)
  2167. for i := 0; i < concurrency; i++ {
  2168. go func() {
  2169. conn, err := ln.Dial()
  2170. if err != nil {
  2171. t.Errorf("unexepcted error: %s", err)
  2172. }
  2173. if _, err = conn.Write([]byte("GET / HTTP/1.1\r\nHost: google.com\r\n\r\n")); err != nil {
  2174. t.Errorf("unexpected error: %s", err)
  2175. }
  2176. br := bufio.NewReader(conn)
  2177. verifyResponse(t, br, StatusOK, "aaa/bbb", "real response")
  2178. clientCh <- struct{}{}
  2179. }()
  2180. }
  2181. for i := 0; i < concurrency; i++ {
  2182. select {
  2183. case <-clientCh:
  2184. case <-time.After(time.Second):
  2185. t.Fatal("timeout")
  2186. }
  2187. }
  2188. if err := ln.Close(); err != nil {
  2189. t.Fatalf("unexpected error: %s", err)
  2190. }
  2191. select {
  2192. case <-serverCh:
  2193. case <-time.After(time.Second):
  2194. t.Fatal("timeout")
  2195. }
  2196. }
  2197. func TestTimeoutHandlerTimeout(t *testing.T) {
  2198. t.Parallel()
  2199. ln := fasthttputil.NewInmemoryListener()
  2200. readyCh := make(chan struct{})
  2201. doneCh := make(chan struct{})
  2202. h := func(ctx *RequestCtx) {
  2203. ctx.Success("aaa/bbb", []byte("real response"))
  2204. <-readyCh
  2205. doneCh <- struct{}{}
  2206. }
  2207. s := &Server{
  2208. Handler: TimeoutHandler(h, 20*time.Millisecond, "timeout!!!"),
  2209. }
  2210. serverCh := make(chan struct{})
  2211. go func() {
  2212. if err := s.Serve(ln); err != nil {
  2213. t.Errorf("unexepcted error: %s", err)
  2214. }
  2215. close(serverCh)
  2216. }()
  2217. concurrency := 20
  2218. clientCh := make(chan struct{}, concurrency)
  2219. for i := 0; i < concurrency; i++ {
  2220. go func() {
  2221. conn, err := ln.Dial()
  2222. if err != nil {
  2223. t.Errorf("unexpected error: %s", err)
  2224. }
  2225. if _, err = conn.Write([]byte("GET / HTTP/1.1\r\nHost: google.com\r\n\r\n")); err != nil {
  2226. t.Errorf("unexpected error: %s", err)
  2227. }
  2228. br := bufio.NewReader(conn)
  2229. verifyResponse(t, br, StatusRequestTimeout, string(defaultContentType), "timeout!!!")
  2230. clientCh <- struct{}{}
  2231. }()
  2232. }
  2233. for i := 0; i < concurrency; i++ {
  2234. select {
  2235. case <-clientCh:
  2236. case <-time.After(time.Second):
  2237. t.Fatal("timeout")
  2238. }
  2239. }
  2240. close(readyCh)
  2241. for i := 0; i < concurrency; i++ {
  2242. select {
  2243. case <-doneCh:
  2244. case <-time.After(time.Second):
  2245. t.Fatal("timeout")
  2246. }
  2247. }
  2248. if err := ln.Close(); err != nil {
  2249. t.Fatalf("unexpected error: %s", err)
  2250. }
  2251. select {
  2252. case <-serverCh:
  2253. case <-time.After(time.Second):
  2254. t.Fatal("timeout")
  2255. }
  2256. }
  2257. func TestTimeoutHandlerTimeoutReuse(t *testing.T) {
  2258. t.Parallel()
  2259. ln := fasthttputil.NewInmemoryListener()
  2260. h := func(ctx *RequestCtx) {
  2261. if string(ctx.Path()) == "/timeout" {
  2262. time.Sleep(time.Second)
  2263. }
  2264. ctx.SetBodyString("ok")
  2265. }
  2266. s := &Server{
  2267. Handler: TimeoutHandler(h, 500*time.Millisecond, "timeout!!!"),
  2268. }
  2269. go func() {
  2270. if err := s.Serve(ln); err != nil {
  2271. t.Errorf("unexepcted error: %s", err)
  2272. }
  2273. }()
  2274. conn, err := ln.Dial()
  2275. if err != nil {
  2276. t.Fatalf("unexpected error: %s", err)
  2277. }
  2278. br := bufio.NewReader(conn)
  2279. if _, err = conn.Write([]byte("GET /timeout HTTP/1.1\r\nHost: google.com\r\n\r\n")); err != nil {
  2280. t.Fatalf("unexpected error: %s", err)
  2281. }
  2282. verifyResponse(t, br, StatusRequestTimeout, string(defaultContentType), "timeout!!!")
  2283. if _, err = conn.Write([]byte("GET / HTTP/1.1\r\nHost: google.com\r\n\r\n")); err != nil {
  2284. t.Fatalf("unexpected error: %s", err)
  2285. }
  2286. verifyResponse(t, br, StatusOK, string(defaultContentType), "ok")
  2287. if err := ln.Close(); err != nil {
  2288. t.Fatalf("unexpected error: %s", err)
  2289. }
  2290. }
  2291. func TestServerGetOnly(t *testing.T) {
  2292. t.Parallel()
  2293. h := func(ctx *RequestCtx) {
  2294. if !ctx.IsGet() {
  2295. t.Errorf("non-get request: %q", ctx.Method())
  2296. }
  2297. ctx.Success("foo/bar", []byte("success"))
  2298. }
  2299. s := &Server{
  2300. Handler: h,
  2301. GetOnly: true,
  2302. }
  2303. rw := &readWriter{}
  2304. rw.r.WriteString("POST /foo HTTP/1.1\r\nHost: google.com\r\nContent-Length: 5\r\nContent-Type: aaa\r\n\r\n12345")
  2305. ch := make(chan error)
  2306. go func() {
  2307. ch <- s.ServeConn(rw)
  2308. }()
  2309. select {
  2310. case err := <-ch:
  2311. if err == nil {
  2312. t.Fatal("expecting error")
  2313. }
  2314. if err != ErrGetOnly {
  2315. t.Fatalf("Unexpected error from serveConn: %s. Expecting %s", err, ErrGetOnly)
  2316. }
  2317. case <-time.After(100 * time.Millisecond):
  2318. t.Fatal("timeout")
  2319. }
  2320. br := bufio.NewReader(&rw.w)
  2321. var resp Response
  2322. if err := resp.Read(br); err != nil {
  2323. t.Fatalf("unexpected error: %s", err)
  2324. }
  2325. statusCode := resp.StatusCode()
  2326. if statusCode != StatusBadRequest {
  2327. t.Fatalf("unexpected status code: %d. Expecting %d", statusCode, StatusBadRequest)
  2328. }
  2329. if !resp.ConnectionClose() {
  2330. t.Fatal("missing 'Connection: close' response header")
  2331. }
  2332. }
  2333. func TestServerTimeoutErrorWithResponse(t *testing.T) {
  2334. t.Parallel()
  2335. s := &Server{
  2336. Handler: func(ctx *RequestCtx) {
  2337. go func() {
  2338. ctx.Success("aaa/bbb", []byte("xxxyyy"))
  2339. }()
  2340. var resp Response
  2341. resp.SetStatusCode(123)
  2342. resp.SetBodyString("foobar. Should be ignored")
  2343. ctx.TimeoutErrorWithResponse(&resp)
  2344. resp.SetStatusCode(456)
  2345. resp.ResetBody()
  2346. fmt.Fprintf(resp.BodyWriter(), "path=%s", ctx.Path())
  2347. resp.Header.SetContentType("foo/bar")
  2348. ctx.TimeoutErrorWithResponse(&resp)
  2349. },
  2350. }
  2351. rw := &readWriter{}
  2352. rw.r.WriteString("GET /foo HTTP/1.1\r\nHost: google.com\r\n\r\n")
  2353. rw.r.WriteString("GET /bar HTTP/1.1\r\nHost: google.com\r\n\r\n")
  2354. if err := s.ServeConn(rw); err != nil {
  2355. t.Fatalf("Unexpected error from serveConn: %s", err)
  2356. }
  2357. br := bufio.NewReader(&rw.w)
  2358. verifyResponse(t, br, 456, "foo/bar", "path=/foo")
  2359. verifyResponse(t, br, 456, "foo/bar", "path=/bar")
  2360. data, err := ioutil.ReadAll(br)
  2361. if err != nil {
  2362. t.Fatalf("Unexpected error when reading remaining data: %s", err)
  2363. }
  2364. if len(data) != 0 {
  2365. t.Fatalf("Unexpected data read after the first response %q. Expecting %q", data, "")
  2366. }
  2367. }
  2368. func TestServerTimeoutErrorWithCode(t *testing.T) {
  2369. t.Parallel()
  2370. s := &Server{
  2371. Handler: func(ctx *RequestCtx) {
  2372. go func() {
  2373. ctx.Success("aaa/bbb", []byte("xxxyyy"))
  2374. }()
  2375. ctx.TimeoutErrorWithCode("should be ignored", 234)
  2376. ctx.TimeoutErrorWithCode("stolen ctx", StatusBadRequest)
  2377. },
  2378. }
  2379. rw := &readWriter{}
  2380. rw.r.WriteString("GET /foo HTTP/1.1\r\nHost: google.com\r\n\r\n")
  2381. rw.r.WriteString("GET /foo HTTP/1.1\r\nHost: google.com\r\n\r\n")
  2382. if err := s.ServeConn(rw); err != nil {
  2383. t.Fatalf("Unexpected error from serveConn: %s", err)
  2384. }
  2385. br := bufio.NewReader(&rw.w)
  2386. verifyResponse(t, br, StatusBadRequest, string(defaultContentType), "stolen ctx")
  2387. verifyResponse(t, br, StatusBadRequest, string(defaultContentType), "stolen ctx")
  2388. data, err := ioutil.ReadAll(br)
  2389. if err != nil {
  2390. t.Fatalf("Unexpected error when reading remaining data: %s", err)
  2391. }
  2392. if len(data) != 0 {
  2393. t.Fatalf("Unexpected data read after the first response %q. Expecting %q", data, "")
  2394. }
  2395. }
  2396. func TestServerTimeoutError(t *testing.T) {
  2397. t.Parallel()
  2398. s := &Server{
  2399. Handler: func(ctx *RequestCtx) {
  2400. go func() {
  2401. ctx.Success("aaa/bbb", []byte("xxxyyy"))
  2402. }()
  2403. ctx.TimeoutError("should be ignored")
  2404. ctx.TimeoutError("stolen ctx")
  2405. },
  2406. }
  2407. rw := &readWriter{}
  2408. rw.r.WriteString("GET /foo HTTP/1.1\r\nHost: google.com\r\n\r\n")
  2409. rw.r.WriteString("GET /foo HTTP/1.1\r\nHost: google.com\r\n\r\n")
  2410. if err := s.ServeConn(rw); err != nil {
  2411. t.Fatalf("Unexpected error from serveConn: %s", err)
  2412. }
  2413. br := bufio.NewReader(&rw.w)
  2414. verifyResponse(t, br, StatusRequestTimeout, string(defaultContentType), "stolen ctx")
  2415. verifyResponse(t, br, StatusRequestTimeout, string(defaultContentType), "stolen ctx")
  2416. data, err := ioutil.ReadAll(br)
  2417. if err != nil {
  2418. t.Fatalf("Unexpected error when reading remaining data: %s", err)
  2419. }
  2420. if len(data) != 0 {
  2421. t.Fatalf("Unexpected data read after the first response %q. Expecting %q", data, "")
  2422. }
  2423. }
  2424. func TestServerMaxRequestsPerConn(t *testing.T) {
  2425. t.Parallel()
  2426. s := &Server{
  2427. Handler: func(ctx *RequestCtx) {},
  2428. MaxRequestsPerConn: 1,
  2429. }
  2430. rw := &readWriter{}
  2431. rw.r.WriteString("GET /foo1 HTTP/1.1\r\nHost: google.com\r\n\r\n")
  2432. rw.r.WriteString("GET /bar HTTP/1.1\r\nHost: aaa.com\r\n\r\n")
  2433. if err := s.ServeConn(rw); err != nil {
  2434. t.Fatalf("Unexpected error from serveConn: %s", err)
  2435. }
  2436. br := bufio.NewReader(&rw.w)
  2437. var resp Response
  2438. if err := resp.Read(br); err != nil {
  2439. t.Fatalf("Unexpected error when parsing response: %s", err)
  2440. }
  2441. if !resp.ConnectionClose() {
  2442. t.Fatal("Response must have 'connection: close' header")
  2443. }
  2444. verifyResponseHeader(t, &resp.Header, 200, 0, string(defaultContentType))
  2445. data, err := ioutil.ReadAll(br)
  2446. if err != nil {
  2447. t.Fatalf("Unexpected error when reading remaining data: %s", err)
  2448. }
  2449. if len(data) != 0 {
  2450. t.Fatalf("Unexpected data read after the first response %q. Expecting %q", data, "")
  2451. }
  2452. }
  2453. func TestServerConnectionClose(t *testing.T) {
  2454. t.Parallel()
  2455. s := &Server{
  2456. Handler: func(ctx *RequestCtx) {
  2457. ctx.SetConnectionClose()
  2458. },
  2459. }
  2460. rw := &readWriter{}
  2461. rw.r.WriteString("GET /foo1 HTTP/1.1\r\nHost: google.com\r\n\r\n")
  2462. rw.r.WriteString("GET /must/be/ignored HTTP/1.1\r\nHost: aaa.com\r\n\r\n")
  2463. if err := s.ServeConn(rw); err != nil {
  2464. t.Fatalf("Unexpected error from serveConn: %s", err)
  2465. }
  2466. br := bufio.NewReader(&rw.w)
  2467. var resp Response
  2468. if err := resp.Read(br); err != nil {
  2469. t.Fatalf("Unexpected error when parsing response: %s", err)
  2470. }
  2471. if !resp.ConnectionClose() {
  2472. t.Fatal("expecting Connection: close header")
  2473. }
  2474. data, err := ioutil.ReadAll(br)
  2475. if err != nil {
  2476. t.Fatalf("Unexpected error when reading remaining data: %s", err)
  2477. }
  2478. if len(data) != 0 {
  2479. t.Fatalf("Unexpected data read after the first response %q. Expecting %q", data, "")
  2480. }
  2481. }
  2482. func TestServerRequestNumAndTime(t *testing.T) {
  2483. t.Parallel()
  2484. n := uint64(0)
  2485. var connT time.Time
  2486. s := &Server{
  2487. Handler: func(ctx *RequestCtx) {
  2488. n++
  2489. if ctx.ConnRequestNum() != n {
  2490. t.Errorf("unexpected request number: %d. Expecting %d", ctx.ConnRequestNum(), n)
  2491. }
  2492. if connT.IsZero() {
  2493. connT = ctx.ConnTime()
  2494. }
  2495. if ctx.ConnTime() != connT {
  2496. t.Errorf("unexpected serve conn time: %s. Expecting %s", ctx.ConnTime(), connT)
  2497. }
  2498. },
  2499. }
  2500. rw := &readWriter{}
  2501. rw.r.WriteString("GET /foo1 HTTP/1.1\r\nHost: google.com\r\n\r\n")
  2502. rw.r.WriteString("GET /bar HTTP/1.1\r\nHost: google.com\r\n\r\n")
  2503. rw.r.WriteString("GET /baz HTTP/1.1\r\nHost: google.com\r\n\r\n")
  2504. if err := s.ServeConn(rw); err != nil {
  2505. t.Fatalf("Unexpected error from serveConn: %s", err)
  2506. }
  2507. if n != 3 {
  2508. t.Fatalf("unexpected number of requests served: %d. Expecting %d", n, 3)
  2509. }
  2510. br := bufio.NewReader(&rw.w)
  2511. verifyResponse(t, br, 200, string(defaultContentType), "")
  2512. }
  2513. func TestServerEmptyResponse(t *testing.T) {
  2514. t.Parallel()
  2515. s := &Server{
  2516. Handler: func(ctx *RequestCtx) {
  2517. // do nothing :)
  2518. },
  2519. }
  2520. rw := &readWriter{}
  2521. rw.r.WriteString("GET /foo1 HTTP/1.1\r\nHost: google.com\r\n\r\n")
  2522. if err := s.ServeConn(rw); err != nil {
  2523. t.Fatalf("Unexpected error from serveConn: %s", err)
  2524. }
  2525. br := bufio.NewReader(&rw.w)
  2526. verifyResponse(t, br, 200, string(defaultContentType), "")
  2527. }
  2528. func TestServerLogger(t *testing.T) {
  2529. // This test can't run parallel as it modifies globalConnID.
  2530. cl := &testLogger{}
  2531. s := &Server{
  2532. Handler: func(ctx *RequestCtx) {
  2533. logger := ctx.Logger()
  2534. h := &ctx.Request.Header
  2535. logger.Printf("begin")
  2536. ctx.Success("text/html", []byte(fmt.Sprintf("requestURI=%s, body=%q, remoteAddr=%s",
  2537. h.RequestURI(), ctx.Request.Body(), ctx.RemoteAddr())))
  2538. logger.Printf("end")
  2539. },
  2540. Logger: cl,
  2541. }
  2542. rw := &readWriter{}
  2543. rw.r.WriteString("GET /foo1 HTTP/1.1\r\nHost: google.com\r\n\r\n")
  2544. rw.r.WriteString("POST /foo2 HTTP/1.1\r\nHost: aaa.com\r\nContent-Length: 5\r\nContent-Type: aa\r\n\r\nabcde")
  2545. rwx := &readWriterRemoteAddr{
  2546. rw: rw,
  2547. addr: &net.TCPAddr{
  2548. IP: []byte{1, 2, 3, 4},
  2549. Port: 8765,
  2550. },
  2551. }
  2552. globalConnID = 0
  2553. if err := s.ServeConn(rwx); err != nil {
  2554. t.Fatalf("Unexpected error from serveConn: %s", err)
  2555. }
  2556. br := bufio.NewReader(&rw.w)
  2557. verifyResponse(t, br, 200, "text/html", "requestURI=/foo1, body=\"\", remoteAddr=1.2.3.4:8765")
  2558. verifyResponse(t, br, 200, "text/html", "requestURI=/foo2, body=\"abcde\", remoteAddr=1.2.3.4:8765")
  2559. expectedLogOut := `#0000000100000001 - 1.2.3.4:8765<->1.2.3.4:8765 - GET http://google.com/foo1 - begin
  2560. #0000000100000001 - 1.2.3.4:8765<->1.2.3.4:8765 - GET http://google.com/foo1 - end
  2561. #0000000100000002 - 1.2.3.4:8765<->1.2.3.4:8765 - POST http://aaa.com/foo2 - begin
  2562. #0000000100000002 - 1.2.3.4:8765<->1.2.3.4:8765 - POST http://aaa.com/foo2 - end
  2563. `
  2564. if cl.out != expectedLogOut {
  2565. t.Fatalf("Unexpected logger output: %q. Expected %q", cl.out, expectedLogOut)
  2566. }
  2567. }
  2568. func TestServerRemoteAddr(t *testing.T) {
  2569. t.Parallel()
  2570. s := &Server{
  2571. Handler: func(ctx *RequestCtx) {
  2572. h := &ctx.Request.Header
  2573. ctx.Success("text/html", []byte(fmt.Sprintf("requestURI=%s, remoteAddr=%s, remoteIP=%s",
  2574. h.RequestURI(), ctx.RemoteAddr(), ctx.RemoteIP())))
  2575. },
  2576. }
  2577. rw := &readWriter{}
  2578. rw.r.WriteString("GET /foo1 HTTP/1.1\r\nHost: google.com\r\n\r\n")
  2579. rwx := &readWriterRemoteAddr{
  2580. rw: rw,
  2581. addr: &net.TCPAddr{
  2582. IP: []byte{1, 2, 3, 4},
  2583. Port: 8765,
  2584. },
  2585. }
  2586. if err := s.ServeConn(rwx); err != nil {
  2587. t.Fatalf("Unexpected error from serveConn: %s", err)
  2588. }
  2589. br := bufio.NewReader(&rw.w)
  2590. verifyResponse(t, br, 200, "text/html", "requestURI=/foo1, remoteAddr=1.2.3.4:8765, remoteIP=1.2.3.4")
  2591. }
  2592. func TestServerCustomRemoteAddr(t *testing.T) {
  2593. t.Parallel()
  2594. customRemoteAddrHandler := func(h RequestHandler) RequestHandler {
  2595. return func(ctx *RequestCtx) {
  2596. ctx.SetRemoteAddr(&net.TCPAddr{
  2597. IP: []byte{1, 2, 3, 5},
  2598. Port: 0,
  2599. })
  2600. h(ctx)
  2601. }
  2602. }
  2603. s := &Server{
  2604. Handler: customRemoteAddrHandler(func(ctx *RequestCtx) {
  2605. h := &ctx.Request.Header
  2606. ctx.Success("text/html", []byte(fmt.Sprintf("requestURI=%s, remoteAddr=%s, remoteIP=%s",
  2607. h.RequestURI(), ctx.RemoteAddr(), ctx.RemoteIP())))
  2608. }),
  2609. }
  2610. rw := &readWriter{}
  2611. rw.r.WriteString("GET /foo1 HTTP/1.1\r\nHost: google.com\r\n\r\n")
  2612. rwx := &readWriterRemoteAddr{
  2613. rw: rw,
  2614. addr: &net.TCPAddr{
  2615. IP: []byte{1, 2, 3, 4},
  2616. Port: 8765,
  2617. },
  2618. }
  2619. if err := s.ServeConn(rwx); err != nil {
  2620. t.Fatalf("Unexpected error from serveConn: %s", err)
  2621. }
  2622. br := bufio.NewReader(&rw.w)
  2623. verifyResponse(t, br, 200, "text/html", "requestURI=/foo1, remoteAddr=1.2.3.5:0, remoteIP=1.2.3.5")
  2624. }
  2625. type readWriterRemoteAddr struct {
  2626. net.Conn
  2627. rw io.ReadWriteCloser
  2628. addr net.Addr
  2629. }
  2630. func (rw *readWriterRemoteAddr) Close() error {
  2631. return rw.rw.Close()
  2632. }
  2633. func (rw *readWriterRemoteAddr) Read(b []byte) (int, error) {
  2634. return rw.rw.Read(b)
  2635. }
  2636. func (rw *readWriterRemoteAddr) Write(b []byte) (int, error) {
  2637. return rw.rw.Write(b)
  2638. }
  2639. func (rw *readWriterRemoteAddr) RemoteAddr() net.Addr {
  2640. return rw.addr
  2641. }
  2642. func (rw *readWriterRemoteAddr) LocalAddr() net.Addr {
  2643. return rw.addr
  2644. }
  2645. func TestServerConnError(t *testing.T) {
  2646. t.Parallel()
  2647. s := &Server{
  2648. Handler: func(ctx *RequestCtx) {
  2649. ctx.Error("foobar", 423)
  2650. },
  2651. }
  2652. rw := &readWriter{}
  2653. rw.r.WriteString("GET /foo/bar?baz HTTP/1.1\r\nHost: google.com\r\n\r\n")
  2654. if err := s.ServeConn(rw); err != nil {
  2655. t.Fatalf("Unexpected error from serveConn: %s", err)
  2656. }
  2657. br := bufio.NewReader(&rw.w)
  2658. var resp Response
  2659. if err := resp.Read(br); err != nil {
  2660. t.Fatalf("Unexpected error when reading response: %s", err)
  2661. }
  2662. if resp.Header.StatusCode() != 423 {
  2663. t.Fatalf("Unexpected status code %d. Expected %d", resp.Header.StatusCode(), 423)
  2664. }
  2665. if resp.Header.ContentLength() != 6 {
  2666. t.Fatalf("Unexpected Content-Length %d. Expected %d", resp.Header.ContentLength(), 6)
  2667. }
  2668. if !bytes.Equal(resp.Header.Peek(HeaderContentType), defaultContentType) {
  2669. t.Fatalf("Unexpected Content-Type %q. Expected %q", resp.Header.Peek(HeaderContentType), defaultContentType)
  2670. }
  2671. if !bytes.Equal(resp.Body(), []byte("foobar")) {
  2672. t.Fatalf("Unexpected body %q. Expected %q", resp.Body(), "foobar")
  2673. }
  2674. }
  2675. func TestServeConnSingleRequest(t *testing.T) {
  2676. t.Parallel()
  2677. s := &Server{
  2678. Handler: func(ctx *RequestCtx) {
  2679. h := &ctx.Request.Header
  2680. ctx.Success("aaa", []byte(fmt.Sprintf("requestURI=%s, host=%s", h.RequestURI(), h.Peek(HeaderHost))))
  2681. },
  2682. }
  2683. rw := &readWriter{}
  2684. rw.r.WriteString("GET /foo/bar?baz HTTP/1.1\r\nHost: google.com\r\n\r\n")
  2685. if err := s.ServeConn(rw); err != nil {
  2686. t.Fatalf("Unexpected error from serveConn: %s", err)
  2687. }
  2688. br := bufio.NewReader(&rw.w)
  2689. verifyResponse(t, br, 200, "aaa", "requestURI=/foo/bar?baz, host=google.com")
  2690. }
  2691. func TestServeConnMultiRequests(t *testing.T) {
  2692. t.Parallel()
  2693. s := &Server{
  2694. Handler: func(ctx *RequestCtx) {
  2695. h := &ctx.Request.Header
  2696. ctx.Success("aaa", []byte(fmt.Sprintf("requestURI=%s, host=%s", h.RequestURI(), h.Peek(HeaderHost))))
  2697. },
  2698. }
  2699. rw := &readWriter{}
  2700. rw.r.WriteString("GET /foo/bar?baz HTTP/1.1\r\nHost: google.com\r\n\r\nGET /abc HTTP/1.1\r\nHost: foobar.com\r\n\r\n")
  2701. if err := s.ServeConn(rw); err != nil {
  2702. t.Fatalf("Unexpected error from serveConn: %s", err)
  2703. }
  2704. br := bufio.NewReader(&rw.w)
  2705. verifyResponse(t, br, 200, "aaa", "requestURI=/foo/bar?baz, host=google.com")
  2706. verifyResponse(t, br, 200, "aaa", "requestURI=/abc, host=foobar.com")
  2707. }
  2708. func TestShutdown(t *testing.T) {
  2709. t.Parallel()
  2710. ln := fasthttputil.NewInmemoryListener()
  2711. s := &Server{
  2712. Handler: func(ctx *RequestCtx) {
  2713. time.Sleep(time.Millisecond * 500)
  2714. ctx.Success("aaa/bbb", []byte("real response"))
  2715. },
  2716. }
  2717. serveCh := make(chan struct{})
  2718. go func() {
  2719. if err := s.Serve(ln); err != nil {
  2720. t.Errorf("unexepcted error: %s", err)
  2721. }
  2722. _, err := ln.Dial()
  2723. if err == nil {
  2724. t.Error("server is still listening")
  2725. }
  2726. serveCh <- struct{}{}
  2727. }()
  2728. clientCh := make(chan struct{})
  2729. go func() {
  2730. conn, err := ln.Dial()
  2731. if err != nil {
  2732. t.Errorf("unexepcted error: %s", err)
  2733. }
  2734. if _, err = conn.Write([]byte("GET / HTTP/1.1\r\nHost: google.com\r\n\r\n")); err != nil {
  2735. t.Errorf("unexpected error: %s", err)
  2736. }
  2737. br := bufio.NewReader(conn)
  2738. resp := verifyResponse(t, br, StatusOK, "aaa/bbb", "real response")
  2739. verifyResponseHeaderConnection(t, &resp.Header, "")
  2740. clientCh <- struct{}{}
  2741. }()
  2742. time.Sleep(time.Millisecond * 100)
  2743. shutdownCh := make(chan struct{})
  2744. go func() {
  2745. if err := s.Shutdown(); err != nil {
  2746. t.Errorf("unexepcted error: %s", err)
  2747. }
  2748. shutdownCh <- struct{}{}
  2749. }()
  2750. done := 0
  2751. for {
  2752. select {
  2753. case <-time.After(time.Second * 2):
  2754. t.Fatal("shutdown took too long")
  2755. case <-serveCh:
  2756. done++
  2757. case <-clientCh:
  2758. done++
  2759. case <-shutdownCh:
  2760. done++
  2761. }
  2762. if done == 3 {
  2763. return
  2764. }
  2765. }
  2766. }
  2767. func TestCloseOnShutdown(t *testing.T) {
  2768. t.Parallel()
  2769. ln := fasthttputil.NewInmemoryListener()
  2770. s := &Server{
  2771. Handler: func(ctx *RequestCtx) {
  2772. time.Sleep(time.Millisecond * 500)
  2773. ctx.Success("aaa/bbb", []byte("real response"))
  2774. },
  2775. CloseOnShutdown: true,
  2776. }
  2777. serveCh := make(chan struct{})
  2778. go func() {
  2779. if err := s.Serve(ln); err != nil {
  2780. t.Errorf("unexepcted error: %s", err)
  2781. }
  2782. _, err := ln.Dial()
  2783. if err == nil {
  2784. t.Error("server is still listening")
  2785. }
  2786. serveCh <- struct{}{}
  2787. }()
  2788. clientCh := make(chan struct{})
  2789. go func() {
  2790. conn, err := ln.Dial()
  2791. if err != nil {
  2792. t.Errorf("unexepcted error: %s", err)
  2793. }
  2794. if _, err = conn.Write([]byte("GET / HTTP/1.1\r\nHost: google.com\r\n\r\n")); err != nil {
  2795. t.Errorf("unexpected error: %s", err)
  2796. }
  2797. br := bufio.NewReader(conn)
  2798. resp := verifyResponse(t, br, StatusOK, "aaa/bbb", "real response")
  2799. verifyResponseHeaderConnection(t, &resp.Header, "close")
  2800. clientCh <- struct{}{}
  2801. }()
  2802. time.Sleep(time.Millisecond * 100)
  2803. shutdownCh := make(chan struct{})
  2804. go func() {
  2805. if err := s.Shutdown(); err != nil {
  2806. t.Errorf("unexepcted error: %s", err)
  2807. }
  2808. shutdownCh <- struct{}{}
  2809. }()
  2810. done := 0
  2811. for {
  2812. select {
  2813. case <-time.After(time.Second):
  2814. t.Fatal("shutdown took too long")
  2815. case <-serveCh:
  2816. done++
  2817. case <-clientCh:
  2818. done++
  2819. case <-shutdownCh:
  2820. done++
  2821. }
  2822. if done == 3 {
  2823. return
  2824. }
  2825. }
  2826. }
  2827. func TestShutdownReuse(t *testing.T) {
  2828. t.Parallel()
  2829. ln := fasthttputil.NewInmemoryListener()
  2830. s := &Server{
  2831. Handler: func(ctx *RequestCtx) {
  2832. ctx.Success("aaa/bbb", []byte("real response"))
  2833. },
  2834. ReadTimeout: time.Millisecond * 100,
  2835. Logger: &testLogger{}, // Ignore log output.
  2836. }
  2837. go func() {
  2838. if err := s.Serve(ln); err != nil {
  2839. t.Errorf("unexepcted error: %s", err)
  2840. }
  2841. }()
  2842. conn, err := ln.Dial()
  2843. if err != nil {
  2844. t.Fatalf("unexepcted error: %s", err)
  2845. }
  2846. if _, err = conn.Write([]byte("GET / HTTP/1.1\r\nHost: google.com\r\n\r\n")); err != nil {
  2847. t.Fatalf("unexpected error: %s", err)
  2848. }
  2849. br := bufio.NewReader(conn)
  2850. verifyResponse(t, br, StatusOK, "aaa/bbb", "real response")
  2851. if err := s.Shutdown(); err != nil {
  2852. t.Fatalf("unexepcted error: %s", err)
  2853. }
  2854. ln = fasthttputil.NewInmemoryListener()
  2855. go func() {
  2856. if err := s.Serve(ln); err != nil {
  2857. t.Errorf("unexepcted error: %s", err)
  2858. }
  2859. }()
  2860. conn, err = ln.Dial()
  2861. if err != nil {
  2862. t.Fatalf("unexepcted error: %s", err)
  2863. }
  2864. if _, err = conn.Write([]byte("GET / HTTP/1.1\r\nHost: google.com\r\n\r\n")); err != nil {
  2865. t.Fatalf("unexpected error: %s", err)
  2866. }
  2867. br = bufio.NewReader(conn)
  2868. verifyResponse(t, br, StatusOK, "aaa/bbb", "real response")
  2869. if err := s.Shutdown(); err != nil {
  2870. t.Fatalf("unexepcted error: %s", err)
  2871. }
  2872. }
  2873. func TestShutdownDone(t *testing.T) {
  2874. t.Parallel()
  2875. ln := fasthttputil.NewInmemoryListener()
  2876. s := &Server{
  2877. Handler: func(ctx *RequestCtx) {
  2878. <-ctx.Done()
  2879. ctx.Success("aaa/bbb", []byte("real response"))
  2880. },
  2881. }
  2882. go func() {
  2883. if err := s.Serve(ln); err != nil {
  2884. t.Errorf("unexepcted error: %s", err)
  2885. }
  2886. }()
  2887. conn, err := ln.Dial()
  2888. if err != nil {
  2889. t.Fatalf("unexepcted error: %s", err)
  2890. }
  2891. if _, err = conn.Write([]byte("GET / HTTP/1.1\r\nHost: google.com\r\n\r\n")); err != nil {
  2892. t.Fatalf("unexpected error: %s", err)
  2893. }
  2894. go func() {
  2895. // Shutdown won't return if the connection doesn't close,
  2896. // which doesn't happen until we read the response.
  2897. if err := s.Shutdown(); err != nil {
  2898. t.Errorf("unexepcted error: %s", err)
  2899. }
  2900. }()
  2901. // We can only reach this point and get a valid response
  2902. // if reading from ctx.Done() returned.
  2903. br := bufio.NewReader(conn)
  2904. verifyResponse(t, br, StatusOK, "aaa/bbb", "real response")
  2905. }
  2906. func TestShutdownErr(t *testing.T) {
  2907. t.Parallel()
  2908. ln := fasthttputil.NewInmemoryListener()
  2909. s := &Server{
  2910. Handler: func(ctx *RequestCtx) {
  2911. // This will panic, but I was not able to intercept with recover()
  2912. c, cancel := context.WithCancel(ctx)
  2913. defer cancel()
  2914. <-c.Done()
  2915. ctx.Success("aaa/bbb", []byte("real response"))
  2916. },
  2917. }
  2918. go func() {
  2919. if err := s.Serve(ln); err != nil {
  2920. t.Errorf("unexepcted error: %s", err)
  2921. }
  2922. }()
  2923. conn, err := ln.Dial()
  2924. if err != nil {
  2925. t.Fatalf("unexepcted error: %s", err)
  2926. }
  2927. if _, err = conn.Write([]byte("GET / HTTP/1.1\r\nHost: google.com\r\n\r\n")); err != nil {
  2928. t.Fatalf("unexpected error: %s", err)
  2929. }
  2930. go func() {
  2931. // Shutdown won't return if the connection doesn't close,
  2932. // which doesn't happen until we read the response.
  2933. if err := s.Shutdown(); err != nil {
  2934. t.Errorf("unexepcted error: %s", err)
  2935. }
  2936. }()
  2937. // We can only reach this point and get a valid response
  2938. // if reading from ctx.Done() returned.
  2939. br := bufio.NewReader(conn)
  2940. verifyResponse(t, br, StatusOK, "aaa/bbb", "real response")
  2941. }
  2942. func TestShutdownCloseIdleConns(t *testing.T) {
  2943. t.Parallel()
  2944. ln := fasthttputil.NewInmemoryListener()
  2945. s := &Server{
  2946. Handler: func(ctx *RequestCtx) {
  2947. ctx.Success("aaa/bbb", []byte("real response"))
  2948. },
  2949. }
  2950. go func() {
  2951. if err := s.Serve(ln); err != nil {
  2952. t.Errorf("unexepcted error: %s", err)
  2953. }
  2954. }()
  2955. conn, err := ln.Dial()
  2956. if err != nil {
  2957. t.Fatalf("unexepcted error: %s", err)
  2958. }
  2959. if _, err = conn.Write([]byte("GET / HTTP/1.1\r\nHost: google.com\r\n\r\n")); err != nil {
  2960. t.Errorf("unexpected error: %s", err)
  2961. }
  2962. br := bufio.NewReader(conn)
  2963. verifyResponse(t, br, StatusOK, "aaa/bbb", "real response")
  2964. shutdownErr := make(chan error)
  2965. go func() {
  2966. shutdownErr <- s.Shutdown()
  2967. }()
  2968. timer := time.NewTimer(time.Second)
  2969. select {
  2970. case <-timer.C:
  2971. t.Fatal("idle connections not closed on shutdown")
  2972. case err = <-shutdownErr:
  2973. if err != nil {
  2974. t.Errorf("unexepcted error: %s", err)
  2975. }
  2976. }
  2977. }
  2978. func TestMultipleServe(t *testing.T) {
  2979. t.Parallel()
  2980. s := &Server{
  2981. Handler: func(ctx *RequestCtx) {
  2982. ctx.Success("aaa/bbb", []byte("real response"))
  2983. },
  2984. }
  2985. ln1 := fasthttputil.NewInmemoryListener()
  2986. ln2 := fasthttputil.NewInmemoryListener()
  2987. go func() {
  2988. if err := s.Serve(ln1); err != nil {
  2989. t.Errorf("unexepcted error: %s", err)
  2990. }
  2991. }()
  2992. go func() {
  2993. if err := s.Serve(ln2); err != nil {
  2994. t.Errorf("unexepcted error: %s", err)
  2995. }
  2996. }()
  2997. conn, err := ln1.Dial()
  2998. if err != nil {
  2999. t.Fatalf("unexepcted error: %s", err)
  3000. }
  3001. if _, err = conn.Write([]byte("GET / HTTP/1.1\r\nHost: google.com\r\n\r\n")); err != nil {
  3002. t.Fatalf("unexpected error: %s", err)
  3003. }
  3004. br := bufio.NewReader(conn)
  3005. verifyResponse(t, br, StatusOK, "aaa/bbb", "real response")
  3006. conn, err = ln2.Dial()
  3007. if err != nil {
  3008. t.Fatalf("unexepcted error: %s", err)
  3009. }
  3010. if _, err = conn.Write([]byte("GET / HTTP/1.1\r\nHost: google.com\r\n\r\n")); err != nil {
  3011. t.Fatalf("unexpected error: %s", err)
  3012. }
  3013. br = bufio.NewReader(conn)
  3014. verifyResponse(t, br, StatusOK, "aaa/bbb", "real response")
  3015. }
  3016. func TestMaxBodySizePerRequest(t *testing.T) {
  3017. t.Parallel()
  3018. s := &Server{
  3019. Handler: func(ctx *RequestCtx) {
  3020. // do nothing :)
  3021. },
  3022. HeaderReceived: func(header *RequestHeader) RequestConfig {
  3023. return RequestConfig{
  3024. MaxRequestBodySize: 5 << 10,
  3025. }
  3026. },
  3027. ReadTimeout: time.Second * 5,
  3028. WriteTimeout: time.Second * 5,
  3029. MaxRequestBodySize: 1 << 20,
  3030. }
  3031. rw := &readWriter{}
  3032. rw.r.WriteString(fmt.Sprintf("POST /foo2 HTTP/1.1\r\nHost: aaa.com\r\nContent-Length: %d\r\nContent-Type: aa\r\n\r\n%s", (5<<10)+1, strings.Repeat("a", (5<<10)+1)))
  3033. if err := s.ServeConn(rw); err != ErrBodyTooLarge {
  3034. t.Fatalf("Unexpected error from serveConn: %s", err)
  3035. }
  3036. }
  3037. func TestStreamRequestBody(t *testing.T) {
  3038. t.Parallel()
  3039. part1 := strings.Repeat("1", 1<<15)
  3040. part2 := strings.Repeat("2", 1<<16)
  3041. contentLength := len(part1) + len(part2)
  3042. next := make(chan struct{})
  3043. s := &Server{
  3044. Handler: func(ctx *RequestCtx) {
  3045. checkReader(t, ctx.RequestBodyStream(), part1)
  3046. close(next)
  3047. checkReader(t, ctx.RequestBodyStream(), part2)
  3048. },
  3049. StreamRequestBody: true,
  3050. }
  3051. pipe := fasthttputil.NewPipeConns()
  3052. cc, sc := pipe.Conn1(), pipe.Conn2()
  3053. //write headers and part1 body
  3054. if _, err := cc.Write([]byte(fmt.Sprintf("POST /foo2 HTTP/1.1\r\nHost: aaa.com\r\nContent-Length: %d\r\nContent-Type: aa\r\n\r\n", contentLength))); err != nil {
  3055. t.Fatal(err)
  3056. }
  3057. if _, err := cc.Write([]byte(part1)); err != nil {
  3058. t.Fatal(err)
  3059. }
  3060. ch := make(chan error)
  3061. go func() {
  3062. ch <- s.ServeConn(sc)
  3063. }()
  3064. select {
  3065. case <-next:
  3066. case <-time.After(500 * time.Millisecond):
  3067. t.Fatal("part1 timeout")
  3068. }
  3069. if _, err := cc.Write([]byte(part2)); err != nil {
  3070. t.Fatal(err)
  3071. }
  3072. if err := sc.Close(); err != nil {
  3073. t.Fatal(err)
  3074. }
  3075. select {
  3076. case err := <-ch:
  3077. if err == nil || err.Error() != "connection closed" { // fasthttputil.errConnectionClosed is private so do a string match.
  3078. t.Fatalf("Unexpected error from serveConn: %s", err)
  3079. }
  3080. case <-time.After(500 * time.Millisecond):
  3081. t.Fatal("part2 timeout")
  3082. }
  3083. }
  3084. func TestStreamRequestBodyExceedMaxSize(t *testing.T) {
  3085. t.Parallel()
  3086. part1 := strings.Repeat("1", 1<<18)
  3087. part2 := strings.Repeat("2", 1<<20-1<<18)
  3088. contentLength := len(part1) + len(part2)
  3089. next := make(chan struct{})
  3090. s := &Server{
  3091. Handler: func(ctx *RequestCtx) {
  3092. checkReader(t, ctx.RequestBodyStream(), part1)
  3093. close(next)
  3094. checkReader(t, ctx.RequestBodyStream(), part2)
  3095. },
  3096. DisableKeepalive: true,
  3097. StreamRequestBody: true,
  3098. MaxRequestBodySize: 1,
  3099. }
  3100. pipe := fasthttputil.NewPipeConns()
  3101. cc, sc := pipe.Conn1(), pipe.Conn2()
  3102. //write headers and part1 body
  3103. if _, err := cc.Write([]byte(fmt.Sprintf("POST /foo2 HTTP/1.1\r\nHost: aaa.com\r\nContent-Length: %d\r\nContent-Type: aa\r\n\r\n%s", contentLength, part1))); err != nil {
  3104. t.Error(err)
  3105. }
  3106. ch := make(chan error)
  3107. go func() {
  3108. ch <- s.ServeConn(sc)
  3109. }()
  3110. select {
  3111. case <-next:
  3112. case <-time.After(500 * time.Millisecond):
  3113. t.Fatal("part1 timeout")
  3114. }
  3115. if _, err := cc.Write([]byte(part2)); err != nil {
  3116. t.Error(err)
  3117. }
  3118. select {
  3119. case err := <-ch:
  3120. if err != nil {
  3121. t.Error(err)
  3122. }
  3123. case <-time.After(500 * time.Millisecond):
  3124. t.Fatal("part2 timeout")
  3125. }
  3126. }
  3127. func TestStreamBodyRequestContentLength(t *testing.T) {
  3128. t.Parallel()
  3129. content := strings.Repeat("1", 1<<15) // 32K
  3130. contentLength := len(content)
  3131. s := &Server{
  3132. Handler: func(ctx *RequestCtx) {
  3133. realContentLength := ctx.Request.Header.ContentLength()
  3134. if realContentLength != contentLength {
  3135. t.Fatal("incorrect content length")
  3136. }
  3137. },
  3138. MaxRequestBodySize: 1 * 1024 * 1024, // 1M
  3139. StreamRequestBody: true,
  3140. }
  3141. pipe := fasthttputil.NewPipeConns()
  3142. cc, sc := pipe.Conn1(), pipe.Conn2()
  3143. if _, err := cc.Write([]byte(fmt.Sprintf("POST /foo2 HTTP/1.1\r\nHost: aaa.com\r\nContent-Length: %d\r\nContent-Type: aa\r\n\r\n%s", contentLength, content))); err != nil {
  3144. t.Fatal(err)
  3145. }
  3146. ch := make(chan error)
  3147. go func() {
  3148. ch <- s.ServeConn(sc)
  3149. }()
  3150. if err := sc.Close(); err != nil {
  3151. t.Fatal(err)
  3152. }
  3153. select {
  3154. case err := <-ch:
  3155. if err == nil || err.Error() != "connection closed" { // fasthttputil.errConnectionClosed is private so do a string match.
  3156. t.Fatalf("Unexpected error from serveConn: %s", err)
  3157. }
  3158. case <-time.After(time.Second):
  3159. t.Fatal("test timeout")
  3160. }
  3161. }
  3162. func checkReader(t *testing.T, r io.Reader, expected string) {
  3163. b := make([]byte, len(expected))
  3164. if _, err := io.ReadFull(r, b); err != nil {
  3165. t.Fatalf("Unexpected error from reader: %s", err)
  3166. }
  3167. if string(b) != expected {
  3168. t.Fatal("incorrect request body")
  3169. }
  3170. }
  3171. func TestMaxReadTimeoutPerRequest(t *testing.T) {
  3172. t.Parallel()
  3173. headers := []byte(fmt.Sprintf("POST /foo2 HTTP/1.1\r\nHost: aaa.com\r\nContent-Length: %d\r\nContent-Type: aa\r\n\r\n", 5*1024))
  3174. s := &Server{
  3175. Handler: func(ctx *RequestCtx) {
  3176. t.Error("shouldn't reach handler")
  3177. },
  3178. HeaderReceived: func(header *RequestHeader) RequestConfig {
  3179. return RequestConfig{
  3180. ReadTimeout: time.Millisecond,
  3181. }
  3182. },
  3183. ReadBufferSize: len(headers),
  3184. ReadTimeout: time.Second * 5,
  3185. WriteTimeout: time.Second * 5,
  3186. }
  3187. pipe := fasthttputil.NewPipeConns()
  3188. cc, sc := pipe.Conn1(), pipe.Conn2()
  3189. go func() {
  3190. //write headers
  3191. _, err := cc.Write(headers)
  3192. if err != nil {
  3193. t.Error(err)
  3194. }
  3195. //write body
  3196. for i := 0; i < 5*1024; i++ {
  3197. time.Sleep(time.Millisecond)
  3198. cc.Write([]byte{'a'}) //nolint:errcheck
  3199. }
  3200. }()
  3201. ch := make(chan error)
  3202. go func() {
  3203. ch <- s.ServeConn(sc)
  3204. }()
  3205. select {
  3206. case err := <-ch:
  3207. if err == nil || err != nil && !strings.EqualFold(err.Error(), "timeout") {
  3208. t.Fatalf("Unexpected error from serveConn: %s", err)
  3209. }
  3210. case <-time.After(time.Second):
  3211. t.Fatal("test timeout")
  3212. }
  3213. }
  3214. func TestMaxWriteTimeoutPerRequest(t *testing.T) {
  3215. t.Parallel()
  3216. headers := []byte("GET /foo2 HTTP/1.1\r\nHost: aaa.com\r\nContent-Type: aa\r\n\r\n")
  3217. s := &Server{
  3218. Handler: func(ctx *RequestCtx) {
  3219. ctx.SetBodyStreamWriter(func(w *bufio.Writer) {
  3220. var buf [192]byte
  3221. for {
  3222. w.Write(buf[:]) //nolint:errcheck
  3223. }
  3224. })
  3225. },
  3226. HeaderReceived: func(header *RequestHeader) RequestConfig {
  3227. return RequestConfig{
  3228. WriteTimeout: time.Millisecond,
  3229. }
  3230. },
  3231. ReadBufferSize: 192,
  3232. ReadTimeout: time.Second * 5,
  3233. WriteTimeout: time.Second * 5,
  3234. }
  3235. pipe := fasthttputil.NewPipeConns()
  3236. cc, sc := pipe.Conn1(), pipe.Conn2()
  3237. var resp Response
  3238. go func() {
  3239. //write headers
  3240. _, err := cc.Write(headers)
  3241. if err != nil {
  3242. t.Error(err)
  3243. }
  3244. br := bufio.NewReaderSize(cc, 192)
  3245. err = resp.Header.Read(br)
  3246. if err != nil {
  3247. t.Error(err)
  3248. }
  3249. var chunk [192]byte
  3250. for {
  3251. time.Sleep(time.Millisecond)
  3252. br.Read(chunk[:]) //nolint:errcheck
  3253. }
  3254. }()
  3255. ch := make(chan error)
  3256. go func() {
  3257. ch <- s.ServeConn(sc)
  3258. }()
  3259. select {
  3260. case err := <-ch:
  3261. if err == nil || err != nil && !strings.EqualFold(err.Error(), "timeout") {
  3262. t.Fatalf("Unexpected error from serveConn: %s", err)
  3263. }
  3264. case <-time.After(time.Second):
  3265. t.Fatal("test timeout")
  3266. }
  3267. }
  3268. func TestIncompleteBodyReturnsUnexpectedEOF(t *testing.T) {
  3269. t.Parallel()
  3270. rw := &readWriter{}
  3271. rw.r.WriteString("POST /foo HTTP/1.1\r\nHost: google.com\r\nContent-Length: 5\r\n\r\n123")
  3272. s := &Server{
  3273. Handler: func(ctx *RequestCtx) {},
  3274. }
  3275. ch := make(chan error)
  3276. go func() {
  3277. ch <- s.ServeConn(rw)
  3278. }()
  3279. if err := <-ch; err == nil || err.Error() != "unexpected EOF" {
  3280. t.Fatal(err)
  3281. }
  3282. }
  3283. func TestServerChunkedResponse(t *testing.T) {
  3284. t.Parallel()
  3285. trailer := map[string]string{
  3286. "AtEnd1": "1111",
  3287. "AtEnd2": "2222",
  3288. "AtEnd3": "3333",
  3289. }
  3290. h := func(ctx *RequestCtx) {
  3291. ctx.Response.Header.DisableNormalizing()
  3292. ctx.Response.Header.Set("Transfer-Encoding", "chunked")
  3293. for k := range trailer {
  3294. err := ctx.Response.Header.AddTrailer(k)
  3295. if err != nil {
  3296. t.Errorf("unexpected error: %s", err)
  3297. }
  3298. }
  3299. ctx.Response.SetBodyStreamWriter(func(w *bufio.Writer) {
  3300. for i := 0; i < 3; i++ {
  3301. fmt.Fprintf(w, "message %d", i)
  3302. if err := w.Flush(); err != nil {
  3303. t.Errorf("unexpected error: %s", err)
  3304. }
  3305. time.Sleep(time.Second)
  3306. }
  3307. })
  3308. for k, v := range trailer {
  3309. ctx.Response.Header.Set(k, v)
  3310. }
  3311. }
  3312. s := &Server{
  3313. Handler: h,
  3314. }
  3315. rw := &readWriter{}
  3316. rw.r.WriteString("GET / HTTP/1.1\r\nHost: test.com\r\n\r\n")
  3317. if err := s.ServeConn(rw); err != nil {
  3318. t.Fatalf("Unexpected error from serveConn: %s", err)
  3319. }
  3320. br := bufio.NewReader(&rw.w)
  3321. var resp Response
  3322. if err := resp.Read(br); err != nil {
  3323. t.Fatalf("Unexpected error when reading response: %s", err)
  3324. }
  3325. if resp.Header.ContentLength() != -1 {
  3326. t.Fatalf("Unexpected Content-Length %d. Expected %d", resp.Header.ContentLength(), -1)
  3327. }
  3328. if !bytes.Equal(resp.Body(), []byte("message 0"+"message 1"+"message 2")) {
  3329. t.Fatalf("Unexpected body %q. Expected %q", resp.Body(), "foobar")
  3330. }
  3331. for k, v := range trailer {
  3332. h := resp.Header.Peek(k)
  3333. if !bytes.Equal(resp.Header.Peek(k), []byte(v)) {
  3334. t.Fatalf("Unexpected trailer %s. Expected %s. Got %q", k, v, h)
  3335. }
  3336. }
  3337. }
  3338. func verifyResponse(t *testing.T, r *bufio.Reader, expectedStatusCode int, expectedContentType, expectedBody string) *Response {
  3339. var resp Response
  3340. if err := resp.Read(r); err != nil {
  3341. t.Fatalf("Unexpected error when parsing response: %s", err)
  3342. }
  3343. if !bytes.Equal(resp.Body(), []byte(expectedBody)) {
  3344. t.Fatalf("Unexpected body %q. Expected %q", resp.Body(), []byte(expectedBody))
  3345. }
  3346. verifyResponseHeader(t, &resp.Header, expectedStatusCode, len(resp.Body()), expectedContentType)
  3347. return &resp
  3348. }
  3349. type readWriter struct {
  3350. net.Conn
  3351. r bytes.Buffer
  3352. w bytes.Buffer
  3353. }
  3354. func (rw *readWriter) Close() error {
  3355. return nil
  3356. }
  3357. func (rw *readWriter) Read(b []byte) (int, error) {
  3358. return rw.r.Read(b)
  3359. }
  3360. func (rw *readWriter) Write(b []byte) (int, error) {
  3361. return rw.w.Write(b)
  3362. }
  3363. func (rw *readWriter) RemoteAddr() net.Addr {
  3364. return zeroTCPAddr
  3365. }
  3366. func (rw *readWriter) LocalAddr() net.Addr {
  3367. return zeroTCPAddr
  3368. }
  3369. func (rw *readWriter) SetDeadline(t time.Time) error {
  3370. return nil
  3371. }
  3372. func (rw *readWriter) SetReadDeadline(t time.Time) error {
  3373. return nil
  3374. }
  3375. func (rw *readWriter) SetWriteDeadline(t time.Time) error {
  3376. return nil
  3377. }
  3378. type testLogger struct {
  3379. lock sync.Mutex
  3380. out string
  3381. }
  3382. func (cl *testLogger) Printf(format string, args ...interface{}) {
  3383. cl.lock.Lock()
  3384. cl.out += fmt.Sprintf(format, args...)[6:] + "\n"
  3385. cl.lock.Unlock()
  3386. }