server.go 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951
  1. package fasthttp
  2. import (
  3. "bufio"
  4. "context"
  5. "crypto/tls"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "log"
  10. "mime/multipart"
  11. "net"
  12. "os"
  13. "strings"
  14. "sync"
  15. "sync/atomic"
  16. "time"
  17. )
  18. var errNoCertOrKeyProvided = errors.New("cert or key has not provided")
  19. // Deprecated: ErrAlreadyServing is never returned from Serve. See issue #633.
  20. var ErrAlreadyServing = errors.New("Server is already serving connections")
  21. // ServeConn serves HTTP requests from the given connection
  22. // using the given handler.
  23. //
  24. // ServeConn returns nil if all requests from the c are successfully served.
  25. // It returns non-nil error otherwise.
  26. //
  27. // Connection c must immediately propagate all the data passed to Write()
  28. // to the client. Otherwise requests' processing may hang.
  29. //
  30. // ServeConn closes c before returning.
  31. func ServeConn(c net.Conn, handler RequestHandler) error {
  32. v := serverPool.Get()
  33. if v == nil {
  34. v = &Server{}
  35. }
  36. s := v.(*Server)
  37. s.Handler = handler
  38. err := s.ServeConn(c)
  39. s.Handler = nil
  40. serverPool.Put(v)
  41. return err
  42. }
  43. var serverPool sync.Pool
  44. // Serve serves incoming connections from the given listener
  45. // using the given handler.
  46. //
  47. // Serve blocks until the given listener returns permanent error.
  48. func Serve(ln net.Listener, handler RequestHandler) error {
  49. s := &Server{
  50. Handler: handler,
  51. }
  52. return s.Serve(ln)
  53. }
  54. // ServeTLS serves HTTPS requests from the given net.Listener
  55. // using the given handler.
  56. //
  57. // certFile and keyFile are paths to TLS certificate and key files.
  58. func ServeTLS(ln net.Listener, certFile, keyFile string, handler RequestHandler) error {
  59. s := &Server{
  60. Handler: handler,
  61. }
  62. return s.ServeTLS(ln, certFile, keyFile)
  63. }
  64. // ServeTLSEmbed serves HTTPS requests from the given net.Listener
  65. // using the given handler.
  66. //
  67. // certData and keyData must contain valid TLS certificate and key data.
  68. func ServeTLSEmbed(ln net.Listener, certData, keyData []byte, handler RequestHandler) error {
  69. s := &Server{
  70. Handler: handler,
  71. }
  72. return s.ServeTLSEmbed(ln, certData, keyData)
  73. }
  74. // ListenAndServe serves HTTP requests from the given TCP addr
  75. // using the given handler.
  76. func ListenAndServe(addr string, handler RequestHandler) error {
  77. s := &Server{
  78. Handler: handler,
  79. }
  80. return s.ListenAndServe(addr)
  81. }
  82. // ListenAndServeUNIX serves HTTP requests from the given UNIX addr
  83. // using the given handler.
  84. //
  85. // The function deletes existing file at addr before starting serving.
  86. //
  87. // The server sets the given file mode for the UNIX addr.
  88. func ListenAndServeUNIX(addr string, mode os.FileMode, handler RequestHandler) error {
  89. s := &Server{
  90. Handler: handler,
  91. }
  92. return s.ListenAndServeUNIX(addr, mode)
  93. }
  94. // ListenAndServeTLS serves HTTPS requests from the given TCP addr
  95. // using the given handler.
  96. //
  97. // certFile and keyFile are paths to TLS certificate and key files.
  98. func ListenAndServeTLS(addr, certFile, keyFile string, handler RequestHandler) error {
  99. s := &Server{
  100. Handler: handler,
  101. }
  102. return s.ListenAndServeTLS(addr, certFile, keyFile)
  103. }
  104. // ListenAndServeTLSEmbed serves HTTPS requests from the given TCP addr
  105. // using the given handler.
  106. //
  107. // certData and keyData must contain valid TLS certificate and key data.
  108. func ListenAndServeTLSEmbed(addr string, certData, keyData []byte, handler RequestHandler) error {
  109. s := &Server{
  110. Handler: handler,
  111. }
  112. return s.ListenAndServeTLSEmbed(addr, certData, keyData)
  113. }
  114. // RequestHandler must process incoming requests.
  115. //
  116. // RequestHandler must call ctx.TimeoutError() before returning
  117. // if it keeps references to ctx and/or its members after the return.
  118. // Consider wrapping RequestHandler into TimeoutHandler if response time
  119. // must be limited.
  120. type RequestHandler func(ctx *RequestCtx)
  121. // ServeHandler must process tls.Config.NextProto negotiated requests.
  122. type ServeHandler func(c net.Conn) error
  123. // Server implements HTTP server.
  124. //
  125. // Default Server settings should satisfy the majority of Server users.
  126. // Adjust Server settings only if you really understand the consequences.
  127. //
  128. // It is forbidden copying Server instances. Create new Server instances
  129. // instead.
  130. //
  131. // It is safe to call Server methods from concurrently running goroutines.
  132. type Server struct {
  133. noCopy noCopy
  134. // Handler for processing incoming requests.
  135. //
  136. // Take into account that no `panic` recovery is done by `fasthttp` (thus any `panic` will take down the entire server).
  137. // Instead the user should use `recover` to handle these situations.
  138. Handler RequestHandler
  139. // ErrorHandler for returning a response in case of an error while receiving or parsing the request.
  140. //
  141. // The following is a non-exhaustive list of errors that can be expected as argument:
  142. // * io.EOF
  143. // * io.ErrUnexpectedEOF
  144. // * ErrGetOnly
  145. // * ErrSmallBuffer
  146. // * ErrBodyTooLarge
  147. // * ErrBrokenChunks
  148. ErrorHandler func(ctx *RequestCtx, err error)
  149. // HeaderReceived is called after receiving the header
  150. //
  151. // non zero RequestConfig field values will overwrite the default configs
  152. HeaderReceived func(header *RequestHeader) RequestConfig
  153. // ContinueHandler is called after receiving the Expect 100 Continue Header
  154. //
  155. // https://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html#sec8.2.3
  156. // https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.1.1
  157. // Using ContinueHandler a server can make decisioning on whether or not
  158. // to read a potentially large request body based on the headers
  159. //
  160. // The default is to automatically read request bodies of Expect 100 Continue requests
  161. // like they are normal requests
  162. ContinueHandler func(header *RequestHeader) bool
  163. // Server name for sending in response headers.
  164. //
  165. // Default server name is used if left blank.
  166. Name string
  167. // The maximum number of concurrent connections the server may serve.
  168. //
  169. // DefaultConcurrency is used if not set.
  170. //
  171. // Concurrency only works if you either call Serve once, or only ServeConn multiple times.
  172. // It works with ListenAndServe as well.
  173. Concurrency int
  174. // Per-connection buffer size for requests' reading.
  175. // This also limits the maximum header size.
  176. //
  177. // Increase this buffer if your clients send multi-KB RequestURIs
  178. // and/or multi-KB headers (for example, BIG cookies).
  179. //
  180. // Default buffer size is used if not set.
  181. ReadBufferSize int
  182. // Per-connection buffer size for responses' writing.
  183. //
  184. // Default buffer size is used if not set.
  185. WriteBufferSize int
  186. // ReadTimeout is the amount of time allowed to read
  187. // the full request including body. The connection's read
  188. // deadline is reset when the connection opens, or for
  189. // keep-alive connections after the first byte has been read.
  190. //
  191. // By default request read timeout is unlimited.
  192. ReadTimeout time.Duration
  193. // WriteTimeout is the maximum duration before timing out
  194. // writes of the response. It is reset after the request handler
  195. // has returned.
  196. //
  197. // By default response write timeout is unlimited.
  198. WriteTimeout time.Duration
  199. // IdleTimeout is the maximum amount of time to wait for the
  200. // next request when keep-alive is enabled. If IdleTimeout
  201. // is zero, the value of ReadTimeout is used.
  202. IdleTimeout time.Duration
  203. // Maximum number of concurrent client connections allowed per IP.
  204. //
  205. // By default unlimited number of concurrent connections
  206. // may be established to the server from a single IP address.
  207. MaxConnsPerIP int
  208. // Maximum number of requests served per connection.
  209. //
  210. // The server closes connection after the last request.
  211. // 'Connection: close' header is added to the last response.
  212. //
  213. // By default unlimited number of requests may be served per connection.
  214. MaxRequestsPerConn int
  215. // MaxKeepaliveDuration is a no-op and only left here for backwards compatibility.
  216. // Deprecated: Use IdleTimeout instead.
  217. MaxKeepaliveDuration time.Duration
  218. // MaxIdleWorkerDuration is the maximum idle time of a single worker in the underlying
  219. // worker pool of the Server. Idle workers beyond this time will be cleared.
  220. MaxIdleWorkerDuration time.Duration
  221. // Period between tcp keep-alive messages.
  222. //
  223. // TCP keep-alive period is determined by operation system by default.
  224. TCPKeepalivePeriod time.Duration
  225. // Maximum request body size.
  226. //
  227. // The server rejects requests with bodies exceeding this limit.
  228. //
  229. // Request body size is limited by DefaultMaxRequestBodySize by default.
  230. MaxRequestBodySize int
  231. // Whether to disable keep-alive connections.
  232. //
  233. // The server will close all the incoming connections after sending
  234. // the first response to client if this option is set to true.
  235. //
  236. // By default keep-alive connections are enabled.
  237. DisableKeepalive bool
  238. // Whether to enable tcp keep-alive connections.
  239. //
  240. // Whether the operating system should send tcp keep-alive messages on the tcp connection.
  241. //
  242. // By default tcp keep-alive connections are disabled.
  243. TCPKeepalive bool
  244. // Aggressively reduces memory usage at the cost of higher CPU usage
  245. // if set to true.
  246. //
  247. // Try enabling this option only if the server consumes too much memory
  248. // serving mostly idle keep-alive connections. This may reduce memory
  249. // usage by more than 50%.
  250. //
  251. // Aggressive memory usage reduction is disabled by default.
  252. ReduceMemoryUsage bool
  253. // Rejects all non-GET requests if set to true.
  254. //
  255. // This option is useful as anti-DoS protection for servers
  256. // accepting only GET requests and HEAD requests. The request size is limited
  257. // by ReadBufferSize if GetOnly is set.
  258. //
  259. // Server accepts all the requests by default.
  260. GetOnly bool
  261. // Will not pre parse Multipart Form data if set to true.
  262. //
  263. // This option is useful for servers that desire to treat
  264. // multipart form data as a binary blob, or choose when to parse the data.
  265. //
  266. // Server pre parses multipart form data by default.
  267. DisablePreParseMultipartForm bool
  268. // Logs all errors, including the most frequent
  269. // 'connection reset by peer', 'broken pipe' and 'connection timeout'
  270. // errors. Such errors are common in production serving real-world
  271. // clients.
  272. //
  273. // By default the most frequent errors such as
  274. // 'connection reset by peer', 'broken pipe' and 'connection timeout'
  275. // are suppressed in order to limit output log traffic.
  276. LogAllErrors bool
  277. // Will not log potentially sensitive content in error logs
  278. //
  279. // This option is useful for servers that handle sensitive data
  280. // in the request/response.
  281. //
  282. // Server logs all full errors by default.
  283. SecureErrorLogMessage bool
  284. // Header names are passed as-is without normalization
  285. // if this option is set.
  286. //
  287. // Disabled header names' normalization may be useful only for proxying
  288. // incoming requests to other servers expecting case-sensitive
  289. // header names. See https://github.com/valyala/fasthttp/issues/57
  290. // for details.
  291. //
  292. // By default request and response header names are normalized, i.e.
  293. // The first letter and the first letters following dashes
  294. // are uppercased, while all the other letters are lowercased.
  295. // Examples:
  296. //
  297. // * HOST -> Host
  298. // * content-type -> Content-Type
  299. // * cONTENT-lenGTH -> Content-Length
  300. DisableHeaderNamesNormalizing bool
  301. // SleepWhenConcurrencyLimitsExceeded is a duration to be slept of if
  302. // the concurrency limit in exceeded (default [when is 0]: don't sleep
  303. // and accept new connections immediately).
  304. SleepWhenConcurrencyLimitsExceeded time.Duration
  305. // NoDefaultServerHeader, when set to true, causes the default Server header
  306. // to be excluded from the Response.
  307. //
  308. // The default Server header value is the value of the Name field or an
  309. // internal default value in its absence. With this option set to true,
  310. // the only time a Server header will be sent is if a non-zero length
  311. // value is explicitly provided during a request.
  312. NoDefaultServerHeader bool
  313. // NoDefaultDate, when set to true, causes the default Date
  314. // header to be excluded from the Response.
  315. //
  316. // The default Date header value is the current date value. When
  317. // set to true, the Date will not be present.
  318. NoDefaultDate bool
  319. // NoDefaultContentType, when set to true, causes the default Content-Type
  320. // header to be excluded from the Response.
  321. //
  322. // The default Content-Type header value is the internal default value. When
  323. // set to true, the Content-Type will not be present.
  324. NoDefaultContentType bool
  325. // KeepHijackedConns is an opt-in disable of connection
  326. // close by fasthttp after connections' HijackHandler returns.
  327. // This allows to save goroutines, e.g. when fasthttp used to upgrade
  328. // http connections to WS and connection goes to another handler,
  329. // which will close it when needed.
  330. KeepHijackedConns bool
  331. // CloseOnShutdown when true adds a `Connection: close` header when the server is shutting down.
  332. CloseOnShutdown bool
  333. // StreamRequestBody enables request body streaming,
  334. // and calls the handler sooner when given body is
  335. // larger than the current limit.
  336. StreamRequestBody bool
  337. // ConnState specifies an optional callback function that is
  338. // called when a client connection changes state. See the
  339. // ConnState type and associated constants for details.
  340. ConnState func(net.Conn, ConnState)
  341. // Logger, which is used by RequestCtx.Logger().
  342. //
  343. // By default standard logger from log package is used.
  344. Logger Logger
  345. // TLSConfig optionally provides a TLS configuration for use
  346. // by ServeTLS, ServeTLSEmbed, ListenAndServeTLS, ListenAndServeTLSEmbed,
  347. // AppendCert, AppendCertEmbed and NextProto.
  348. //
  349. // Note that this value is cloned by ServeTLS, ServeTLSEmbed, ListenAndServeTLS
  350. // and ListenAndServeTLSEmbed, so it's not possible to modify the configuration
  351. // with methods like tls.Config.SetSessionTicketKeys.
  352. // To use SetSessionTicketKeys, use Server.Serve with a TLS Listener
  353. // instead.
  354. TLSConfig *tls.Config
  355. // FormValueFunc, which is used by RequestCtx.FormValue and support for customizing
  356. // the behaviour of the RequestCtx.FormValue function.
  357. //
  358. // NetHttpFormValueFunc gives a FormValueFunc func implementation that is consistent with net/http.
  359. FormValueFunc FormValueFunc
  360. nextProtos map[string]ServeHandler
  361. concurrency uint32
  362. concurrencyCh chan struct{}
  363. perIPConnCounter perIPConnCounter
  364. ctxPool sync.Pool
  365. readerPool sync.Pool
  366. writerPool sync.Pool
  367. hijackConnPool sync.Pool
  368. // We need to know our listeners and idle connections so we can close them in Shutdown().
  369. ln []net.Listener
  370. idleConns map[net.Conn]time.Time
  371. idleConnsMu sync.Mutex
  372. mu sync.Mutex
  373. open int32
  374. stop int32
  375. done chan struct{}
  376. }
  377. // TimeoutHandler creates RequestHandler, which returns StatusRequestTimeout
  378. // error with the given msg to the client if h didn't return during
  379. // the given duration.
  380. //
  381. // The returned handler may return StatusTooManyRequests error with the given
  382. // msg to the client if there are more than Server.Concurrency concurrent
  383. // handlers h are running at the moment.
  384. func TimeoutHandler(h RequestHandler, timeout time.Duration, msg string) RequestHandler {
  385. return TimeoutWithCodeHandler(h, timeout, msg, StatusRequestTimeout)
  386. }
  387. // TimeoutWithCodeHandler creates RequestHandler, which returns an error with
  388. // the given msg and status code to the client if h didn't return during
  389. // the given duration.
  390. //
  391. // The returned handler may return StatusTooManyRequests error with the given
  392. // msg to the client if there are more than Server.Concurrency concurrent
  393. // handlers h are running at the moment.
  394. func TimeoutWithCodeHandler(h RequestHandler, timeout time.Duration, msg string, statusCode int) RequestHandler {
  395. if timeout <= 0 {
  396. return h
  397. }
  398. return func(ctx *RequestCtx) {
  399. concurrencyCh := ctx.s.concurrencyCh
  400. select {
  401. case concurrencyCh <- struct{}{}:
  402. default:
  403. ctx.Error(msg, StatusTooManyRequests)
  404. return
  405. }
  406. ch := ctx.timeoutCh
  407. if ch == nil {
  408. ch = make(chan struct{}, 1)
  409. ctx.timeoutCh = ch
  410. }
  411. go func() {
  412. h(ctx)
  413. ch <- struct{}{}
  414. <-concurrencyCh
  415. }()
  416. ctx.timeoutTimer = initTimer(ctx.timeoutTimer, timeout)
  417. select {
  418. case <-ch:
  419. case <-ctx.timeoutTimer.C:
  420. ctx.TimeoutErrorWithCode(msg, statusCode)
  421. }
  422. stopTimer(ctx.timeoutTimer)
  423. }
  424. }
  425. // RequestConfig configure the per request deadline and body limits
  426. type RequestConfig struct {
  427. // ReadTimeout is the maximum duration for reading the entire
  428. // request body.
  429. // a zero value means that default values will be honored
  430. ReadTimeout time.Duration
  431. // WriteTimeout is the maximum duration before timing out
  432. // writes of the response.
  433. // a zero value means that default values will be honored
  434. WriteTimeout time.Duration
  435. // Maximum request body size.
  436. // a zero value means that default values will be honored
  437. MaxRequestBodySize int
  438. }
  439. // CompressHandler returns RequestHandler that transparently compresses
  440. // response body generated by h if the request contains 'gzip' or 'deflate'
  441. // 'Accept-Encoding' header.
  442. func CompressHandler(h RequestHandler) RequestHandler {
  443. return CompressHandlerLevel(h, CompressDefaultCompression)
  444. }
  445. // CompressHandlerLevel returns RequestHandler that transparently compresses
  446. // response body generated by h if the request contains a 'gzip' or 'deflate'
  447. // 'Accept-Encoding' header.
  448. //
  449. // Level is the desired compression level:
  450. //
  451. // - CompressNoCompression
  452. // - CompressBestSpeed
  453. // - CompressBestCompression
  454. // - CompressDefaultCompression
  455. // - CompressHuffmanOnly
  456. func CompressHandlerLevel(h RequestHandler, level int) RequestHandler {
  457. return func(ctx *RequestCtx) {
  458. h(ctx)
  459. if ctx.Request.Header.HasAcceptEncodingBytes(strGzip) {
  460. ctx.Response.gzipBody(level) //nolint:errcheck
  461. } else if ctx.Request.Header.HasAcceptEncodingBytes(strDeflate) {
  462. ctx.Response.deflateBody(level) //nolint:errcheck
  463. }
  464. }
  465. }
  466. // CompressHandlerBrotliLevel returns RequestHandler that transparently compresses
  467. // response body generated by h if the request contains a 'br', 'gzip' or 'deflate'
  468. // 'Accept-Encoding' header.
  469. //
  470. // brotliLevel is the desired compression level for brotli.
  471. //
  472. // - CompressBrotliNoCompression
  473. // - CompressBrotliBestSpeed
  474. // - CompressBrotliBestCompression
  475. // - CompressBrotliDefaultCompression
  476. //
  477. // otherLevel is the desired compression level for gzip and deflate.
  478. //
  479. // - CompressNoCompression
  480. // - CompressBestSpeed
  481. // - CompressBestCompression
  482. // - CompressDefaultCompression
  483. // - CompressHuffmanOnly
  484. func CompressHandlerBrotliLevel(h RequestHandler, brotliLevel, otherLevel int) RequestHandler {
  485. return func(ctx *RequestCtx) {
  486. h(ctx)
  487. switch {
  488. case ctx.Request.Header.HasAcceptEncodingBytes(strBr):
  489. ctx.Response.brotliBody(brotliLevel) //nolint:errcheck
  490. case ctx.Request.Header.HasAcceptEncodingBytes(strGzip):
  491. ctx.Response.gzipBody(otherLevel) //nolint:errcheck
  492. case ctx.Request.Header.HasAcceptEncodingBytes(strDeflate):
  493. ctx.Response.deflateBody(otherLevel) //nolint:errcheck
  494. }
  495. }
  496. }
  497. // RequestCtx contains incoming request and manages outgoing response.
  498. //
  499. // It is forbidden copying RequestCtx instances.
  500. //
  501. // RequestHandler should avoid holding references to incoming RequestCtx and/or
  502. // its members after the return.
  503. // If holding RequestCtx references after the return is unavoidable
  504. // (for instance, ctx is passed to a separate goroutine and ctx lifetime cannot
  505. // be controlled), then the RequestHandler MUST call ctx.TimeoutError()
  506. // before return.
  507. //
  508. // It is unsafe modifying/reading RequestCtx instance from concurrently
  509. // running goroutines. The only exception is TimeoutError*, which may be called
  510. // while other goroutines accessing RequestCtx.
  511. type RequestCtx struct {
  512. noCopy noCopy
  513. // Incoming request.
  514. //
  515. // Copying Request by value is forbidden. Use pointer to Request instead.
  516. Request Request
  517. // Outgoing response.
  518. //
  519. // Copying Response by value is forbidden. Use pointer to Response instead.
  520. Response Response
  521. userValues userData
  522. connID uint64
  523. connRequestNum uint64
  524. connTime time.Time
  525. remoteAddr net.Addr
  526. time time.Time
  527. logger ctxLogger
  528. s *Server
  529. c net.Conn
  530. fbr firstByteReader
  531. timeoutResponse *Response
  532. timeoutCh chan struct{}
  533. timeoutTimer *time.Timer
  534. hijackHandler HijackHandler
  535. hijackNoResponse bool
  536. formValueFunc FormValueFunc
  537. }
  538. // HijackHandler must process the hijacked connection c.
  539. //
  540. // If KeepHijackedConns is disabled, which is by default,
  541. // the connection c is automatically closed after returning from HijackHandler.
  542. //
  543. // The connection c must not be used after returning from the handler, if KeepHijackedConns is disabled.
  544. //
  545. // When KeepHijackedConns enabled, fasthttp will not Close() the connection,
  546. // you must do it when you need it. You must not use c in any way after calling Close().
  547. type HijackHandler func(c net.Conn)
  548. // Hijack registers the given handler for connection hijacking.
  549. //
  550. // The handler is called after returning from RequestHandler
  551. // and sending http response. The current connection is passed
  552. // to the handler. The connection is automatically closed after
  553. // returning from the handler.
  554. //
  555. // The server skips calling the handler in the following cases:
  556. //
  557. // - 'Connection: close' header exists in either request or response.
  558. // - Unexpected error during response writing to the connection.
  559. //
  560. // The server stops processing requests from hijacked connections.
  561. //
  562. // Server limits such as Concurrency, ReadTimeout, WriteTimeout, etc.
  563. // aren't applied to hijacked connections.
  564. //
  565. // The handler must not retain references to ctx members.
  566. //
  567. // Arbitrary 'Connection: Upgrade' protocols may be implemented
  568. // with HijackHandler. For instance,
  569. //
  570. // - WebSocket ( https://en.wikipedia.org/wiki/WebSocket )
  571. // - HTTP/2.0 ( https://en.wikipedia.org/wiki/HTTP/2 )
  572. func (ctx *RequestCtx) Hijack(handler HijackHandler) {
  573. ctx.hijackHandler = handler
  574. }
  575. // HijackSetNoResponse changes the behavior of hijacking a request.
  576. // If HijackSetNoResponse is called with false fasthttp will send a response
  577. // to the client before calling the HijackHandler (default). If HijackSetNoResponse
  578. // is called with true no response is send back before calling the
  579. // HijackHandler supplied in the Hijack function.
  580. func (ctx *RequestCtx) HijackSetNoResponse(noResponse bool) {
  581. ctx.hijackNoResponse = noResponse
  582. }
  583. // Hijacked returns true after Hijack is called.
  584. func (ctx *RequestCtx) Hijacked() bool {
  585. return ctx.hijackHandler != nil
  586. }
  587. // SetUserValue stores the given value (arbitrary object)
  588. // under the given key in ctx.
  589. //
  590. // The value stored in ctx may be obtained by UserValue*.
  591. //
  592. // This functionality may be useful for passing arbitrary values between
  593. // functions involved in request processing.
  594. //
  595. // All the values are removed from ctx after returning from the top
  596. // RequestHandler. Additionally, Close method is called on each value
  597. // implementing io.Closer before removing the value from ctx.
  598. func (ctx *RequestCtx) SetUserValue(key interface{}, value interface{}) {
  599. ctx.userValues.Set(key, value)
  600. }
  601. // SetUserValueBytes stores the given value (arbitrary object)
  602. // under the given key in ctx.
  603. //
  604. // The value stored in ctx may be obtained by UserValue*.
  605. //
  606. // This functionality may be useful for passing arbitrary values between
  607. // functions involved in request processing.
  608. //
  609. // All the values stored in ctx are deleted after returning from RequestHandler.
  610. func (ctx *RequestCtx) SetUserValueBytes(key []byte, value interface{}) {
  611. ctx.userValues.SetBytes(key, value)
  612. }
  613. // UserValue returns the value stored via SetUserValue* under the given key.
  614. func (ctx *RequestCtx) UserValue(key interface{}) interface{} {
  615. return ctx.userValues.Get(key)
  616. }
  617. // UserValueBytes returns the value stored via SetUserValue*
  618. // under the given key.
  619. func (ctx *RequestCtx) UserValueBytes(key []byte) interface{} {
  620. return ctx.userValues.GetBytes(key)
  621. }
  622. // VisitUserValues calls visitor for each existing userValue with a key that is a string or []byte.
  623. //
  624. // visitor must not retain references to key and value after returning.
  625. // Make key and/or value copies if you need storing them after returning.
  626. func (ctx *RequestCtx) VisitUserValues(visitor func([]byte, interface{})) {
  627. for i, n := 0, len(ctx.userValues); i < n; i++ {
  628. kv := &ctx.userValues[i]
  629. if _, ok := kv.key.(string); ok {
  630. visitor(s2b(kv.key.(string)), kv.value)
  631. }
  632. }
  633. }
  634. // VisitUserValuesAll calls visitor for each existing userValue.
  635. //
  636. // visitor must not retain references to key and value after returning.
  637. // Make key and/or value copies if you need storing them after returning.
  638. func (ctx *RequestCtx) VisitUserValuesAll(visitor func(interface{}, interface{})) {
  639. for i, n := 0, len(ctx.userValues); i < n; i++ {
  640. kv := &ctx.userValues[i]
  641. visitor(kv.key, kv.value)
  642. }
  643. }
  644. // ResetUserValues allows to reset user values from Request Context
  645. func (ctx *RequestCtx) ResetUserValues() {
  646. ctx.userValues.Reset()
  647. }
  648. // RemoveUserValue removes the given key and the value under it in ctx.
  649. func (ctx *RequestCtx) RemoveUserValue(key interface{}) {
  650. ctx.userValues.Remove(key)
  651. }
  652. // RemoveUserValueBytes removes the given key and the value under it in ctx.
  653. func (ctx *RequestCtx) RemoveUserValueBytes(key []byte) {
  654. ctx.userValues.RemoveBytes(key)
  655. }
  656. type connTLSer interface {
  657. Handshake() error
  658. ConnectionState() tls.ConnectionState
  659. }
  660. // IsTLS returns true if the underlying connection is tls.Conn.
  661. //
  662. // tls.Conn is an encrypted connection (aka SSL, HTTPS).
  663. func (ctx *RequestCtx) IsTLS() bool {
  664. // cast to (connTLSer) instead of (*tls.Conn), since it catches
  665. // cases with overridden tls.Conn such as:
  666. //
  667. // type customConn struct {
  668. // *tls.Conn
  669. //
  670. // // other custom fields here
  671. // }
  672. // perIPConn wraps the net.Conn in the Conn field
  673. if pic, ok := ctx.c.(*perIPConn); ok {
  674. _, ok := pic.Conn.(connTLSer)
  675. return ok
  676. }
  677. _, ok := ctx.c.(connTLSer)
  678. return ok
  679. }
  680. // TLSConnectionState returns TLS connection state.
  681. //
  682. // The function returns nil if the underlying connection isn't tls.Conn.
  683. //
  684. // The returned state may be used for verifying TLS version, client certificates,
  685. // etc.
  686. func (ctx *RequestCtx) TLSConnectionState() *tls.ConnectionState {
  687. tlsConn, ok := ctx.c.(connTLSer)
  688. if !ok {
  689. return nil
  690. }
  691. state := tlsConn.ConnectionState()
  692. return &state
  693. }
  694. // Conn returns a reference to the underlying net.Conn.
  695. //
  696. // WARNING: Only use this method if you know what you are doing!
  697. //
  698. // Reading from or writing to the returned connection will end badly!
  699. func (ctx *RequestCtx) Conn() net.Conn {
  700. return ctx.c
  701. }
  702. func (ctx *RequestCtx) reset() {
  703. ctx.userValues.Reset()
  704. ctx.Request.Reset()
  705. ctx.Response.Reset()
  706. ctx.fbr.reset()
  707. ctx.connID = 0
  708. ctx.connRequestNum = 0
  709. ctx.connTime = zeroTime
  710. ctx.remoteAddr = nil
  711. ctx.time = zeroTime
  712. ctx.c = nil
  713. // Don't reset ctx.s!
  714. // We have a pool per server so the next time this ctx is used it
  715. // will be assigned the same value again.
  716. // ctx might still be in use for context.Done() and context.Err()
  717. // which are safe to use as they only use ctx.s and no other value.
  718. if ctx.timeoutResponse != nil {
  719. ctx.timeoutResponse.Reset()
  720. }
  721. if ctx.timeoutTimer != nil {
  722. stopTimer(ctx.timeoutTimer)
  723. }
  724. ctx.hijackHandler = nil
  725. ctx.hijackNoResponse = false
  726. }
  727. type firstByteReader struct {
  728. c net.Conn
  729. ch byte
  730. byteRead bool
  731. }
  732. func (r *firstByteReader) reset() {
  733. r.c = nil
  734. r.ch = 0
  735. r.byteRead = false
  736. }
  737. func (r *firstByteReader) Read(b []byte) (int, error) {
  738. if len(b) == 0 {
  739. return 0, nil
  740. }
  741. nn := 0
  742. if !r.byteRead {
  743. b[0] = r.ch
  744. b = b[1:]
  745. r.byteRead = true
  746. nn = 1
  747. }
  748. n, err := r.c.Read(b)
  749. return n + nn, err
  750. }
  751. // Logger is used for logging formatted messages.
  752. type Logger interface {
  753. // Printf must have the same semantics as log.Printf.
  754. Printf(format string, args ...interface{})
  755. }
  756. var ctxLoggerLock sync.Mutex
  757. type ctxLogger struct {
  758. ctx *RequestCtx
  759. logger Logger
  760. }
  761. func (cl *ctxLogger) Printf(format string, args ...interface{}) {
  762. msg := fmt.Sprintf(format, args...)
  763. ctxLoggerLock.Lock()
  764. cl.logger.Printf("%.3f %s - %s", time.Since(cl.ctx.ConnTime()).Seconds(), cl.ctx.String(), msg)
  765. ctxLoggerLock.Unlock()
  766. }
  767. var zeroTCPAddr = &net.TCPAddr{
  768. IP: net.IPv4zero,
  769. }
  770. // String returns unique string representation of the ctx.
  771. //
  772. // The returned value may be useful for logging.
  773. func (ctx *RequestCtx) String() string {
  774. return fmt.Sprintf("#%016X - %s<->%s - %s %s", ctx.ID(), ctx.LocalAddr(), ctx.RemoteAddr(), ctx.Request.Header.Method(), ctx.URI().FullURI())
  775. }
  776. // ID returns unique ID of the request.
  777. func (ctx *RequestCtx) ID() uint64 {
  778. return (ctx.connID << 32) | ctx.connRequestNum
  779. }
  780. // ConnID returns unique connection ID.
  781. //
  782. // This ID may be used to match distinct requests to the same incoming
  783. // connection.
  784. func (ctx *RequestCtx) ConnID() uint64 {
  785. return ctx.connID
  786. }
  787. // Time returns RequestHandler call time.
  788. func (ctx *RequestCtx) Time() time.Time {
  789. return ctx.time
  790. }
  791. // ConnTime returns the time the server started serving the connection
  792. // the current request came from.
  793. func (ctx *RequestCtx) ConnTime() time.Time {
  794. return ctx.connTime
  795. }
  796. // ConnRequestNum returns request sequence number
  797. // for the current connection.
  798. //
  799. // Sequence starts with 1.
  800. func (ctx *RequestCtx) ConnRequestNum() uint64 {
  801. return ctx.connRequestNum
  802. }
  803. // SetConnectionClose sets 'Connection: close' response header and closes
  804. // connection after the RequestHandler returns.
  805. func (ctx *RequestCtx) SetConnectionClose() {
  806. ctx.Response.SetConnectionClose()
  807. }
  808. // SetStatusCode sets response status code.
  809. func (ctx *RequestCtx) SetStatusCode(statusCode int) {
  810. ctx.Response.SetStatusCode(statusCode)
  811. }
  812. // SetContentType sets response Content-Type.
  813. func (ctx *RequestCtx) SetContentType(contentType string) {
  814. ctx.Response.Header.SetContentType(contentType)
  815. }
  816. // SetContentTypeBytes sets response Content-Type.
  817. //
  818. // It is safe modifying contentType buffer after function return.
  819. func (ctx *RequestCtx) SetContentTypeBytes(contentType []byte) {
  820. ctx.Response.Header.SetContentTypeBytes(contentType)
  821. }
  822. // RequestURI returns RequestURI.
  823. //
  824. // The returned bytes are valid until your request handler returns.
  825. func (ctx *RequestCtx) RequestURI() []byte {
  826. return ctx.Request.Header.RequestURI()
  827. }
  828. // URI returns requested uri.
  829. //
  830. // This uri is valid until your request handler returns.
  831. func (ctx *RequestCtx) URI() *URI {
  832. return ctx.Request.URI()
  833. }
  834. // Referer returns request referer.
  835. //
  836. // The returned bytes are valid until your request handler returns.
  837. func (ctx *RequestCtx) Referer() []byte {
  838. return ctx.Request.Header.Referer()
  839. }
  840. // UserAgent returns User-Agent header value from the request.
  841. //
  842. // The returned bytes are valid until your request handler returns.
  843. func (ctx *RequestCtx) UserAgent() []byte {
  844. return ctx.Request.Header.UserAgent()
  845. }
  846. // Path returns requested path.
  847. //
  848. // The returned bytes are valid until your request handler returns.
  849. func (ctx *RequestCtx) Path() []byte {
  850. return ctx.URI().Path()
  851. }
  852. // Host returns requested host.
  853. //
  854. // The returned bytes are valid until your request handler returns.
  855. func (ctx *RequestCtx) Host() []byte {
  856. return ctx.URI().Host()
  857. }
  858. // QueryArgs returns query arguments from RequestURI.
  859. //
  860. // It doesn't return POST'ed arguments - use PostArgs() for this.
  861. //
  862. // See also PostArgs, FormValue and FormFile.
  863. //
  864. // These args are valid until your request handler returns.
  865. func (ctx *RequestCtx) QueryArgs() *Args {
  866. return ctx.URI().QueryArgs()
  867. }
  868. // PostArgs returns POST arguments.
  869. //
  870. // It doesn't return query arguments from RequestURI - use QueryArgs for this.
  871. //
  872. // See also QueryArgs, FormValue and FormFile.
  873. //
  874. // These args are valid until your request handler returns.
  875. func (ctx *RequestCtx) PostArgs() *Args {
  876. return ctx.Request.PostArgs()
  877. }
  878. // MultipartForm returns request's multipart form.
  879. //
  880. // Returns ErrNoMultipartForm if request's content-type
  881. // isn't 'multipart/form-data'.
  882. //
  883. // All uploaded temporary files are automatically deleted after
  884. // returning from RequestHandler. Either move or copy uploaded files
  885. // into new place if you want retaining them.
  886. //
  887. // Use SaveMultipartFile function for permanently saving uploaded file.
  888. //
  889. // The returned form is valid until your request handler returns.
  890. //
  891. // See also FormFile and FormValue.
  892. func (ctx *RequestCtx) MultipartForm() (*multipart.Form, error) {
  893. return ctx.Request.MultipartForm()
  894. }
  895. // FormFile returns uploaded file associated with the given multipart form key.
  896. //
  897. // The file is automatically deleted after returning from RequestHandler,
  898. // so either move or copy uploaded file into new place if you want retaining it.
  899. //
  900. // Use SaveMultipartFile function for permanently saving uploaded file.
  901. //
  902. // The returned file header is valid until your request handler returns.
  903. func (ctx *RequestCtx) FormFile(key string) (*multipart.FileHeader, error) {
  904. mf, err := ctx.MultipartForm()
  905. if err != nil {
  906. return nil, err
  907. }
  908. if mf.File == nil {
  909. return nil, err
  910. }
  911. fhh := mf.File[key]
  912. if fhh == nil {
  913. return nil, ErrMissingFile
  914. }
  915. return fhh[0], nil
  916. }
  917. // ErrMissingFile may be returned from FormFile when the is no uploaded file
  918. // associated with the given multipart form key.
  919. var ErrMissingFile = errors.New("there is no uploaded file associated with the given key")
  920. // SaveMultipartFile saves multipart file fh under the given filename path.
  921. func SaveMultipartFile(fh *multipart.FileHeader, path string) (err error) {
  922. var (
  923. f multipart.File
  924. ff *os.File
  925. )
  926. f, err = fh.Open()
  927. if err != nil {
  928. return
  929. }
  930. var ok bool
  931. if ff, ok = f.(*os.File); ok {
  932. // Windows can't rename files that are opened.
  933. if err = f.Close(); err != nil {
  934. return
  935. }
  936. // If renaming fails we try the normal copying method.
  937. // Renaming could fail if the files are on different devices.
  938. if os.Rename(ff.Name(), path) == nil {
  939. return nil
  940. }
  941. // Reopen f for the code below.
  942. if f, err = fh.Open(); err != nil {
  943. return
  944. }
  945. }
  946. defer func() {
  947. e := f.Close()
  948. if err == nil {
  949. err = e
  950. }
  951. }()
  952. if ff, err = os.Create(path); err != nil {
  953. return
  954. }
  955. defer func() {
  956. e := ff.Close()
  957. if err == nil {
  958. err = e
  959. }
  960. }()
  961. _, err = copyZeroAlloc(ff, f)
  962. return
  963. }
  964. // FormValue returns form value associated with the given key.
  965. //
  966. // The value is searched in the following places:
  967. //
  968. // - Query string.
  969. // - POST or PUT body.
  970. //
  971. // There are more fine-grained methods for obtaining form values:
  972. //
  973. // - QueryArgs for obtaining values from query string.
  974. // - PostArgs for obtaining values from POST or PUT body.
  975. // - MultipartForm for obtaining values from multipart form.
  976. // - FormFile for obtaining uploaded files.
  977. //
  978. // The returned value is valid until your request handler returns.
  979. func (ctx *RequestCtx) FormValue(key string) []byte {
  980. if ctx.formValueFunc != nil {
  981. return ctx.formValueFunc(ctx, key)
  982. }
  983. return defaultFormValue(ctx, key)
  984. }
  985. type FormValueFunc func(*RequestCtx, string) []byte
  986. var (
  987. defaultFormValue = func(ctx *RequestCtx, key string) []byte {
  988. v := ctx.QueryArgs().Peek(key)
  989. if len(v) > 0 {
  990. return v
  991. }
  992. v = ctx.PostArgs().Peek(key)
  993. if len(v) > 0 {
  994. return v
  995. }
  996. mf, err := ctx.MultipartForm()
  997. if err == nil && mf.Value != nil {
  998. vv := mf.Value[key]
  999. if len(vv) > 0 {
  1000. return []byte(vv[0])
  1001. }
  1002. }
  1003. return nil
  1004. }
  1005. // NetHttpFormValueFunc gives consistent behavior with net/http. POST and PUT body parameters take precedence over URL query string values.
  1006. NetHttpFormValueFunc = func(ctx *RequestCtx, key string) []byte {
  1007. v := ctx.PostArgs().Peek(key)
  1008. if len(v) > 0 {
  1009. return v
  1010. }
  1011. mf, err := ctx.MultipartForm()
  1012. if err == nil && mf.Value != nil {
  1013. vv := mf.Value[key]
  1014. if len(vv) > 0 {
  1015. return []byte(vv[0])
  1016. }
  1017. }
  1018. v = ctx.QueryArgs().Peek(key)
  1019. if len(v) > 0 {
  1020. return v
  1021. }
  1022. return nil
  1023. }
  1024. )
  1025. // IsGet returns true if request method is GET.
  1026. func (ctx *RequestCtx) IsGet() bool {
  1027. return ctx.Request.Header.IsGet()
  1028. }
  1029. // IsPost returns true if request method is POST.
  1030. func (ctx *RequestCtx) IsPost() bool {
  1031. return ctx.Request.Header.IsPost()
  1032. }
  1033. // IsPut returns true if request method is PUT.
  1034. func (ctx *RequestCtx) IsPut() bool {
  1035. return ctx.Request.Header.IsPut()
  1036. }
  1037. // IsDelete returns true if request method is DELETE.
  1038. func (ctx *RequestCtx) IsDelete() bool {
  1039. return ctx.Request.Header.IsDelete()
  1040. }
  1041. // IsConnect returns true if request method is CONNECT.
  1042. func (ctx *RequestCtx) IsConnect() bool {
  1043. return ctx.Request.Header.IsConnect()
  1044. }
  1045. // IsOptions returns true if request method is OPTIONS.
  1046. func (ctx *RequestCtx) IsOptions() bool {
  1047. return ctx.Request.Header.IsOptions()
  1048. }
  1049. // IsTrace returns true if request method is TRACE.
  1050. func (ctx *RequestCtx) IsTrace() bool {
  1051. return ctx.Request.Header.IsTrace()
  1052. }
  1053. // IsPatch returns true if request method is PATCH.
  1054. func (ctx *RequestCtx) IsPatch() bool {
  1055. return ctx.Request.Header.IsPatch()
  1056. }
  1057. // Method return request method.
  1058. //
  1059. // Returned value is valid until your request handler returns.
  1060. func (ctx *RequestCtx) Method() []byte {
  1061. return ctx.Request.Header.Method()
  1062. }
  1063. // IsHead returns true if request method is HEAD.
  1064. func (ctx *RequestCtx) IsHead() bool {
  1065. return ctx.Request.Header.IsHead()
  1066. }
  1067. // RemoteAddr returns client address for the given request.
  1068. //
  1069. // Always returns non-nil result.
  1070. func (ctx *RequestCtx) RemoteAddr() net.Addr {
  1071. if ctx.remoteAddr != nil {
  1072. return ctx.remoteAddr
  1073. }
  1074. if ctx.c == nil {
  1075. return zeroTCPAddr
  1076. }
  1077. addr := ctx.c.RemoteAddr()
  1078. if addr == nil {
  1079. return zeroTCPAddr
  1080. }
  1081. return addr
  1082. }
  1083. // SetRemoteAddr sets remote address to the given value.
  1084. //
  1085. // Set nil value to restore default behaviour for using
  1086. // connection remote address.
  1087. func (ctx *RequestCtx) SetRemoteAddr(remoteAddr net.Addr) {
  1088. ctx.remoteAddr = remoteAddr
  1089. }
  1090. // LocalAddr returns server address for the given request.
  1091. //
  1092. // Always returns non-nil result.
  1093. func (ctx *RequestCtx) LocalAddr() net.Addr {
  1094. if ctx.c == nil {
  1095. return zeroTCPAddr
  1096. }
  1097. addr := ctx.c.LocalAddr()
  1098. if addr == nil {
  1099. return zeroTCPAddr
  1100. }
  1101. return addr
  1102. }
  1103. // RemoteIP returns the client ip the request came from.
  1104. //
  1105. // Always returns non-nil result.
  1106. func (ctx *RequestCtx) RemoteIP() net.IP {
  1107. return addrToIP(ctx.RemoteAddr())
  1108. }
  1109. // LocalIP returns the server ip the request came to.
  1110. //
  1111. // Always returns non-nil result.
  1112. func (ctx *RequestCtx) LocalIP() net.IP {
  1113. return addrToIP(ctx.LocalAddr())
  1114. }
  1115. func addrToIP(addr net.Addr) net.IP {
  1116. x, ok := addr.(*net.TCPAddr)
  1117. if !ok {
  1118. return net.IPv4zero
  1119. }
  1120. return x.IP
  1121. }
  1122. // Error sets response status code to the given value and sets response body
  1123. // to the given message.
  1124. //
  1125. // Warning: this will reset the response headers and body already set!
  1126. func (ctx *RequestCtx) Error(msg string, statusCode int) {
  1127. ctx.Response.Reset()
  1128. ctx.SetStatusCode(statusCode)
  1129. ctx.SetContentTypeBytes(defaultContentType)
  1130. ctx.SetBodyString(msg)
  1131. }
  1132. // Success sets response Content-Type and body to the given values.
  1133. func (ctx *RequestCtx) Success(contentType string, body []byte) {
  1134. ctx.SetContentType(contentType)
  1135. ctx.SetBody(body)
  1136. }
  1137. // SuccessString sets response Content-Type and body to the given values.
  1138. func (ctx *RequestCtx) SuccessString(contentType, body string) {
  1139. ctx.SetContentType(contentType)
  1140. ctx.SetBodyString(body)
  1141. }
  1142. // Redirect sets 'Location: uri' response header and sets the given statusCode.
  1143. //
  1144. // statusCode must have one of the following values:
  1145. //
  1146. // - StatusMovedPermanently (301)
  1147. // - StatusFound (302)
  1148. // - StatusSeeOther (303)
  1149. // - StatusTemporaryRedirect (307)
  1150. // - StatusPermanentRedirect (308)
  1151. //
  1152. // All other statusCode values are replaced by StatusFound (302).
  1153. //
  1154. // The redirect uri may be either absolute or relative to the current
  1155. // request uri. Fasthttp will always send an absolute uri back to the client.
  1156. // To send a relative uri you can use the following code:
  1157. //
  1158. // strLocation = []byte("Location") // Put this with your top level var () declarations.
  1159. // ctx.Response.Header.SetCanonical(strLocation, "/relative?uri")
  1160. // ctx.Response.SetStatusCode(fasthttp.StatusMovedPermanently)
  1161. func (ctx *RequestCtx) Redirect(uri string, statusCode int) {
  1162. u := AcquireURI()
  1163. ctx.URI().CopyTo(u)
  1164. u.Update(uri)
  1165. ctx.redirect(u.FullURI(), statusCode)
  1166. ReleaseURI(u)
  1167. }
  1168. // RedirectBytes sets 'Location: uri' response header and sets
  1169. // the given statusCode.
  1170. //
  1171. // statusCode must have one of the following values:
  1172. //
  1173. // - StatusMovedPermanently (301)
  1174. // - StatusFound (302)
  1175. // - StatusSeeOther (303)
  1176. // - StatusTemporaryRedirect (307)
  1177. // - StatusPermanentRedirect (308)
  1178. //
  1179. // All other statusCode values are replaced by StatusFound (302).
  1180. //
  1181. // The redirect uri may be either absolute or relative to the current
  1182. // request uri. Fasthttp will always send an absolute uri back to the client.
  1183. // To send a relative uri you can use the following code:
  1184. //
  1185. // strLocation = []byte("Location") // Put this with your top level var () declarations.
  1186. // ctx.Response.Header.SetCanonical(strLocation, "/relative?uri")
  1187. // ctx.Response.SetStatusCode(fasthttp.StatusMovedPermanently)
  1188. func (ctx *RequestCtx) RedirectBytes(uri []byte, statusCode int) {
  1189. s := b2s(uri)
  1190. ctx.Redirect(s, statusCode)
  1191. }
  1192. func (ctx *RequestCtx) redirect(uri []byte, statusCode int) {
  1193. ctx.Response.Header.setNonSpecial(strLocation, uri)
  1194. statusCode = getRedirectStatusCode(statusCode)
  1195. ctx.Response.SetStatusCode(statusCode)
  1196. }
  1197. func getRedirectStatusCode(statusCode int) int {
  1198. if statusCode == StatusMovedPermanently || statusCode == StatusFound ||
  1199. statusCode == StatusSeeOther || statusCode == StatusTemporaryRedirect ||
  1200. statusCode == StatusPermanentRedirect {
  1201. return statusCode
  1202. }
  1203. return StatusFound
  1204. }
  1205. // SetBody sets response body to the given value.
  1206. //
  1207. // It is safe re-using body argument after the function returns.
  1208. func (ctx *RequestCtx) SetBody(body []byte) {
  1209. ctx.Response.SetBody(body)
  1210. }
  1211. // SetBodyString sets response body to the given value.
  1212. func (ctx *RequestCtx) SetBodyString(body string) {
  1213. ctx.Response.SetBodyString(body)
  1214. }
  1215. // ResetBody resets response body contents.
  1216. func (ctx *RequestCtx) ResetBody() {
  1217. ctx.Response.ResetBody()
  1218. }
  1219. // SendFile sends local file contents from the given path as response body.
  1220. //
  1221. // This is a shortcut to ServeFile(ctx, path).
  1222. //
  1223. // SendFile logs all the errors via ctx.Logger.
  1224. //
  1225. // See also ServeFile, FSHandler and FS.
  1226. //
  1227. // WARNING: do not pass any user supplied paths to this function!
  1228. // WARNING: if path is based on user input users will be able to request
  1229. // any file on your filesystem! Use fasthttp.FS with a sane Root instead.
  1230. func (ctx *RequestCtx) SendFile(path string) {
  1231. ServeFile(ctx, path)
  1232. }
  1233. // SendFileBytes sends local file contents from the given path as response body.
  1234. //
  1235. // This is a shortcut to ServeFileBytes(ctx, path).
  1236. //
  1237. // SendFileBytes logs all the errors via ctx.Logger.
  1238. //
  1239. // See also ServeFileBytes, FSHandler and FS.
  1240. //
  1241. // WARNING: do not pass any user supplied paths to this function!
  1242. // WARNING: if path is based on user input users will be able to request
  1243. // any file on your filesystem! Use fasthttp.FS with a sane Root instead.
  1244. func (ctx *RequestCtx) SendFileBytes(path []byte) {
  1245. ServeFileBytes(ctx, path)
  1246. }
  1247. // IfModifiedSince returns true if lastModified exceeds 'If-Modified-Since'
  1248. // value from the request header.
  1249. //
  1250. // The function returns true also 'If-Modified-Since' request header is missing.
  1251. func (ctx *RequestCtx) IfModifiedSince(lastModified time.Time) bool {
  1252. ifModStr := ctx.Request.Header.peek(strIfModifiedSince)
  1253. if len(ifModStr) == 0 {
  1254. return true
  1255. }
  1256. ifMod, err := ParseHTTPDate(ifModStr)
  1257. if err != nil {
  1258. return true
  1259. }
  1260. lastModified = lastModified.Truncate(time.Second)
  1261. return ifMod.Before(lastModified)
  1262. }
  1263. // NotModified resets response and sets '304 Not Modified' response status code.
  1264. func (ctx *RequestCtx) NotModified() {
  1265. ctx.Response.Reset()
  1266. ctx.SetStatusCode(StatusNotModified)
  1267. }
  1268. // NotFound resets response and sets '404 Not Found' response status code.
  1269. func (ctx *RequestCtx) NotFound() {
  1270. ctx.Response.Reset()
  1271. ctx.SetStatusCode(StatusNotFound)
  1272. ctx.SetBodyString("404 Page not found")
  1273. }
  1274. // Write writes p into response body.
  1275. func (ctx *RequestCtx) Write(p []byte) (int, error) {
  1276. ctx.Response.AppendBody(p)
  1277. return len(p), nil
  1278. }
  1279. // WriteString appends s to response body.
  1280. func (ctx *RequestCtx) WriteString(s string) (int, error) {
  1281. ctx.Response.AppendBodyString(s)
  1282. return len(s), nil
  1283. }
  1284. // PostBody returns POST request body.
  1285. //
  1286. // The returned bytes are valid until your request handler returns.
  1287. func (ctx *RequestCtx) PostBody() []byte {
  1288. return ctx.Request.Body()
  1289. }
  1290. // SetBodyStream sets response body stream and, optionally body size.
  1291. //
  1292. // bodyStream.Close() is called after finishing reading all body data
  1293. // if it implements io.Closer.
  1294. //
  1295. // If bodySize is >= 0, then bodySize bytes must be provided by bodyStream
  1296. // before returning io.EOF.
  1297. //
  1298. // If bodySize < 0, then bodyStream is read until io.EOF.
  1299. //
  1300. // See also SetBodyStreamWriter.
  1301. func (ctx *RequestCtx) SetBodyStream(bodyStream io.Reader, bodySize int) {
  1302. ctx.Response.SetBodyStream(bodyStream, bodySize)
  1303. }
  1304. // SetBodyStreamWriter registers the given stream writer for populating
  1305. // response body.
  1306. //
  1307. // Access to RequestCtx and/or its members is forbidden from sw.
  1308. //
  1309. // This function may be used in the following cases:
  1310. //
  1311. // - if response body is too big (more than 10MB).
  1312. // - if response body is streamed from slow external sources.
  1313. // - if response body must be streamed to the client in chunks.
  1314. // (aka `http server push`).
  1315. func (ctx *RequestCtx) SetBodyStreamWriter(sw StreamWriter) {
  1316. ctx.Response.SetBodyStreamWriter(sw)
  1317. }
  1318. // IsBodyStream returns true if response body is set via SetBodyStream*.
  1319. func (ctx *RequestCtx) IsBodyStream() bool {
  1320. return ctx.Response.IsBodyStream()
  1321. }
  1322. // Logger returns logger, which may be used for logging arbitrary
  1323. // request-specific messages inside RequestHandler.
  1324. //
  1325. // Each message logged via returned logger contains request-specific information
  1326. // such as request id, request duration, local address, remote address,
  1327. // request method and request url.
  1328. //
  1329. // It is safe re-using returned logger for logging multiple messages
  1330. // for the current request.
  1331. //
  1332. // The returned logger is valid until your request handler returns.
  1333. func (ctx *RequestCtx) Logger() Logger {
  1334. if ctx.logger.ctx == nil {
  1335. ctx.logger.ctx = ctx
  1336. }
  1337. if ctx.logger.logger == nil {
  1338. ctx.logger.logger = ctx.s.logger()
  1339. }
  1340. return &ctx.logger
  1341. }
  1342. // TimeoutError sets response status code to StatusRequestTimeout and sets
  1343. // body to the given msg.
  1344. //
  1345. // All response modifications after TimeoutError call are ignored.
  1346. //
  1347. // TimeoutError MUST be called before returning from RequestHandler if there are
  1348. // references to ctx and/or its members in other goroutines remain.
  1349. //
  1350. // Usage of this function is discouraged. Prefer eliminating ctx references
  1351. // from pending goroutines instead of using this function.
  1352. func (ctx *RequestCtx) TimeoutError(msg string) {
  1353. ctx.TimeoutErrorWithCode(msg, StatusRequestTimeout)
  1354. }
  1355. // TimeoutErrorWithCode sets response body to msg and response status
  1356. // code to statusCode.
  1357. //
  1358. // All response modifications after TimeoutErrorWithCode call are ignored.
  1359. //
  1360. // TimeoutErrorWithCode MUST be called before returning from RequestHandler
  1361. // if there are references to ctx and/or its members in other goroutines remain.
  1362. //
  1363. // Usage of this function is discouraged. Prefer eliminating ctx references
  1364. // from pending goroutines instead of using this function.
  1365. func (ctx *RequestCtx) TimeoutErrorWithCode(msg string, statusCode int) {
  1366. var resp Response
  1367. resp.SetStatusCode(statusCode)
  1368. resp.SetBodyString(msg)
  1369. ctx.TimeoutErrorWithResponse(&resp)
  1370. }
  1371. // TimeoutErrorWithResponse marks the ctx as timed out and sends the given
  1372. // response to the client.
  1373. //
  1374. // All ctx modifications after TimeoutErrorWithResponse call are ignored.
  1375. //
  1376. // TimeoutErrorWithResponse MUST be called before returning from RequestHandler
  1377. // if there are references to ctx and/or its members in other goroutines remain.
  1378. //
  1379. // Usage of this function is discouraged. Prefer eliminating ctx references
  1380. // from pending goroutines instead of using this function.
  1381. func (ctx *RequestCtx) TimeoutErrorWithResponse(resp *Response) {
  1382. respCopy := &Response{}
  1383. resp.CopyTo(respCopy)
  1384. ctx.timeoutResponse = respCopy
  1385. }
  1386. // NextProto adds nph to be processed when key is negotiated when TLS
  1387. // connection is established.
  1388. //
  1389. // This function can only be called before the server is started.
  1390. func (s *Server) NextProto(key string, nph ServeHandler) {
  1391. if s.nextProtos == nil {
  1392. s.nextProtos = make(map[string]ServeHandler)
  1393. }
  1394. s.configTLS()
  1395. s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, key)
  1396. s.nextProtos[key] = nph
  1397. }
  1398. func (s *Server) getNextProto(c net.Conn) (proto string, err error) {
  1399. if tlsConn, ok := c.(connTLSer); ok {
  1400. if s.ReadTimeout > 0 {
  1401. if err := c.SetReadDeadline(time.Now().Add(s.ReadTimeout)); err != nil {
  1402. panic(fmt.Sprintf("BUG: error in SetReadDeadline(%v): %v", s.ReadTimeout, err))
  1403. }
  1404. }
  1405. if s.WriteTimeout > 0 {
  1406. if err := c.SetWriteDeadline(time.Now().Add(s.WriteTimeout)); err != nil {
  1407. panic(fmt.Sprintf("BUG: error in SetWriteDeadline(%v): %v", s.WriteTimeout, err))
  1408. }
  1409. }
  1410. err = tlsConn.Handshake()
  1411. if err == nil {
  1412. proto = tlsConn.ConnectionState().NegotiatedProtocol
  1413. }
  1414. }
  1415. return
  1416. }
  1417. // ListenAndServe serves HTTP requests from the given TCP4 addr.
  1418. //
  1419. // Pass custom listener to Serve if you need listening on non-TCP4 media
  1420. // such as IPv6.
  1421. //
  1422. // Accepted connections are configured to enable TCP keep-alives.
  1423. func (s *Server) ListenAndServe(addr string) error {
  1424. ln, err := net.Listen("tcp4", addr)
  1425. if err != nil {
  1426. return err
  1427. }
  1428. return s.Serve(ln)
  1429. }
  1430. // ListenAndServeUNIX serves HTTP requests from the given UNIX addr.
  1431. //
  1432. // The function deletes existing file at addr before starting serving.
  1433. //
  1434. // The server sets the given file mode for the UNIX addr.
  1435. func (s *Server) ListenAndServeUNIX(addr string, mode os.FileMode) error {
  1436. if err := os.Remove(addr); err != nil && !os.IsNotExist(err) {
  1437. return fmt.Errorf("unexpected error when trying to remove unix socket file %q: %w", addr, err)
  1438. }
  1439. ln, err := net.Listen("unix", addr)
  1440. if err != nil {
  1441. return err
  1442. }
  1443. if err = os.Chmod(addr, mode); err != nil {
  1444. return fmt.Errorf("cannot chmod %#o for %q: %w", mode, addr, err)
  1445. }
  1446. return s.Serve(ln)
  1447. }
  1448. // ListenAndServeTLS serves HTTPS requests from the given TCP4 addr.
  1449. //
  1450. // certFile and keyFile are paths to TLS certificate and key files.
  1451. //
  1452. // Pass custom listener to Serve if you need listening on non-TCP4 media
  1453. // such as IPv6.
  1454. //
  1455. // If the certFile or keyFile has not been provided to the server structure,
  1456. // the function will use the previously added TLS configuration.
  1457. //
  1458. // Accepted connections are configured to enable TCP keep-alives.
  1459. func (s *Server) ListenAndServeTLS(addr, certFile, keyFile string) error {
  1460. ln, err := net.Listen("tcp4", addr)
  1461. if err != nil {
  1462. return err
  1463. }
  1464. return s.ServeTLS(ln, certFile, keyFile)
  1465. }
  1466. // ListenAndServeTLSEmbed serves HTTPS requests from the given TCP4 addr.
  1467. //
  1468. // certData and keyData must contain valid TLS certificate and key data.
  1469. //
  1470. // Pass custom listener to Serve if you need listening on arbitrary media
  1471. // such as IPv6.
  1472. //
  1473. // If the certFile or keyFile has not been provided the server structure,
  1474. // the function will use previously added TLS configuration.
  1475. //
  1476. // Accepted connections are configured to enable TCP keep-alives.
  1477. func (s *Server) ListenAndServeTLSEmbed(addr string, certData, keyData []byte) error {
  1478. ln, err := net.Listen("tcp4", addr)
  1479. if err != nil {
  1480. return err
  1481. }
  1482. return s.ServeTLSEmbed(ln, certData, keyData)
  1483. }
  1484. // ServeTLS serves HTTPS requests from the given listener.
  1485. //
  1486. // certFile and keyFile are paths to TLS certificate and key files.
  1487. //
  1488. // If the certFile or keyFile has not been provided the server structure,
  1489. // the function will use previously added TLS configuration.
  1490. func (s *Server) ServeTLS(ln net.Listener, certFile, keyFile string) error {
  1491. s.mu.Lock()
  1492. s.configTLS()
  1493. configHasCert := len(s.TLSConfig.Certificates) > 0 || s.TLSConfig.GetCertificate != nil
  1494. if !configHasCert || certFile != "" || keyFile != "" {
  1495. if err := s.AppendCert(certFile, keyFile); err != nil {
  1496. s.mu.Unlock()
  1497. return err
  1498. }
  1499. }
  1500. // BuildNameToCertificate has been deprecated since 1.14.
  1501. // But since we also support older versions we'll keep this here.
  1502. s.TLSConfig.BuildNameToCertificate() //nolint:staticcheck
  1503. s.mu.Unlock()
  1504. return s.Serve(
  1505. tls.NewListener(ln, s.TLSConfig.Clone()),
  1506. )
  1507. }
  1508. // ServeTLSEmbed serves HTTPS requests from the given listener.
  1509. //
  1510. // certData and keyData must contain valid TLS certificate and key data.
  1511. //
  1512. // If the certFile or keyFile has not been provided the server structure,
  1513. // the function will use previously added TLS configuration.
  1514. func (s *Server) ServeTLSEmbed(ln net.Listener, certData, keyData []byte) error {
  1515. s.mu.Lock()
  1516. s.configTLS()
  1517. configHasCert := len(s.TLSConfig.Certificates) > 0 || s.TLSConfig.GetCertificate != nil
  1518. if !configHasCert || len(certData) != 0 || len(keyData) != 0 {
  1519. if err := s.AppendCertEmbed(certData, keyData); err != nil {
  1520. s.mu.Unlock()
  1521. return err
  1522. }
  1523. }
  1524. // BuildNameToCertificate has been deprecated since 1.14.
  1525. // But since we also support older versions we'll keep this here.
  1526. s.TLSConfig.BuildNameToCertificate() //nolint:staticcheck
  1527. s.mu.Unlock()
  1528. return s.Serve(
  1529. tls.NewListener(ln, s.TLSConfig.Clone()),
  1530. )
  1531. }
  1532. // AppendCert appends certificate and keyfile to TLS Configuration.
  1533. //
  1534. // This function allows programmer to handle multiple domains
  1535. // in one server structure. See examples/multidomain
  1536. func (s *Server) AppendCert(certFile, keyFile string) error {
  1537. if len(certFile) == 0 && len(keyFile) == 0 {
  1538. return errNoCertOrKeyProvided
  1539. }
  1540. cert, err := tls.LoadX509KeyPair(certFile, keyFile)
  1541. if err != nil {
  1542. return fmt.Errorf("cannot load TLS key pair from certFile=%q and keyFile=%q: %w", certFile, keyFile, err)
  1543. }
  1544. s.configTLS()
  1545. s.TLSConfig.Certificates = append(s.TLSConfig.Certificates, cert)
  1546. return nil
  1547. }
  1548. // AppendCertEmbed does the same as AppendCert but using in-memory data.
  1549. func (s *Server) AppendCertEmbed(certData, keyData []byte) error {
  1550. if len(certData) == 0 && len(keyData) == 0 {
  1551. return errNoCertOrKeyProvided
  1552. }
  1553. cert, err := tls.X509KeyPair(certData, keyData)
  1554. if err != nil {
  1555. return fmt.Errorf("cannot load TLS key pair from the provided certData(%d) and keyData(%d): %w",
  1556. len(certData), len(keyData), err)
  1557. }
  1558. s.configTLS()
  1559. s.TLSConfig.Certificates = append(s.TLSConfig.Certificates, cert)
  1560. return nil
  1561. }
  1562. func (s *Server) configTLS() {
  1563. if s.TLSConfig == nil {
  1564. s.TLSConfig = &tls.Config{}
  1565. }
  1566. }
  1567. // DefaultConcurrency is the maximum number of concurrent connections
  1568. // the Server may serve by default (i.e. if Server.Concurrency isn't set).
  1569. const DefaultConcurrency = 256 * 1024
  1570. // Serve serves incoming connections from the given listener.
  1571. //
  1572. // Serve blocks until the given listener returns permanent error.
  1573. func (s *Server) Serve(ln net.Listener) error {
  1574. var lastOverflowErrorTime time.Time
  1575. var lastPerIPErrorTime time.Time
  1576. var c net.Conn
  1577. var err error
  1578. maxWorkersCount := s.getConcurrency()
  1579. s.mu.Lock()
  1580. s.ln = append(s.ln, ln)
  1581. if s.done == nil {
  1582. s.done = make(chan struct{})
  1583. }
  1584. if s.concurrencyCh == nil {
  1585. s.concurrencyCh = make(chan struct{}, maxWorkersCount)
  1586. }
  1587. s.mu.Unlock()
  1588. wp := &workerPool{
  1589. WorkerFunc: s.serveConn,
  1590. MaxWorkersCount: maxWorkersCount,
  1591. LogAllErrors: s.LogAllErrors,
  1592. MaxIdleWorkerDuration: s.MaxIdleWorkerDuration,
  1593. Logger: s.logger(),
  1594. connState: s.setState,
  1595. }
  1596. wp.Start()
  1597. // Count our waiting to accept a connection as an open connection.
  1598. // This way we can't get into any weird state where just after accepting
  1599. // a connection Shutdown is called which reads open as 0 because it isn't
  1600. // incremented yet.
  1601. atomic.AddInt32(&s.open, 1)
  1602. defer atomic.AddInt32(&s.open, -1)
  1603. for {
  1604. if c, err = acceptConn(s, ln, &lastPerIPErrorTime); err != nil {
  1605. wp.Stop()
  1606. if err == io.EOF {
  1607. return nil
  1608. }
  1609. return err
  1610. }
  1611. s.setState(c, StateNew)
  1612. atomic.AddInt32(&s.open, 1)
  1613. if !wp.Serve(c) {
  1614. atomic.AddInt32(&s.open, -1)
  1615. s.writeFastError(c, StatusServiceUnavailable,
  1616. "The connection cannot be served because Server.Concurrency limit exceeded")
  1617. c.Close()
  1618. s.setState(c, StateClosed)
  1619. if time.Since(lastOverflowErrorTime) > time.Minute {
  1620. s.logger().Printf("The incoming connection cannot be served, because %d concurrent connections are served. "+
  1621. "Try increasing Server.Concurrency", maxWorkersCount)
  1622. lastOverflowErrorTime = time.Now()
  1623. }
  1624. // The current server reached concurrency limit,
  1625. // so give other concurrently running servers a chance
  1626. // accepting incoming connections on the same address.
  1627. //
  1628. // There is a hope other servers didn't reach their
  1629. // concurrency limits yet :)
  1630. //
  1631. // See also: https://github.com/valyala/fasthttp/pull/485#discussion_r239994990
  1632. if s.SleepWhenConcurrencyLimitsExceeded > 0 {
  1633. time.Sleep(s.SleepWhenConcurrencyLimitsExceeded)
  1634. }
  1635. }
  1636. c = nil
  1637. }
  1638. }
  1639. // Shutdown gracefully shuts down the server without interrupting any active connections.
  1640. // Shutdown works by first closing all open listeners and then waiting indefinitely for all connections to return to idle and then shut down.
  1641. //
  1642. // When Shutdown is called, Serve, ListenAndServe, and ListenAndServeTLS immediately return nil.
  1643. // Make sure the program doesn't exit and waits instead for Shutdown to return.
  1644. //
  1645. // Shutdown does not close keepalive connections so it's recommended to set ReadTimeout and IdleTimeout to something else than 0.
  1646. func (s *Server) Shutdown() error {
  1647. return s.ShutdownWithContext(context.Background())
  1648. }
  1649. // ShutdownWithContext gracefully shuts down the server without interrupting any active connections.
  1650. // ShutdownWithContext works by first closing all open listeners and then waiting for all connections to return to idle or context timeout and then shut down.
  1651. //
  1652. // When ShutdownWithContext is called, Serve, ListenAndServe, and ListenAndServeTLS immediately return nil.
  1653. // Make sure the program doesn't exit and waits instead for Shutdown to return.
  1654. //
  1655. // ShutdownWithContext does not close keepalive connections so it's recommended to set ReadTimeout and IdleTimeout to something else than 0.
  1656. func (s *Server) ShutdownWithContext(ctx context.Context) (err error) {
  1657. s.mu.Lock()
  1658. defer s.mu.Unlock()
  1659. atomic.StoreInt32(&s.stop, 1)
  1660. defer atomic.StoreInt32(&s.stop, 0)
  1661. if s.ln == nil {
  1662. return nil
  1663. }
  1664. for _, ln := range s.ln {
  1665. if err = ln.Close(); err != nil {
  1666. return err
  1667. }
  1668. }
  1669. if s.done != nil {
  1670. close(s.done)
  1671. }
  1672. // Closing the listener will make Serve() call Stop on the worker pool.
  1673. // Setting .stop to 1 will make serveConn() break out of its loop.
  1674. // Now we just have to wait until all workers are done or timeout.
  1675. ticker := time.NewTicker(time.Millisecond * 100)
  1676. defer ticker.Stop()
  1677. END:
  1678. for {
  1679. s.closeIdleConns()
  1680. if open := atomic.LoadInt32(&s.open); open == 0 {
  1681. break
  1682. }
  1683. // This is not an optimal solution but using a sync.WaitGroup
  1684. // here causes data races as it's hard to prevent Add() to be called
  1685. // while Wait() is waiting.
  1686. select {
  1687. case <-ctx.Done():
  1688. err = ctx.Err()
  1689. break END
  1690. case <-ticker.C:
  1691. continue
  1692. }
  1693. }
  1694. s.done = nil
  1695. s.ln = nil
  1696. return err
  1697. }
  1698. func acceptConn(s *Server, ln net.Listener, lastPerIPErrorTime *time.Time) (net.Conn, error) {
  1699. for {
  1700. c, err := ln.Accept()
  1701. if err != nil {
  1702. if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
  1703. s.logger().Printf("Timeout error when accepting new connections: %v", netErr)
  1704. time.Sleep(time.Second)
  1705. continue
  1706. }
  1707. if err != io.EOF && !strings.Contains(err.Error(), "use of closed network connection") {
  1708. s.logger().Printf("Permanent error when accepting new connections: %v", err)
  1709. return nil, err
  1710. }
  1711. return nil, io.EOF
  1712. }
  1713. if tc, ok := c.(*net.TCPConn); ok && s.TCPKeepalive {
  1714. if err := tc.SetKeepAlive(s.TCPKeepalive); err != nil {
  1715. _ = tc.Close()
  1716. return nil, err
  1717. }
  1718. if s.TCPKeepalivePeriod > 0 {
  1719. if err := tc.SetKeepAlivePeriod(s.TCPKeepalivePeriod); err != nil {
  1720. _ = tc.Close()
  1721. return nil, err
  1722. }
  1723. }
  1724. }
  1725. if s.MaxConnsPerIP > 0 {
  1726. pic := wrapPerIPConn(s, c)
  1727. if pic == nil {
  1728. if time.Since(*lastPerIPErrorTime) > time.Minute {
  1729. s.logger().Printf("The number of connections from %s exceeds MaxConnsPerIP=%d",
  1730. getConnIP4(c), s.MaxConnsPerIP)
  1731. *lastPerIPErrorTime = time.Now()
  1732. }
  1733. continue
  1734. }
  1735. c = pic
  1736. }
  1737. return c, nil
  1738. }
  1739. }
  1740. func wrapPerIPConn(s *Server, c net.Conn) net.Conn {
  1741. ip := getUint32IP(c)
  1742. if ip == 0 {
  1743. return c
  1744. }
  1745. n := s.perIPConnCounter.Register(ip)
  1746. if n > s.MaxConnsPerIP {
  1747. s.perIPConnCounter.Unregister(ip)
  1748. s.writeFastError(c, StatusTooManyRequests, "The number of connections from your ip exceeds MaxConnsPerIP")
  1749. c.Close()
  1750. return nil
  1751. }
  1752. return acquirePerIPConn(c, ip, &s.perIPConnCounter)
  1753. }
  1754. var defaultLogger = Logger(log.New(os.Stderr, "", log.LstdFlags))
  1755. func (s *Server) logger() Logger {
  1756. if s.Logger != nil {
  1757. return s.Logger
  1758. }
  1759. return defaultLogger
  1760. }
  1761. var (
  1762. // ErrPerIPConnLimit may be returned from ServeConn if the number of connections
  1763. // per ip exceeds Server.MaxConnsPerIP.
  1764. ErrPerIPConnLimit = errors.New("too many connections per ip")
  1765. // ErrConcurrencyLimit may be returned from ServeConn if the number
  1766. // of concurrently served connections exceeds Server.Concurrency.
  1767. ErrConcurrencyLimit = errors.New("cannot serve the connection because Server.Concurrency concurrent connections are served")
  1768. )
  1769. // ServeConn serves HTTP requests from the given connection.
  1770. //
  1771. // ServeConn returns nil if all requests from the c are successfully served.
  1772. // It returns non-nil error otherwise.
  1773. //
  1774. // Connection c must immediately propagate all the data passed to Write()
  1775. // to the client. Otherwise requests' processing may hang.
  1776. //
  1777. // ServeConn closes c before returning.
  1778. func (s *Server) ServeConn(c net.Conn) error {
  1779. if s.MaxConnsPerIP > 0 {
  1780. pic := wrapPerIPConn(s, c)
  1781. if pic == nil {
  1782. return ErrPerIPConnLimit
  1783. }
  1784. c = pic
  1785. }
  1786. n := atomic.AddUint32(&s.concurrency, 1)
  1787. if n > uint32(s.getConcurrency()) {
  1788. atomic.AddUint32(&s.concurrency, ^uint32(0))
  1789. s.writeFastError(c, StatusServiceUnavailable, "The connection cannot be served because Server.Concurrency limit exceeded")
  1790. c.Close()
  1791. return ErrConcurrencyLimit
  1792. }
  1793. atomic.AddInt32(&s.open, 1)
  1794. err := s.serveConn(c)
  1795. atomic.AddUint32(&s.concurrency, ^uint32(0))
  1796. if err != errHijacked {
  1797. err1 := c.Close()
  1798. s.setState(c, StateClosed)
  1799. if err == nil {
  1800. err = err1
  1801. }
  1802. } else {
  1803. err = nil
  1804. s.setState(c, StateHijacked)
  1805. }
  1806. return err
  1807. }
  1808. var errHijacked = errors.New("connection has been hijacked")
  1809. // GetCurrentConcurrency returns a number of currently served
  1810. // connections.
  1811. //
  1812. // This function is intended be used by monitoring systems
  1813. func (s *Server) GetCurrentConcurrency() uint32 {
  1814. return atomic.LoadUint32(&s.concurrency)
  1815. }
  1816. // GetOpenConnectionsCount returns a number of opened connections.
  1817. //
  1818. // This function is intended be used by monitoring systems
  1819. func (s *Server) GetOpenConnectionsCount() int32 {
  1820. if atomic.LoadInt32(&s.stop) == 0 {
  1821. // Decrement by one to avoid reporting the extra open value that gets
  1822. // counted while the server is listening.
  1823. return atomic.LoadInt32(&s.open) - 1
  1824. }
  1825. // This is not perfect, because s.stop could have changed to zero
  1826. // before we load the value of s.open. However, in the common case
  1827. // this avoids underreporting open connections by 1 during server shutdown.
  1828. return atomic.LoadInt32(&s.open)
  1829. }
  1830. func (s *Server) getConcurrency() int {
  1831. n := s.Concurrency
  1832. if n <= 0 {
  1833. n = DefaultConcurrency
  1834. }
  1835. return n
  1836. }
  1837. var globalConnID uint64
  1838. func nextConnID() uint64 {
  1839. return atomic.AddUint64(&globalConnID, 1)
  1840. }
  1841. // DefaultMaxRequestBodySize is the maximum request body size the server
  1842. // reads by default.
  1843. //
  1844. // See Server.MaxRequestBodySize for details.
  1845. const DefaultMaxRequestBodySize = 4 * 1024 * 1024
  1846. func (s *Server) idleTimeout() time.Duration {
  1847. if s.IdleTimeout != 0 {
  1848. return s.IdleTimeout
  1849. }
  1850. return s.ReadTimeout
  1851. }
  1852. func (s *Server) serveConnCleanup() {
  1853. atomic.AddInt32(&s.open, -1)
  1854. atomic.AddUint32(&s.concurrency, ^uint32(0))
  1855. }
  1856. func (s *Server) serveConn(c net.Conn) (err error) {
  1857. defer s.serveConnCleanup()
  1858. atomic.AddUint32(&s.concurrency, 1)
  1859. var proto string
  1860. if proto, err = s.getNextProto(c); err != nil {
  1861. return
  1862. }
  1863. if handler, ok := s.nextProtos[proto]; ok {
  1864. // Remove read or write deadlines that might have previously been set.
  1865. // The next handler is responsible for setting its own deadlines.
  1866. if s.ReadTimeout > 0 || s.WriteTimeout > 0 {
  1867. if err := c.SetDeadline(zeroTime); err != nil {
  1868. panic(fmt.Sprintf("BUG: error in SetDeadline(zeroTime): %v", err))
  1869. }
  1870. }
  1871. return handler(c)
  1872. }
  1873. serverName := s.getServerName()
  1874. connRequestNum := uint64(0)
  1875. connID := nextConnID()
  1876. connTime := time.Now()
  1877. maxRequestBodySize := s.MaxRequestBodySize
  1878. if maxRequestBodySize <= 0 {
  1879. maxRequestBodySize = DefaultMaxRequestBodySize
  1880. }
  1881. writeTimeout := s.WriteTimeout
  1882. previousWriteTimeout := time.Duration(0)
  1883. ctx := s.acquireCtx(c)
  1884. ctx.connTime = connTime
  1885. isTLS := ctx.IsTLS()
  1886. var (
  1887. br *bufio.Reader
  1888. bw *bufio.Writer
  1889. timeoutResponse *Response
  1890. hijackHandler HijackHandler
  1891. hijackNoResponse bool
  1892. connectionClose bool
  1893. continueReadingRequest = true
  1894. )
  1895. for {
  1896. connRequestNum++
  1897. // If this is a keep-alive connection set the idle timeout.
  1898. if connRequestNum > 1 {
  1899. if d := s.idleTimeout(); d > 0 {
  1900. if err := c.SetReadDeadline(time.Now().Add(d)); err != nil {
  1901. break
  1902. }
  1903. }
  1904. }
  1905. if !s.ReduceMemoryUsage || br != nil {
  1906. if br == nil {
  1907. br = acquireReader(ctx)
  1908. }
  1909. // If this is a keep-alive connection we want to try and read the first bytes
  1910. // within the idle time.
  1911. if connRequestNum > 1 {
  1912. var b []byte
  1913. b, err = br.Peek(1)
  1914. if len(b) == 0 {
  1915. // If reading from a keep-alive connection returns nothing it means
  1916. // the connection was closed (either timeout or from the other side).
  1917. if err != io.EOF {
  1918. err = ErrNothingRead{err}
  1919. }
  1920. }
  1921. }
  1922. } else {
  1923. // If this is a keep-alive connection acquireByteReader will try to peek
  1924. // a couple of bytes already so the idle timeout will already be used.
  1925. br, err = acquireByteReader(&ctx)
  1926. }
  1927. ctx.Request.isTLS = isTLS
  1928. ctx.Response.Header.noDefaultContentType = s.NoDefaultContentType
  1929. ctx.Response.Header.noDefaultDate = s.NoDefaultDate
  1930. // Secure header error logs configuration
  1931. ctx.Request.Header.secureErrorLogMessage = s.SecureErrorLogMessage
  1932. ctx.Response.Header.secureErrorLogMessage = s.SecureErrorLogMessage
  1933. ctx.Request.secureErrorLogMessage = s.SecureErrorLogMessage
  1934. ctx.Response.secureErrorLogMessage = s.SecureErrorLogMessage
  1935. if err == nil {
  1936. s.setState(c, StateActive)
  1937. if s.ReadTimeout > 0 {
  1938. if err := c.SetReadDeadline(time.Now().Add(s.ReadTimeout)); err != nil {
  1939. break
  1940. }
  1941. } else if s.IdleTimeout > 0 && connRequestNum > 1 {
  1942. // If this was an idle connection and the server has an IdleTimeout but
  1943. // no ReadTimeout then we should remove the ReadTimeout.
  1944. if err := c.SetReadDeadline(zeroTime); err != nil {
  1945. break
  1946. }
  1947. }
  1948. if s.DisableHeaderNamesNormalizing {
  1949. ctx.Request.Header.DisableNormalizing()
  1950. ctx.Response.Header.DisableNormalizing()
  1951. }
  1952. // Reading Headers.
  1953. //
  1954. // If we have pipeline response in the outgoing buffer,
  1955. // we only want to try and read the next headers once.
  1956. // If we have to wait for the next request we flush the
  1957. // outgoing buffer first so it doesn't have to wait.
  1958. if bw != nil && bw.Buffered() > 0 {
  1959. err = ctx.Request.Header.readLoop(br, false)
  1960. if err == errNeedMore {
  1961. err = bw.Flush()
  1962. if err != nil {
  1963. break
  1964. }
  1965. err = ctx.Request.Header.Read(br)
  1966. }
  1967. } else {
  1968. err = ctx.Request.Header.Read(br)
  1969. }
  1970. if err == nil {
  1971. if onHdrRecv := s.HeaderReceived; onHdrRecv != nil {
  1972. reqConf := onHdrRecv(&ctx.Request.Header)
  1973. if reqConf.ReadTimeout > 0 {
  1974. deadline := time.Now().Add(reqConf.ReadTimeout)
  1975. if err := c.SetReadDeadline(deadline); err != nil {
  1976. panic(fmt.Sprintf("BUG: error in SetReadDeadline(%v): %v", deadline, err))
  1977. }
  1978. }
  1979. switch {
  1980. case reqConf.MaxRequestBodySize > 0:
  1981. maxRequestBodySize = reqConf.MaxRequestBodySize
  1982. case s.MaxRequestBodySize > 0:
  1983. maxRequestBodySize = s.MaxRequestBodySize
  1984. default:
  1985. maxRequestBodySize = DefaultMaxRequestBodySize
  1986. }
  1987. if reqConf.WriteTimeout > 0 {
  1988. writeTimeout = reqConf.WriteTimeout
  1989. } else {
  1990. writeTimeout = s.WriteTimeout
  1991. }
  1992. }
  1993. // read body
  1994. if s.StreamRequestBody {
  1995. err = ctx.Request.readBodyStream(br, maxRequestBodySize, s.GetOnly, !s.DisablePreParseMultipartForm)
  1996. } else {
  1997. err = ctx.Request.readLimitBody(br, maxRequestBodySize, s.GetOnly, !s.DisablePreParseMultipartForm)
  1998. }
  1999. }
  2000. if (s.ReduceMemoryUsage && br.Buffered() == 0) || err != nil {
  2001. releaseReader(s, br)
  2002. br = nil
  2003. }
  2004. }
  2005. if err != nil {
  2006. if err == io.EOF {
  2007. err = nil
  2008. } else if nr, ok := err.(ErrNothingRead); ok {
  2009. if connRequestNum > 1 {
  2010. // This is not the first request and we haven't read a single byte
  2011. // of a new request yet. This means it's just a keep-alive connection
  2012. // closing down either because the remote closed it or because
  2013. // or a read timeout on our side. Either way just close the connection
  2014. // and don't return any error response.
  2015. err = nil
  2016. } else {
  2017. err = nr.error
  2018. }
  2019. }
  2020. if err != nil {
  2021. bw = s.writeErrorResponse(bw, ctx, serverName, err)
  2022. }
  2023. break
  2024. }
  2025. // 'Expect: 100-continue' request handling.
  2026. // See https://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html#sec8.2.3 for details.
  2027. if ctx.Request.MayContinue() {
  2028. // Allow the ability to deny reading the incoming request body
  2029. if s.ContinueHandler != nil {
  2030. if continueReadingRequest = s.ContinueHandler(&ctx.Request.Header); !continueReadingRequest {
  2031. if br != nil {
  2032. br.Reset(ctx.c)
  2033. }
  2034. ctx.SetStatusCode(StatusExpectationFailed)
  2035. }
  2036. }
  2037. if continueReadingRequest {
  2038. if bw == nil {
  2039. bw = acquireWriter(ctx)
  2040. }
  2041. // Send 'HTTP/1.1 100 Continue' response.
  2042. _, err = bw.Write(strResponseContinue)
  2043. if err != nil {
  2044. break
  2045. }
  2046. err = bw.Flush()
  2047. if err != nil {
  2048. break
  2049. }
  2050. if s.ReduceMemoryUsage {
  2051. releaseWriter(s, bw)
  2052. bw = nil
  2053. }
  2054. // Read request body.
  2055. if br == nil {
  2056. br = acquireReader(ctx)
  2057. }
  2058. if s.StreamRequestBody {
  2059. err = ctx.Request.ContinueReadBodyStream(br, maxRequestBodySize, !s.DisablePreParseMultipartForm)
  2060. } else {
  2061. err = ctx.Request.ContinueReadBody(br, maxRequestBodySize, !s.DisablePreParseMultipartForm)
  2062. }
  2063. if (s.ReduceMemoryUsage && br.Buffered() == 0) || err != nil {
  2064. releaseReader(s, br)
  2065. br = nil
  2066. }
  2067. if err != nil {
  2068. bw = s.writeErrorResponse(bw, ctx, serverName, err)
  2069. break
  2070. }
  2071. }
  2072. }
  2073. // store req.ConnectionClose so even if it was changed inside of handler
  2074. connectionClose = s.DisableKeepalive || ctx.Request.Header.ConnectionClose()
  2075. if serverName != "" {
  2076. ctx.Response.Header.SetServer(serverName)
  2077. }
  2078. ctx.connID = connID
  2079. ctx.connRequestNum = connRequestNum
  2080. ctx.time = time.Now()
  2081. // If a client denies a request the handler should not be called
  2082. if continueReadingRequest {
  2083. s.Handler(ctx)
  2084. }
  2085. timeoutResponse = ctx.timeoutResponse
  2086. if timeoutResponse != nil {
  2087. // Acquire a new ctx because the old one will still be in use by the timeout out handler.
  2088. ctx = s.acquireCtx(c)
  2089. timeoutResponse.CopyTo(&ctx.Response)
  2090. }
  2091. if ctx.IsHead() {
  2092. ctx.Response.SkipBody = true
  2093. }
  2094. hijackHandler = ctx.hijackHandler
  2095. ctx.hijackHandler = nil
  2096. hijackNoResponse = ctx.hijackNoResponse && hijackHandler != nil
  2097. ctx.hijackNoResponse = false
  2098. if writeTimeout > 0 {
  2099. if err := c.SetWriteDeadline(time.Now().Add(writeTimeout)); err != nil {
  2100. panic(fmt.Sprintf("BUG: error in SetWriteDeadline(%v): %v", writeTimeout, err))
  2101. }
  2102. previousWriteTimeout = writeTimeout
  2103. } else if previousWriteTimeout > 0 {
  2104. // We don't want a write timeout but we previously set one, remove it.
  2105. if err := c.SetWriteDeadline(zeroTime); err != nil {
  2106. panic(fmt.Sprintf("BUG: error in SetWriteDeadline(zeroTime): %v", err))
  2107. }
  2108. previousWriteTimeout = 0
  2109. }
  2110. connectionClose = connectionClose ||
  2111. (s.MaxRequestsPerConn > 0 && connRequestNum >= uint64(s.MaxRequestsPerConn)) ||
  2112. ctx.Response.Header.ConnectionClose() ||
  2113. (s.CloseOnShutdown && atomic.LoadInt32(&s.stop) == 1)
  2114. if connectionClose {
  2115. ctx.Response.Header.SetConnectionClose()
  2116. } else if !ctx.Request.Header.IsHTTP11() {
  2117. // Set 'Connection: keep-alive' response header for HTTP/1.0 request.
  2118. // There is no need in setting this header for http/1.1, since in http/1.1
  2119. // connections are keep-alive by default.
  2120. ctx.Response.Header.setNonSpecial(strConnection, strKeepAlive)
  2121. }
  2122. if serverName != "" && len(ctx.Response.Header.Server()) == 0 {
  2123. ctx.Response.Header.SetServer(serverName)
  2124. }
  2125. if !hijackNoResponse {
  2126. if bw == nil {
  2127. bw = acquireWriter(ctx)
  2128. }
  2129. if err = writeResponse(ctx, bw); err != nil {
  2130. break
  2131. }
  2132. // Only flush the writer if we don't have another request in the pipeline.
  2133. // This is a big of an ugly optimization for https://www.techempower.com/benchmarks/
  2134. // This benchmark will send 16 pipelined requests. It is faster to pack as many responses
  2135. // in a TCP packet and send it back at once than waiting for a flush every request.
  2136. // In real world circumstances this behaviour could be argued as being wrong.
  2137. if br == nil || br.Buffered() == 0 || connectionClose {
  2138. err = bw.Flush()
  2139. if err != nil {
  2140. break
  2141. }
  2142. }
  2143. if connectionClose {
  2144. break
  2145. }
  2146. if s.ReduceMemoryUsage && hijackHandler == nil {
  2147. releaseWriter(s, bw)
  2148. bw = nil
  2149. }
  2150. }
  2151. if hijackHandler != nil {
  2152. var hjr io.Reader = c
  2153. if br != nil {
  2154. hjr = br
  2155. br = nil
  2156. }
  2157. if bw != nil {
  2158. err = bw.Flush()
  2159. if err != nil {
  2160. break
  2161. }
  2162. releaseWriter(s, bw)
  2163. bw = nil
  2164. }
  2165. err = c.SetDeadline(zeroTime)
  2166. if err != nil {
  2167. break
  2168. }
  2169. go hijackConnHandler(ctx, hjr, c, s, hijackHandler)
  2170. err = errHijacked
  2171. break
  2172. }
  2173. if ctx.Request.bodyStream != nil {
  2174. if rs, ok := ctx.Request.bodyStream.(*requestStream); ok {
  2175. releaseRequestStream(rs)
  2176. }
  2177. ctx.Request.bodyStream = nil
  2178. }
  2179. s.setState(c, StateIdle)
  2180. ctx.userValues.Reset()
  2181. ctx.Request.Reset()
  2182. ctx.Response.Reset()
  2183. if atomic.LoadInt32(&s.stop) == 1 {
  2184. err = nil
  2185. break
  2186. }
  2187. }
  2188. if br != nil {
  2189. releaseReader(s, br)
  2190. }
  2191. if bw != nil {
  2192. releaseWriter(s, bw)
  2193. }
  2194. if hijackHandler == nil {
  2195. s.releaseCtx(ctx)
  2196. }
  2197. return
  2198. }
  2199. func (s *Server) setState(nc net.Conn, state ConnState) {
  2200. s.trackConn(nc, state)
  2201. if hook := s.ConnState; hook != nil {
  2202. hook(nc, state)
  2203. }
  2204. }
  2205. func hijackConnHandler(ctx *RequestCtx, r io.Reader, c net.Conn, s *Server, h HijackHandler) {
  2206. hjc := s.acquireHijackConn(r, c)
  2207. h(hjc)
  2208. if br, ok := r.(*bufio.Reader); ok {
  2209. releaseReader(s, br)
  2210. }
  2211. if !s.KeepHijackedConns {
  2212. c.Close()
  2213. s.releaseHijackConn(hjc)
  2214. }
  2215. s.releaseCtx(ctx)
  2216. }
  2217. func (s *Server) acquireHijackConn(r io.Reader, c net.Conn) *hijackConn {
  2218. v := s.hijackConnPool.Get()
  2219. if v == nil {
  2220. hjc := &hijackConn{
  2221. Conn: c,
  2222. r: r,
  2223. s: s,
  2224. }
  2225. return hjc
  2226. }
  2227. hjc := v.(*hijackConn)
  2228. hjc.Conn = c
  2229. hjc.r = r
  2230. return hjc
  2231. }
  2232. func (s *Server) releaseHijackConn(hjc *hijackConn) {
  2233. hjc.Conn = nil
  2234. hjc.r = nil
  2235. s.hijackConnPool.Put(hjc)
  2236. }
  2237. type hijackConn struct {
  2238. net.Conn
  2239. r io.Reader
  2240. s *Server
  2241. }
  2242. func (c *hijackConn) UnsafeConn() net.Conn {
  2243. return c.Conn
  2244. }
  2245. func (c *hijackConn) Read(p []byte) (int, error) {
  2246. return c.r.Read(p)
  2247. }
  2248. func (c *hijackConn) Close() error {
  2249. if !c.s.KeepHijackedConns {
  2250. // when we do not keep hijacked connections,
  2251. // it is closed in hijackConnHandler.
  2252. return nil
  2253. }
  2254. return c.Conn.Close()
  2255. }
  2256. // LastTimeoutErrorResponse returns the last timeout response set
  2257. // via TimeoutError* call.
  2258. //
  2259. // This function is intended for custom server implementations.
  2260. func (ctx *RequestCtx) LastTimeoutErrorResponse() *Response {
  2261. return ctx.timeoutResponse
  2262. }
  2263. func writeResponse(ctx *RequestCtx, w *bufio.Writer) error {
  2264. if ctx.timeoutResponse != nil {
  2265. return errors.New("cannot write timed out response")
  2266. }
  2267. err := ctx.Response.Write(w)
  2268. return err
  2269. }
  2270. const (
  2271. defaultReadBufferSize = 4096
  2272. defaultWriteBufferSize = 4096
  2273. )
  2274. func acquireByteReader(ctxP **RequestCtx) (*bufio.Reader, error) {
  2275. ctx := *ctxP
  2276. s := ctx.s
  2277. c := ctx.c
  2278. s.releaseCtx(ctx)
  2279. // Make GC happy, so it could garbage collect ctx while we wait for the
  2280. // next request.
  2281. ctx = nil
  2282. *ctxP = nil
  2283. var b [1]byte
  2284. n, err := c.Read(b[:])
  2285. ctx = s.acquireCtx(c)
  2286. *ctxP = ctx
  2287. if err != nil {
  2288. // Treat all errors as EOF on unsuccessful read
  2289. // of the first request byte.
  2290. return nil, io.EOF
  2291. }
  2292. if n != 1 {
  2293. // developer sanity-check
  2294. panic("BUG: Reader must return at least one byte")
  2295. }
  2296. ctx.fbr.c = c
  2297. ctx.fbr.ch = b[0]
  2298. ctx.fbr.byteRead = false
  2299. r := acquireReader(ctx)
  2300. r.Reset(&ctx.fbr)
  2301. return r, nil
  2302. }
  2303. func acquireReader(ctx *RequestCtx) *bufio.Reader {
  2304. v := ctx.s.readerPool.Get()
  2305. if v == nil {
  2306. n := ctx.s.ReadBufferSize
  2307. if n <= 0 {
  2308. n = defaultReadBufferSize
  2309. }
  2310. return bufio.NewReaderSize(ctx.c, n)
  2311. }
  2312. r := v.(*bufio.Reader)
  2313. r.Reset(ctx.c)
  2314. return r
  2315. }
  2316. func releaseReader(s *Server, r *bufio.Reader) {
  2317. s.readerPool.Put(r)
  2318. }
  2319. func acquireWriter(ctx *RequestCtx) *bufio.Writer {
  2320. v := ctx.s.writerPool.Get()
  2321. if v == nil {
  2322. n := ctx.s.WriteBufferSize
  2323. if n <= 0 {
  2324. n = defaultWriteBufferSize
  2325. }
  2326. return bufio.NewWriterSize(ctx.c, n)
  2327. }
  2328. w := v.(*bufio.Writer)
  2329. w.Reset(ctx.c)
  2330. return w
  2331. }
  2332. func releaseWriter(s *Server, w *bufio.Writer) {
  2333. s.writerPool.Put(w)
  2334. }
  2335. func (s *Server) acquireCtx(c net.Conn) (ctx *RequestCtx) {
  2336. v := s.ctxPool.Get()
  2337. if v == nil {
  2338. keepBodyBuffer := !s.ReduceMemoryUsage
  2339. ctx = new(RequestCtx)
  2340. ctx.Request.keepBodyBuffer = keepBodyBuffer
  2341. ctx.Response.keepBodyBuffer = keepBodyBuffer
  2342. ctx.s = s
  2343. } else {
  2344. ctx = v.(*RequestCtx)
  2345. }
  2346. if s.FormValueFunc != nil {
  2347. ctx.formValueFunc = s.FormValueFunc
  2348. }
  2349. ctx.c = c
  2350. return ctx
  2351. }
  2352. // Init2 prepares ctx for passing to RequestHandler.
  2353. //
  2354. // conn is used only for determining local and remote addresses.
  2355. //
  2356. // This function is intended for custom Server implementations.
  2357. // See https://github.com/valyala/httpteleport for details.
  2358. func (ctx *RequestCtx) Init2(conn net.Conn, logger Logger, reduceMemoryUsage bool) {
  2359. ctx.c = conn
  2360. ctx.remoteAddr = nil
  2361. ctx.logger.logger = logger
  2362. ctx.connID = nextConnID()
  2363. ctx.s = fakeServer
  2364. ctx.connRequestNum = 0
  2365. ctx.connTime = time.Now()
  2366. keepBodyBuffer := !reduceMemoryUsage
  2367. ctx.Request.keepBodyBuffer = keepBodyBuffer
  2368. ctx.Response.keepBodyBuffer = keepBodyBuffer
  2369. }
  2370. // Init prepares ctx for passing to RequestHandler.
  2371. //
  2372. // remoteAddr and logger are optional. They are used by RequestCtx.Logger().
  2373. //
  2374. // This function is intended for custom Server implementations.
  2375. func (ctx *RequestCtx) Init(req *Request, remoteAddr net.Addr, logger Logger) {
  2376. if remoteAddr == nil {
  2377. remoteAddr = zeroTCPAddr
  2378. }
  2379. c := &fakeAddrer{
  2380. laddr: zeroTCPAddr,
  2381. raddr: remoteAddr,
  2382. }
  2383. if logger == nil {
  2384. logger = defaultLogger
  2385. }
  2386. ctx.Init2(c, logger, true)
  2387. req.CopyTo(&ctx.Request)
  2388. }
  2389. // Deadline returns the time when work done on behalf of this context
  2390. // should be canceled. Deadline returns ok==false when no deadline is
  2391. // set. Successive calls to Deadline return the same results.
  2392. //
  2393. // This method always returns 0, false and is only present to make
  2394. // RequestCtx implement the context interface.
  2395. func (ctx *RequestCtx) Deadline() (deadline time.Time, ok bool) {
  2396. return
  2397. }
  2398. // Done returns a channel that's closed when work done on behalf of this
  2399. // context should be canceled. Done may return nil if this context can
  2400. // never be canceled. Successive calls to Done return the same value.
  2401. //
  2402. // Note: Because creating a new channel for every request is just too expensive, so
  2403. // RequestCtx.s.done is only closed when the server is shutting down
  2404. func (ctx *RequestCtx) Done() <-chan struct{} {
  2405. return ctx.s.done
  2406. }
  2407. // Err returns a non-nil error value after Done is closed,
  2408. // successive calls to Err return the same error.
  2409. // If Done is not yet closed, Err returns nil.
  2410. // If Done is closed, Err returns a non-nil error explaining why:
  2411. // Canceled if the context was canceled (via server Shutdown)
  2412. // or DeadlineExceeded if the context's deadline passed.
  2413. //
  2414. // Note: Because creating a new channel for every request is just too expensive, so
  2415. // RequestCtx.s.done is only closed when the server is shutting down
  2416. func (ctx *RequestCtx) Err() error {
  2417. select {
  2418. case <-ctx.s.done:
  2419. return context.Canceled
  2420. default:
  2421. return nil
  2422. }
  2423. }
  2424. // Value returns the value associated with this context for key, or nil
  2425. // if no value is associated with key. Successive calls to Value with
  2426. // the same key returns the same result.
  2427. //
  2428. // This method is present to make RequestCtx implement the context interface.
  2429. // This method is the same as calling ctx.UserValue(key)
  2430. func (ctx *RequestCtx) Value(key interface{}) interface{} {
  2431. return ctx.UserValue(key)
  2432. }
  2433. var fakeServer = &Server{
  2434. // Initialize concurrencyCh for TimeoutHandler
  2435. concurrencyCh: make(chan struct{}, DefaultConcurrency),
  2436. }
  2437. type fakeAddrer struct {
  2438. net.Conn
  2439. laddr net.Addr
  2440. raddr net.Addr
  2441. }
  2442. func (fa *fakeAddrer) RemoteAddr() net.Addr {
  2443. return fa.raddr
  2444. }
  2445. func (fa *fakeAddrer) LocalAddr() net.Addr {
  2446. return fa.laddr
  2447. }
  2448. func (fa *fakeAddrer) Read(p []byte) (int, error) {
  2449. // developer sanity-check
  2450. panic("BUG: unexpected Read call")
  2451. }
  2452. func (fa *fakeAddrer) Write(p []byte) (int, error) {
  2453. // developer sanity-check
  2454. panic("BUG: unexpected Write call")
  2455. }
  2456. func (fa *fakeAddrer) Close() error {
  2457. // developer sanity-check
  2458. panic("BUG: unexpected Close call")
  2459. }
  2460. func (s *Server) releaseCtx(ctx *RequestCtx) {
  2461. if ctx.timeoutResponse != nil {
  2462. // developer sanity-check
  2463. panic("BUG: cannot release timed out RequestCtx")
  2464. }
  2465. ctx.reset()
  2466. s.ctxPool.Put(ctx)
  2467. }
  2468. func (s *Server) getServerName() string {
  2469. serverName := s.Name
  2470. if serverName == "" {
  2471. if !s.NoDefaultServerHeader {
  2472. serverName = defaultServerName
  2473. }
  2474. }
  2475. return serverName
  2476. }
  2477. func (s *Server) writeFastError(w io.Writer, statusCode int, msg string) {
  2478. w.Write(formatStatusLine(nil, strHTTP11, statusCode, s2b(StatusMessage(statusCode)))) //nolint:errcheck
  2479. server := s.getServerName()
  2480. if server != "" {
  2481. server = fmt.Sprintf("Server: %s\r\n", server)
  2482. }
  2483. date := ""
  2484. if !s.NoDefaultDate {
  2485. serverDateOnce.Do(updateServerDate)
  2486. date = fmt.Sprintf("Date: %s\r\n", serverDate.Load())
  2487. }
  2488. fmt.Fprintf(w, "Connection: close\r\n"+
  2489. server+
  2490. date+
  2491. "Content-Type: text/plain\r\n"+
  2492. "Content-Length: %d\r\n"+
  2493. "\r\n"+
  2494. "%s",
  2495. len(msg), msg)
  2496. }
  2497. func defaultErrorHandler(ctx *RequestCtx, err error) {
  2498. if _, ok := err.(*ErrSmallBuffer); ok {
  2499. ctx.Error("Too big request header", StatusRequestHeaderFieldsTooLarge)
  2500. } else if netErr, ok := err.(*net.OpError); ok && netErr.Timeout() {
  2501. ctx.Error("Request timeout", StatusRequestTimeout)
  2502. } else {
  2503. ctx.Error("Error when parsing request", StatusBadRequest)
  2504. }
  2505. }
  2506. func (s *Server) writeErrorResponse(bw *bufio.Writer, ctx *RequestCtx, serverName string, err error) *bufio.Writer {
  2507. errorHandler := defaultErrorHandler
  2508. if s.ErrorHandler != nil {
  2509. errorHandler = s.ErrorHandler
  2510. }
  2511. errorHandler(ctx, err)
  2512. if serverName != "" {
  2513. ctx.Response.Header.SetServer(serverName)
  2514. }
  2515. ctx.SetConnectionClose()
  2516. if bw == nil {
  2517. bw = acquireWriter(ctx)
  2518. }
  2519. writeResponse(ctx, bw) //nolint:errcheck
  2520. ctx.Response.Reset()
  2521. bw.Flush()
  2522. return bw
  2523. }
  2524. func (s *Server) trackConn(c net.Conn, state ConnState) {
  2525. s.idleConnsMu.Lock()
  2526. switch state {
  2527. case StateIdle:
  2528. if s.idleConns == nil {
  2529. s.idleConns = make(map[net.Conn]time.Time)
  2530. }
  2531. s.idleConns[c] = time.Now()
  2532. case StateNew:
  2533. if s.idleConns == nil {
  2534. s.idleConns = make(map[net.Conn]time.Time)
  2535. }
  2536. // Count the connection as Idle after 5 seconds.
  2537. // Same as net/http.Server: https://github.com/golang/go/blob/85d7bab91d9a3ed1f76842e4328973ea75efef54/src/net/http/server.go#L2834-L2836
  2538. s.idleConns[c] = time.Now().Add(time.Second * 5)
  2539. default:
  2540. delete(s.idleConns, c)
  2541. }
  2542. s.idleConnsMu.Unlock()
  2543. }
  2544. func (s *Server) closeIdleConns() {
  2545. s.idleConnsMu.Lock()
  2546. now := time.Now()
  2547. for c, t := range s.idleConns {
  2548. if now.Sub(t) >= 0 {
  2549. _ = c.Close()
  2550. delete(s.idleConns, c)
  2551. }
  2552. }
  2553. s.idleConnsMu.Unlock()
  2554. }
  2555. // A ConnState represents the state of a client connection to a server.
  2556. // It's used by the optional Server.ConnState hook.
  2557. type ConnState int
  2558. const (
  2559. // StateNew represents a new connection that is expected to
  2560. // send a request immediately. Connections begin at this
  2561. // state and then transition to either StateActive or
  2562. // StateClosed.
  2563. StateNew ConnState = iota
  2564. // StateActive represents a connection that has read 1 or more
  2565. // bytes of a request. The Server.ConnState hook for
  2566. // StateActive fires before the request has entered a handler
  2567. // and doesn't fire again until the request has been
  2568. // handled. After the request is handled, the state
  2569. // transitions to StateClosed, StateHijacked, or StateIdle.
  2570. // For HTTP/2, StateActive fires on the transition from zero
  2571. // to one active request, and only transitions away once all
  2572. // active requests are complete. That means that ConnState
  2573. // cannot be used to do per-request work; ConnState only notes
  2574. // the overall state of the connection.
  2575. StateActive
  2576. // StateIdle represents a connection that has finished
  2577. // handling a request and is in the keep-alive state, waiting
  2578. // for a new request. Connections transition from StateIdle
  2579. // to either StateActive or StateClosed.
  2580. StateIdle
  2581. // StateHijacked represents a hijacked connection.
  2582. // This is a terminal state. It does not transition to StateClosed.
  2583. StateHijacked
  2584. // StateClosed represents a closed connection.
  2585. // This is a terminal state. Hijacked connections do not
  2586. // transition to StateClosed.
  2587. StateClosed
  2588. )
  2589. var stateName = map[ConnState]string{
  2590. StateNew: "new",
  2591. StateActive: "active",
  2592. StateIdle: "idle",
  2593. StateHijacked: "hijacked",
  2594. StateClosed: "closed",
  2595. }
  2596. func (c ConnState) String() string {
  2597. return stateName[c]
  2598. }