server.go 90 KB

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