app.go 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118
  1. // ⚡️ Fiber is an Express inspired web framework written in Go with ☕️
  2. // 🤖 Github Repository: https://github.com/gofiber/fiber
  3. // 📌 API Documentation: https://docs.gofiber.io
  4. // Package fiber is an Express inspired web framework built on top of Fasthttp,
  5. // the fastest HTTP engine for Go. Designed to ease things up for fast
  6. // development with zero memory allocation and performance in mind.
  7. package fiber
  8. import (
  9. "bufio"
  10. "context"
  11. "encoding/json"
  12. "encoding/xml"
  13. "errors"
  14. "fmt"
  15. "net"
  16. "net/http"
  17. "net/http/httputil"
  18. "reflect"
  19. "strconv"
  20. "strings"
  21. "sync"
  22. "time"
  23. "github.com/gofiber/fiber/v2/log"
  24. "github.com/gofiber/fiber/v2/utils"
  25. "github.com/valyala/fasthttp"
  26. )
  27. // Version of current fiber package
  28. const Version = "2.50.0"
  29. // Handler defines a function to serve HTTP requests.
  30. type Handler = func(*Ctx) error
  31. // Map is a shortcut for map[string]interface{}, useful for JSON returns
  32. type Map map[string]interface{}
  33. // Storage interface for communicating with different database/key-value
  34. // providers
  35. type Storage interface {
  36. // Get gets the value for the given key.
  37. // `nil, nil` is returned when the key does not exist
  38. Get(key string) ([]byte, error)
  39. // Set stores the given value for the given key along
  40. // with an expiration value, 0 means no expiration.
  41. // Empty key or value will be ignored without an error.
  42. Set(key string, val []byte, exp time.Duration) error
  43. // Delete deletes the value for the given key.
  44. // It returns no error if the storage does not contain the key,
  45. Delete(key string) error
  46. // Reset resets the storage and delete all keys.
  47. Reset() error
  48. // Close closes the storage and will stop any running garbage
  49. // collectors and open connections.
  50. Close() error
  51. }
  52. // ErrorHandler defines a function that will process all errors
  53. // returned from any handlers in the stack
  54. //
  55. // cfg := fiber.Config{}
  56. // cfg.ErrorHandler = func(c *Ctx, err error) error {
  57. // code := StatusInternalServerError
  58. // var e *fiber.Error
  59. // if errors.As(err, &e) {
  60. // code = e.Code
  61. // }
  62. // c.Set(HeaderContentType, MIMETextPlainCharsetUTF8)
  63. // return c.Status(code).SendString(err.Error())
  64. // }
  65. // app := fiber.New(cfg)
  66. type ErrorHandler = func(*Ctx, error) error
  67. // Error represents an error that occurred while handling a request.
  68. type Error struct {
  69. Code int `json:"code"`
  70. Message string `json:"message"`
  71. }
  72. // App denotes the Fiber application.
  73. type App struct {
  74. mutex sync.Mutex
  75. // Route stack divided by HTTP methods
  76. stack [][]*Route
  77. // Route stack divided by HTTP methods and route prefixes
  78. treeStack []map[string][]*Route
  79. // contains the information if the route stack has been changed to build the optimized tree
  80. routesRefreshed bool
  81. // Amount of registered routes
  82. routesCount uint32
  83. // Amount of registered handlers
  84. handlersCount uint32
  85. // Ctx pool
  86. pool sync.Pool
  87. // Fasthttp server
  88. server *fasthttp.Server
  89. // App config
  90. config Config
  91. // Converts string to a byte slice
  92. getBytes func(s string) (b []byte)
  93. // Converts byte slice to a string
  94. getString func(b []byte) string
  95. // Hooks
  96. hooks *Hooks
  97. // Latest route & group
  98. latestRoute *Route
  99. // TLS handler
  100. tlsHandler *TLSHandler
  101. // Mount fields
  102. mountFields *mountFields
  103. // Indicates if the value was explicitly configured
  104. configured Config
  105. }
  106. // Config is a struct holding the server settings.
  107. type Config struct {
  108. // When set to true, this will spawn multiple Go processes listening on the same port.
  109. //
  110. // Default: false
  111. Prefork bool `json:"prefork"`
  112. // Enables the "Server: value" HTTP header.
  113. //
  114. // Default: ""
  115. ServerHeader string `json:"server_header"`
  116. // When set to true, the router treats "/foo" and "/foo/" as different.
  117. // By default this is disabled and both "/foo" and "/foo/" will execute the same handler.
  118. //
  119. // Default: false
  120. StrictRouting bool `json:"strict_routing"`
  121. // When set to true, enables case sensitive routing.
  122. // E.g. "/FoO" and "/foo" are treated as different routes.
  123. // By default this is disabled and both "/FoO" and "/foo" will execute the same handler.
  124. //
  125. // Default: false
  126. CaseSensitive bool `json:"case_sensitive"`
  127. // When set to true, this relinquishes the 0-allocation promise in certain
  128. // cases in order to access the handler values (e.g. request bodies) in an
  129. // immutable fashion so that these values are available even if you return
  130. // from handler.
  131. //
  132. // Default: false
  133. Immutable bool `json:"immutable"`
  134. // When set to true, converts all encoded characters in the route back
  135. // before setting the path for the context, so that the routing,
  136. // the returning of the current url from the context `ctx.Path()`
  137. // and the parameters `ctx.Params(%key%)` with decoded characters will work
  138. //
  139. // Default: false
  140. UnescapePath bool `json:"unescape_path"`
  141. // Enable or disable ETag header generation, since both weak and strong etags are generated
  142. // using the same hashing method (CRC-32). Weak ETags are the default when enabled.
  143. //
  144. // Default: false
  145. ETag bool `json:"etag"`
  146. // Max body size that the server accepts.
  147. // -1 will decline any body size
  148. //
  149. // Default: 4 * 1024 * 1024
  150. BodyLimit int `json:"body_limit"`
  151. // Maximum number of concurrent connections.
  152. //
  153. // Default: 256 * 1024
  154. Concurrency int `json:"concurrency"`
  155. // Views is the interface that wraps the Render function.
  156. //
  157. // Default: nil
  158. Views Views `json:"-"`
  159. // Views Layout is the global layout for all template render until override on Render function.
  160. //
  161. // Default: ""
  162. ViewsLayout string `json:"views_layout"`
  163. // PassLocalsToViews Enables passing of the locals set on a fiber.Ctx to the template engine
  164. //
  165. // Default: false
  166. PassLocalsToViews bool `json:"pass_locals_to_views"`
  167. // The amount of time allowed to read the full request including body.
  168. // It is reset after the request handler has returned.
  169. // The connection's read deadline is reset when the connection opens.
  170. //
  171. // Default: unlimited
  172. ReadTimeout time.Duration `json:"read_timeout"`
  173. // The maximum duration before timing out writes of the response.
  174. // It is reset after the request handler has returned.
  175. //
  176. // Default: unlimited
  177. WriteTimeout time.Duration `json:"write_timeout"`
  178. // The maximum amount of time to wait for the next request when keep-alive is enabled.
  179. // If IdleTimeout is zero, the value of ReadTimeout is used.
  180. //
  181. // Default: unlimited
  182. IdleTimeout time.Duration `json:"idle_timeout"`
  183. // Per-connection buffer size for requests' reading.
  184. // This also limits the maximum header size.
  185. // Increase this buffer if your clients send multi-KB RequestURIs
  186. // and/or multi-KB headers (for example, BIG cookies).
  187. //
  188. // Default: 4096
  189. ReadBufferSize int `json:"read_buffer_size"`
  190. // Per-connection buffer size for responses' writing.
  191. //
  192. // Default: 4096
  193. WriteBufferSize int `json:"write_buffer_size"`
  194. // CompressedFileSuffix adds suffix to the original file name and
  195. // tries saving the resulting compressed file under the new file name.
  196. //
  197. // Default: ".fiber.gz"
  198. CompressedFileSuffix string `json:"compressed_file_suffix"`
  199. // ProxyHeader will enable c.IP() to return the value of the given header key
  200. // By default c.IP() will return the Remote IP from the TCP connection
  201. // This property can be useful if you are behind a load balancer: X-Forwarded-*
  202. // NOTE: headers are easily spoofed and the detected IP addresses are unreliable.
  203. //
  204. // Default: ""
  205. ProxyHeader string `json:"proxy_header"`
  206. // GETOnly rejects all non-GET requests if set to true.
  207. // This option is useful as anti-DoS protection for servers
  208. // accepting only GET requests. The request size is limited
  209. // by ReadBufferSize if GETOnly is set.
  210. //
  211. // Default: false
  212. GETOnly bool `json:"get_only"`
  213. // ErrorHandler is executed when an error is returned from fiber.Handler.
  214. //
  215. // Default: DefaultErrorHandler
  216. ErrorHandler ErrorHandler `json:"-"`
  217. // When set to true, disables keep-alive connections.
  218. // The server will close incoming connections after sending the first response to client.
  219. //
  220. // Default: false
  221. DisableKeepalive bool `json:"disable_keepalive"`
  222. // When set to true, causes the default date header to be excluded from the response.
  223. //
  224. // Default: false
  225. DisableDefaultDate bool `json:"disable_default_date"`
  226. // When set to true, causes the default Content-Type header to be excluded from the response.
  227. //
  228. // Default: false
  229. DisableDefaultContentType bool `json:"disable_default_content_type"`
  230. // When set to true, disables header normalization.
  231. // By default all header names are normalized: conteNT-tYPE -> Content-Type.
  232. //
  233. // Default: false
  234. DisableHeaderNormalizing bool `json:"disable_header_normalizing"`
  235. // When set to true, it will not print out the «Fiber» ASCII art and listening address.
  236. //
  237. // Default: false
  238. DisableStartupMessage bool `json:"disable_startup_message"`
  239. // This function allows to setup app name for the app
  240. //
  241. // Default: nil
  242. AppName string `json:"app_name"`
  243. // StreamRequestBody enables request body streaming,
  244. // and calls the handler sooner when given body is
  245. // larger then the current limit.
  246. StreamRequestBody bool
  247. // Will not pre parse Multipart Form data if set to true.
  248. //
  249. // This option is useful for servers that desire to treat
  250. // multipart form data as a binary blob, or choose when to parse the data.
  251. //
  252. // Server pre parses multipart form data by default.
  253. DisablePreParseMultipartForm bool
  254. // Aggressively reduces memory usage at the cost of higher CPU usage
  255. // if set to true.
  256. //
  257. // Try enabling this option only if the server consumes too much memory
  258. // serving mostly idle keep-alive connections. This may reduce memory
  259. // usage by more than 50%.
  260. //
  261. // Default: false
  262. ReduceMemoryUsage bool `json:"reduce_memory_usage"`
  263. // FEATURE: v2.3.x
  264. // The router executes the same handler by default if StrictRouting or CaseSensitive is disabled.
  265. // Enabling RedirectFixedPath will change this behavior into a client redirect to the original route path.
  266. // Using the status code 301 for GET requests and 308 for all other request methods.
  267. //
  268. // Default: false
  269. // RedirectFixedPath bool
  270. // When set by an external client of Fiber it will use the provided implementation of a
  271. // JSONMarshal
  272. //
  273. // Allowing for flexibility in using another json library for encoding
  274. // Default: json.Marshal
  275. JSONEncoder utils.JSONMarshal `json:"-"`
  276. // When set by an external client of Fiber it will use the provided implementation of a
  277. // JSONUnmarshal
  278. //
  279. // Allowing for flexibility in using another json library for decoding
  280. // Default: json.Unmarshal
  281. JSONDecoder utils.JSONUnmarshal `json:"-"`
  282. // XMLEncoder set by an external client of Fiber it will use the provided implementation of a
  283. // XMLMarshal
  284. //
  285. // Allowing for flexibility in using another XML library for encoding
  286. // Default: xml.Marshal
  287. XMLEncoder utils.XMLMarshal `json:"-"`
  288. // Known networks are "tcp", "tcp4" (IPv4-only), "tcp6" (IPv6-only)
  289. // WARNING: When prefork is set to true, only "tcp4" and "tcp6" can be chose.
  290. //
  291. // Default: NetworkTCP4
  292. Network string
  293. // If you find yourself behind some sort of proxy, like a load balancer,
  294. // then certain header information may be sent to you using special X-Forwarded-* headers or the Forwarded header.
  295. // For example, the Host HTTP header is usually used to return the requested host.
  296. // But when you’re behind a proxy, the actual host may be stored in an X-Forwarded-Host header.
  297. //
  298. // If you are behind a proxy, you should enable TrustedProxyCheck to prevent header spoofing.
  299. // If you enable EnableTrustedProxyCheck and leave TrustedProxies empty Fiber will skip
  300. // all headers that could be spoofed.
  301. // If request ip in TrustedProxies whitelist then:
  302. // 1. c.Protocol() get value from X-Forwarded-Proto, X-Forwarded-Protocol, X-Forwarded-Ssl or X-Url-Scheme header
  303. // 2. c.IP() get value from ProxyHeader header.
  304. // 3. c.Hostname() get value from X-Forwarded-Host header
  305. // But if request ip NOT in Trusted Proxies whitelist then:
  306. // 1. c.Protocol() WON't get value from X-Forwarded-Proto, X-Forwarded-Protocol, X-Forwarded-Ssl or X-Url-Scheme header,
  307. // will return https in case when tls connection is handled by the app, of http otherwise
  308. // 2. c.IP() WON'T get value from ProxyHeader header, will return RemoteIP() from fasthttp context
  309. // 3. c.Hostname() WON'T get value from X-Forwarded-Host header, fasthttp.Request.URI().Host()
  310. // will be used to get the hostname.
  311. //
  312. // Default: false
  313. EnableTrustedProxyCheck bool `json:"enable_trusted_proxy_check"`
  314. // Read EnableTrustedProxyCheck doc.
  315. //
  316. // Default: []string
  317. TrustedProxies []string `json:"trusted_proxies"`
  318. trustedProxiesMap map[string]struct{}
  319. trustedProxyRanges []*net.IPNet
  320. // If set to true, c.IP() and c.IPs() will validate IP addresses before returning them.
  321. // Also, c.IP() will return only the first valid IP rather than just the raw header
  322. // WARNING: this has a performance cost associated with it.
  323. //
  324. // Default: false
  325. EnableIPValidation bool `json:"enable_ip_validation"`
  326. // If set to true, will print all routes with their method, path and handler.
  327. // Default: false
  328. EnablePrintRoutes bool `json:"enable_print_routes"`
  329. // You can define custom color scheme. They'll be used for startup message, route list and some middlewares.
  330. //
  331. // Optional. Default: DefaultColors
  332. ColorScheme Colors `json:"color_scheme"`
  333. // RequestMethods provides customizibility for HTTP methods. You can add/remove methods as you wish.
  334. //
  335. // Optional. Default: DefaultMethods
  336. RequestMethods []string
  337. // EnableSplittingOnParsers splits the query/body/header parameters by comma when it's true.
  338. // For example, you can use it to parse multiple values from a query parameter like this:
  339. // /api?foo=bar,baz == foo[]=bar&foo[]=baz
  340. //
  341. // Optional. Default: false
  342. EnableSplittingOnParsers bool `json:"enable_splitting_on_parsers"`
  343. }
  344. // Static defines configuration options when defining static assets.
  345. type Static struct {
  346. // When set to true, the server tries minimizing CPU usage by caching compressed files.
  347. // This works differently than the github.com/gofiber/compression middleware.
  348. // Optional. Default value false
  349. Compress bool `json:"compress"`
  350. // When set to true, enables byte range requests.
  351. // Optional. Default value false
  352. ByteRange bool `json:"byte_range"`
  353. // When set to true, enables directory browsing.
  354. // Optional. Default value false.
  355. Browse bool `json:"browse"`
  356. // When set to true, enables direct download.
  357. // Optional. Default value false.
  358. Download bool `json:"download"`
  359. // The name of the index file for serving a directory.
  360. // Optional. Default value "index.html".
  361. Index string `json:"index"`
  362. // Expiration duration for inactive file handlers.
  363. // Use a negative time.Duration to disable it.
  364. //
  365. // Optional. Default value 10 * time.Second.
  366. CacheDuration time.Duration `json:"cache_duration"`
  367. // The value for the Cache-Control HTTP-header
  368. // that is set on the file response. MaxAge is defined in seconds.
  369. //
  370. // Optional. Default value 0.
  371. MaxAge int `json:"max_age"`
  372. // ModifyResponse defines a function that allows you to alter the response.
  373. //
  374. // Optional. Default: nil
  375. ModifyResponse Handler
  376. // Next defines a function to skip this middleware when returned true.
  377. //
  378. // Optional. Default: nil
  379. Next func(c *Ctx) bool
  380. }
  381. // RouteMessage is some message need to be print when server starts
  382. type RouteMessage struct {
  383. name string
  384. method string
  385. path string
  386. handlers string
  387. }
  388. // Default Config values
  389. const (
  390. DefaultBodyLimit = 4 * 1024 * 1024
  391. DefaultConcurrency = 256 * 1024
  392. DefaultReadBufferSize = 4096
  393. DefaultWriteBufferSize = 4096
  394. DefaultCompressedFileSuffix = ".fiber.gz"
  395. )
  396. // HTTP methods enabled by default
  397. var DefaultMethods = []string{
  398. MethodGet,
  399. MethodHead,
  400. MethodPost,
  401. MethodPut,
  402. MethodDelete,
  403. MethodConnect,
  404. MethodOptions,
  405. MethodTrace,
  406. MethodPatch,
  407. }
  408. // DefaultErrorHandler that process return errors from handlers
  409. func DefaultErrorHandler(c *Ctx, err error) error {
  410. code := StatusInternalServerError
  411. var e *Error
  412. if errors.As(err, &e) {
  413. code = e.Code
  414. }
  415. c.Set(HeaderContentType, MIMETextPlainCharsetUTF8)
  416. return c.Status(code).SendString(err.Error())
  417. }
  418. // New creates a new Fiber named instance.
  419. //
  420. // app := fiber.New()
  421. //
  422. // You can pass optional configuration options by passing a Config struct:
  423. //
  424. // app := fiber.New(fiber.Config{
  425. // Prefork: true,
  426. // ServerHeader: "Fiber",
  427. // })
  428. func New(config ...Config) *App {
  429. // Create a new app
  430. app := &App{
  431. // Create Ctx pool
  432. pool: sync.Pool{
  433. New: func() interface{} {
  434. return new(Ctx)
  435. },
  436. },
  437. // Create config
  438. config: Config{},
  439. getBytes: utils.UnsafeBytes,
  440. getString: utils.UnsafeString,
  441. latestRoute: &Route{},
  442. }
  443. // Define hooks
  444. app.hooks = newHooks(app)
  445. // Define mountFields
  446. app.mountFields = newMountFields(app)
  447. // Override config if provided
  448. if len(config) > 0 {
  449. app.config = config[0]
  450. }
  451. // Initialize configured before defaults are set
  452. app.configured = app.config
  453. if app.config.ETag {
  454. if !IsChild() {
  455. log.Warn("Config.ETag is deprecated since v2.0.6, please use 'middleware/etag'.")
  456. }
  457. }
  458. // Override default values
  459. if app.config.BodyLimit == 0 {
  460. app.config.BodyLimit = DefaultBodyLimit
  461. }
  462. if app.config.Concurrency <= 0 {
  463. app.config.Concurrency = DefaultConcurrency
  464. }
  465. if app.config.ReadBufferSize <= 0 {
  466. app.config.ReadBufferSize = DefaultReadBufferSize
  467. }
  468. if app.config.WriteBufferSize <= 0 {
  469. app.config.WriteBufferSize = DefaultWriteBufferSize
  470. }
  471. if app.config.CompressedFileSuffix == "" {
  472. app.config.CompressedFileSuffix = DefaultCompressedFileSuffix
  473. }
  474. if app.config.Immutable {
  475. app.getBytes, app.getString = getBytesImmutable, getStringImmutable
  476. }
  477. if app.config.ErrorHandler == nil {
  478. app.config.ErrorHandler = DefaultErrorHandler
  479. }
  480. if app.config.JSONEncoder == nil {
  481. app.config.JSONEncoder = json.Marshal
  482. }
  483. if app.config.JSONDecoder == nil {
  484. app.config.JSONDecoder = json.Unmarshal
  485. }
  486. if app.config.XMLEncoder == nil {
  487. app.config.XMLEncoder = xml.Marshal
  488. }
  489. if app.config.Network == "" {
  490. app.config.Network = NetworkTCP4
  491. }
  492. if len(app.config.RequestMethods) == 0 {
  493. app.config.RequestMethods = DefaultMethods
  494. }
  495. app.config.trustedProxiesMap = make(map[string]struct{}, len(app.config.TrustedProxies))
  496. for _, ipAddress := range app.config.TrustedProxies {
  497. app.handleTrustedProxy(ipAddress)
  498. }
  499. // Create router stack
  500. app.stack = make([][]*Route, len(app.config.RequestMethods))
  501. app.treeStack = make([]map[string][]*Route, len(app.config.RequestMethods))
  502. // Override colors
  503. app.config.ColorScheme = defaultColors(app.config.ColorScheme)
  504. // Init app
  505. app.init()
  506. // Return app
  507. return app
  508. }
  509. // Adds an ip address to trustedProxyRanges or trustedProxiesMap based on whether it is an IP range or not
  510. func (app *App) handleTrustedProxy(ipAddress string) {
  511. if strings.Contains(ipAddress, "/") {
  512. _, ipNet, err := net.ParseCIDR(ipAddress)
  513. if err != nil {
  514. log.Warnf("IP range %q could not be parsed: %v", ipAddress, err)
  515. } else {
  516. app.config.trustedProxyRanges = append(app.config.trustedProxyRanges, ipNet)
  517. }
  518. } else {
  519. app.config.trustedProxiesMap[ipAddress] = struct{}{}
  520. }
  521. }
  522. // SetTLSHandler You can use SetTLSHandler to use ClientHelloInfo when using TLS with Listener.
  523. func (app *App) SetTLSHandler(tlsHandler *TLSHandler) {
  524. // Attach the tlsHandler to the config
  525. app.mutex.Lock()
  526. app.tlsHandler = tlsHandler
  527. app.mutex.Unlock()
  528. }
  529. // Name Assign name to specific route.
  530. func (app *App) Name(name string) Router {
  531. app.mutex.Lock()
  532. defer app.mutex.Unlock()
  533. for _, routes := range app.stack {
  534. for _, route := range routes {
  535. if route.Path == app.latestRoute.Path {
  536. route.Name = name
  537. if route.group != nil {
  538. route.Name = route.group.name + route.Name
  539. }
  540. }
  541. }
  542. }
  543. if err := app.hooks.executeOnNameHooks(*app.latestRoute); err != nil {
  544. panic(err)
  545. }
  546. return app
  547. }
  548. // GetRoute Get route by name
  549. func (app *App) GetRoute(name string) Route {
  550. for _, routes := range app.stack {
  551. for _, route := range routes {
  552. if route.Name == name {
  553. return *route
  554. }
  555. }
  556. }
  557. return Route{}
  558. }
  559. // GetRoutes Get all routes. When filterUseOption equal to true, it will filter the routes registered by the middleware.
  560. func (app *App) GetRoutes(filterUseOption ...bool) []Route {
  561. var rs []Route
  562. var filterUse bool
  563. if len(filterUseOption) != 0 {
  564. filterUse = filterUseOption[0]
  565. }
  566. for _, routes := range app.stack {
  567. for _, route := range routes {
  568. if filterUse && route.use {
  569. continue
  570. }
  571. rs = append(rs, *route)
  572. }
  573. }
  574. return rs
  575. }
  576. // Use registers a middleware route that will match requests
  577. // with the provided prefix (which is optional and defaults to "/").
  578. //
  579. // app.Use(func(c *fiber.Ctx) error {
  580. // return c.Next()
  581. // })
  582. // app.Use("/api", func(c *fiber.Ctx) error {
  583. // return c.Next()
  584. // })
  585. // app.Use("/api", handler, func(c *fiber.Ctx) error {
  586. // return c.Next()
  587. // })
  588. //
  589. // This method will match all HTTP verbs: GET, POST, PUT, HEAD etc...
  590. func (app *App) Use(args ...interface{}) Router {
  591. var prefix string
  592. var prefixes []string
  593. var handlers []Handler
  594. for i := 0; i < len(args); i++ {
  595. switch arg := args[i].(type) {
  596. case string:
  597. prefix = arg
  598. case []string:
  599. prefixes = arg
  600. case Handler:
  601. handlers = append(handlers, arg)
  602. default:
  603. panic(fmt.Sprintf("use: invalid handler %v\n", reflect.TypeOf(arg)))
  604. }
  605. }
  606. if len(prefixes) == 0 {
  607. prefixes = append(prefixes, prefix)
  608. }
  609. for _, prefix := range prefixes {
  610. app.register(methodUse, prefix, nil, handlers...)
  611. }
  612. return app
  613. }
  614. // Get registers a route for GET methods that requests a representation
  615. // of the specified resource. Requests using GET should only retrieve data.
  616. func (app *App) Get(path string, handlers ...Handler) Router {
  617. return app.Head(path, handlers...).Add(MethodGet, path, handlers...)
  618. }
  619. // Head registers a route for HEAD methods that asks for a response identical
  620. // to that of a GET request, but without the response body.
  621. func (app *App) Head(path string, handlers ...Handler) Router {
  622. return app.Add(MethodHead, path, handlers...)
  623. }
  624. // Post registers a route for POST methods that is used to submit an entity to the
  625. // specified resource, often causing a change in state or side effects on the server.
  626. func (app *App) Post(path string, handlers ...Handler) Router {
  627. return app.Add(MethodPost, path, handlers...)
  628. }
  629. // Put registers a route for PUT methods that replaces all current representations
  630. // of the target resource with the request payload.
  631. func (app *App) Put(path string, handlers ...Handler) Router {
  632. return app.Add(MethodPut, path, handlers...)
  633. }
  634. // Delete registers a route for DELETE methods that deletes the specified resource.
  635. func (app *App) Delete(path string, handlers ...Handler) Router {
  636. return app.Add(MethodDelete, path, handlers...)
  637. }
  638. // Connect registers a route for CONNECT methods that establishes a tunnel to the
  639. // server identified by the target resource.
  640. func (app *App) Connect(path string, handlers ...Handler) Router {
  641. return app.Add(MethodConnect, path, handlers...)
  642. }
  643. // Options registers a route for OPTIONS methods that is used to describe the
  644. // communication options for the target resource.
  645. func (app *App) Options(path string, handlers ...Handler) Router {
  646. return app.Add(MethodOptions, path, handlers...)
  647. }
  648. // Trace registers a route for TRACE methods that performs a message loop-back
  649. // test along the path to the target resource.
  650. func (app *App) Trace(path string, handlers ...Handler) Router {
  651. return app.Add(MethodTrace, path, handlers...)
  652. }
  653. // Patch registers a route for PATCH methods that is used to apply partial
  654. // modifications to a resource.
  655. func (app *App) Patch(path string, handlers ...Handler) Router {
  656. return app.Add(MethodPatch, path, handlers...)
  657. }
  658. // Add allows you to specify a HTTP method to register a route
  659. func (app *App) Add(method, path string, handlers ...Handler) Router {
  660. app.register(method, path, nil, handlers...)
  661. return app
  662. }
  663. // Static will create a file server serving static files
  664. func (app *App) Static(prefix, root string, config ...Static) Router {
  665. app.registerStatic(prefix, root, config...)
  666. return app
  667. }
  668. // All will register the handler on all HTTP methods
  669. func (app *App) All(path string, handlers ...Handler) Router {
  670. for _, method := range app.config.RequestMethods {
  671. _ = app.Add(method, path, handlers...)
  672. }
  673. return app
  674. }
  675. // Group is used for Routes with common prefix to define a new sub-router with optional middleware.
  676. //
  677. // api := app.Group("/api")
  678. // api.Get("/users", handler)
  679. func (app *App) Group(prefix string, handlers ...Handler) Router {
  680. grp := &Group{Prefix: prefix, app: app}
  681. if len(handlers) > 0 {
  682. app.register(methodUse, prefix, grp, handlers...)
  683. }
  684. if err := app.hooks.executeOnGroupHooks(*grp); err != nil {
  685. panic(err)
  686. }
  687. return grp
  688. }
  689. // Route is used to define routes with a common prefix inside the common function.
  690. // Uses Group method to define new sub-router.
  691. func (app *App) Route(prefix string, fn func(router Router), name ...string) Router {
  692. // Create new group
  693. group := app.Group(prefix)
  694. if len(name) > 0 {
  695. group.Name(name[0])
  696. }
  697. // Define routes
  698. fn(group)
  699. return group
  700. }
  701. // Error makes it compatible with the `error` interface.
  702. func (e *Error) Error() string {
  703. return e.Message
  704. }
  705. // NewError creates a new Error instance with an optional message
  706. func NewError(code int, message ...string) *Error {
  707. err := &Error{
  708. Code: code,
  709. Message: utils.StatusMessage(code),
  710. }
  711. if len(message) > 0 {
  712. err.Message = message[0]
  713. }
  714. return err
  715. }
  716. // Config returns the app config as value ( read-only ).
  717. func (app *App) Config() Config {
  718. return app.config
  719. }
  720. // Handler returns the server handler.
  721. func (app *App) Handler() fasthttp.RequestHandler { //revive:disable-line:confusing-naming // Having both a Handler() (uppercase) and a handler() (lowercase) is fine. TODO: Use nolint:revive directive instead. See https://github.com/golangci/golangci-lint/issues/3476
  722. // prepare the server for the start
  723. app.startupProcess()
  724. return app.handler
  725. }
  726. // Stack returns the raw router stack.
  727. func (app *App) Stack() [][]*Route {
  728. return app.stack
  729. }
  730. // HandlersCount returns the amount of registered handlers.
  731. func (app *App) HandlersCount() uint32 {
  732. return app.handlersCount
  733. }
  734. // Shutdown gracefully shuts down the server without interrupting any active connections.
  735. // Shutdown works by first closing all open listeners and then waiting indefinitely for all connections to return to idle before shutting down.
  736. //
  737. // Make sure the program doesn't exit and waits instead for Shutdown to return.
  738. //
  739. // Shutdown does not close keepalive connections so its recommended to set ReadTimeout to something else than 0.
  740. func (app *App) Shutdown() error {
  741. return app.ShutdownWithContext(context.Background())
  742. }
  743. // ShutdownWithTimeout gracefully shuts down the server without interrupting any active connections. However, if the timeout is exceeded,
  744. // ShutdownWithTimeout will forcefully close any active connections.
  745. // ShutdownWithTimeout works by first closing all open listeners and then waiting for all connections to return to idle before shutting down.
  746. //
  747. // Make sure the program doesn't exit and waits instead for ShutdownWithTimeout to return.
  748. //
  749. // ShutdownWithTimeout does not close keepalive connections so its recommended to set ReadTimeout to something else than 0.
  750. func (app *App) ShutdownWithTimeout(timeout time.Duration) error {
  751. ctx, cancelFunc := context.WithTimeout(context.Background(), timeout)
  752. defer cancelFunc()
  753. return app.ShutdownWithContext(ctx)
  754. }
  755. // ShutdownWithContext shuts down the server including by force if the context's deadline is exceeded.
  756. //
  757. // Make sure the program doesn't exit and waits instead for ShutdownWithTimeout to return.
  758. //
  759. // ShutdownWithContext does not close keepalive connections so its recommended to set ReadTimeout to something else than 0.
  760. func (app *App) ShutdownWithContext(ctx context.Context) error {
  761. if app.hooks != nil {
  762. defer app.hooks.executeOnShutdownHooks()
  763. }
  764. app.mutex.Lock()
  765. defer app.mutex.Unlock()
  766. if app.server == nil {
  767. return fmt.Errorf("shutdown: server is not running")
  768. }
  769. return app.server.ShutdownWithContext(ctx)
  770. }
  771. // Server returns the underlying fasthttp server
  772. func (app *App) Server() *fasthttp.Server {
  773. return app.server
  774. }
  775. // Hooks returns the hook struct to register hooks.
  776. func (app *App) Hooks() *Hooks {
  777. return app.hooks
  778. }
  779. // Test is used for internal debugging by passing a *http.Request.
  780. // Timeout is optional and defaults to 1s, -1 will disable it completely.
  781. func (app *App) Test(req *http.Request, msTimeout ...int) (*http.Response, error) {
  782. // Set timeout
  783. timeout := 1000
  784. if len(msTimeout) > 0 {
  785. timeout = msTimeout[0]
  786. }
  787. // Add Content-Length if not provided with body
  788. if req.Body != http.NoBody && req.Header.Get(HeaderContentLength) == "" {
  789. req.Header.Add(HeaderContentLength, strconv.FormatInt(req.ContentLength, 10))
  790. }
  791. // Dump raw http request
  792. dump, err := httputil.DumpRequest(req, true)
  793. if err != nil {
  794. return nil, fmt.Errorf("failed to dump request: %w", err)
  795. }
  796. // Create test connection
  797. conn := new(testConn)
  798. // Write raw http request
  799. if _, err := conn.r.Write(dump); err != nil {
  800. return nil, fmt.Errorf("failed to write: %w", err)
  801. }
  802. // prepare the server for the start
  803. app.startupProcess()
  804. // Serve conn to server
  805. channel := make(chan error)
  806. go func() {
  807. var returned bool
  808. defer func() {
  809. if !returned {
  810. channel <- fmt.Errorf("runtime.Goexit() called in handler or server panic")
  811. }
  812. }()
  813. channel <- app.server.ServeConn(conn)
  814. returned = true
  815. }()
  816. // Wait for callback
  817. if timeout >= 0 {
  818. // With timeout
  819. select {
  820. case err = <-channel:
  821. case <-time.After(time.Duration(timeout) * time.Millisecond):
  822. return nil, fmt.Errorf("test: timeout error %vms", timeout)
  823. }
  824. } else {
  825. // Without timeout
  826. err = <-channel
  827. }
  828. // Check for errors
  829. if err != nil && !errors.Is(err, fasthttp.ErrGetOnly) {
  830. return nil, err
  831. }
  832. // Read response
  833. buffer := bufio.NewReader(&conn.w)
  834. // Convert raw http response to *http.Response
  835. res, err := http.ReadResponse(buffer, req)
  836. if err != nil {
  837. return nil, fmt.Errorf("failed to read response: %w", err)
  838. }
  839. return res, nil
  840. }
  841. type disableLogger struct{}
  842. func (*disableLogger) Printf(_ string, _ ...interface{}) {
  843. // fmt.Println(fmt.Sprintf(format, args...))
  844. }
  845. func (app *App) init() *App {
  846. // lock application
  847. app.mutex.Lock()
  848. // Only load templates if a view engine is specified
  849. if app.config.Views != nil {
  850. if err := app.config.Views.Load(); err != nil {
  851. log.Warnf("failed to load views: %v", err)
  852. }
  853. }
  854. // create fasthttp server
  855. app.server = &fasthttp.Server{
  856. Logger: &disableLogger{},
  857. LogAllErrors: false,
  858. ErrorHandler: app.serverErrorHandler,
  859. }
  860. // fasthttp server settings
  861. app.server.Handler = app.handler
  862. app.server.Name = app.config.ServerHeader
  863. app.server.Concurrency = app.config.Concurrency
  864. app.server.NoDefaultDate = app.config.DisableDefaultDate
  865. app.server.NoDefaultContentType = app.config.DisableDefaultContentType
  866. app.server.DisableHeaderNamesNormalizing = app.config.DisableHeaderNormalizing
  867. app.server.DisableKeepalive = app.config.DisableKeepalive
  868. app.server.MaxRequestBodySize = app.config.BodyLimit
  869. app.server.NoDefaultServerHeader = app.config.ServerHeader == ""
  870. app.server.ReadTimeout = app.config.ReadTimeout
  871. app.server.WriteTimeout = app.config.WriteTimeout
  872. app.server.IdleTimeout = app.config.IdleTimeout
  873. app.server.ReadBufferSize = app.config.ReadBufferSize
  874. app.server.WriteBufferSize = app.config.WriteBufferSize
  875. app.server.GetOnly = app.config.GETOnly
  876. app.server.ReduceMemoryUsage = app.config.ReduceMemoryUsage
  877. app.server.StreamRequestBody = app.config.StreamRequestBody
  878. app.server.DisablePreParseMultipartForm = app.config.DisablePreParseMultipartForm
  879. // unlock application
  880. app.mutex.Unlock()
  881. return app
  882. }
  883. // ErrorHandler is the application's method in charge of finding the
  884. // appropriate handler for the given request. It searches any mounted
  885. // sub fibers by their prefixes and if it finds a match, it uses that
  886. // error handler. Otherwise it uses the configured error handler for
  887. // the app, which if not set is the DefaultErrorHandler.
  888. func (app *App) ErrorHandler(ctx *Ctx, err error) error {
  889. var (
  890. mountedErrHandler ErrorHandler
  891. mountedPrefixParts int
  892. )
  893. for prefix, subApp := range app.mountFields.appList {
  894. if prefix != "" && strings.HasPrefix(ctx.path, prefix) {
  895. parts := len(strings.Split(prefix, "/"))
  896. if mountedPrefixParts <= parts {
  897. if subApp.configured.ErrorHandler != nil {
  898. mountedErrHandler = subApp.config.ErrorHandler
  899. }
  900. mountedPrefixParts = parts
  901. }
  902. }
  903. }
  904. if mountedErrHandler != nil {
  905. return mountedErrHandler(ctx, err)
  906. }
  907. return app.config.ErrorHandler(ctx, err)
  908. }
  909. // serverErrorHandler is a wrapper around the application's error handler method
  910. // user for the fasthttp server configuration. It maps a set of fasthttp errors to fiber
  911. // errors before calling the application's error handler method.
  912. func (app *App) serverErrorHandler(fctx *fasthttp.RequestCtx, err error) {
  913. c := app.AcquireCtx(fctx)
  914. defer app.ReleaseCtx(c)
  915. var (
  916. errNetOP *net.OpError
  917. netErr net.Error
  918. )
  919. switch {
  920. case errors.As(err, new(*fasthttp.ErrSmallBuffer)):
  921. err = ErrRequestHeaderFieldsTooLarge
  922. case errors.As(err, &errNetOP) && errNetOP.Timeout():
  923. err = ErrRequestTimeout
  924. case errors.As(err, &netErr):
  925. err = ErrBadGateway
  926. case errors.Is(err, fasthttp.ErrBodyTooLarge):
  927. err = ErrRequestEntityTooLarge
  928. case errors.Is(err, fasthttp.ErrGetOnly):
  929. err = ErrMethodNotAllowed
  930. case strings.Contains(err.Error(), "timeout"):
  931. err = ErrRequestTimeout
  932. default:
  933. err = NewError(StatusBadRequest, err.Error())
  934. }
  935. if catch := app.ErrorHandler(c, err); catch != nil {
  936. log.Errorf("serverErrorHandler: failed to call ErrorHandler: %v", catch)
  937. _ = c.SendStatus(StatusInternalServerError) //nolint:errcheck // It is fine to ignore the error here
  938. return
  939. }
  940. }
  941. // startupProcess Is the method which executes all the necessary processes just before the start of the server.
  942. func (app *App) startupProcess() *App {
  943. app.mutex.Lock()
  944. defer app.mutex.Unlock()
  945. app.mountStartupProcess()
  946. // build route tree stack
  947. app.buildTree()
  948. return app
  949. }
  950. // Run onListen hooks. If they return an error, panic.
  951. func (app *App) runOnListenHooks(listenData ListenData) {
  952. if err := app.hooks.executeOnListenHooks(listenData); err != nil {
  953. panic(err)
  954. }
  955. }