server.go 85 KB

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