server.go 84 KB

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