server.go 85 KB

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