description
The app instance conventionally denotes the Fiber application.

🚀 Application

Default

New

This method creates a new App named instance with a custom configuration.

  1. func New(config Config) *App
  1. package main
  2. import "github.com/gofiber/fiber"
  3. func main() {
  4. app := fiber.New(fiber.Config{
  5. Prefork: true,
  6. CaseSensitive: true,
  7. StrictRouting: true,
  8. ServerHeader: "Fiber",
  9. })
  10. // ...
  11. if err := app.Listen(":3000"); err != nil {
  12. println(err)
  13. }
  14. }

Config

When creating a new Fiber instance, you can use different configurations for your application.

  1. func main() {
  2. // Pass Settings creating a new instance
  3. app := fiber.New(&fiber.Settings{
  4. Prefork: true,
  5. CaseSensitive: true,
  6. StrictRouting: true,
  7. ServerHeader: "Fiber",
  8. })
  9. // ...
  10. app.Listen(3000)
  11. }

Or change the settings after initializing an app.

  1. func main() {
  2. app := fiber.New()
  3. // Or change Settings after creating an instance
  4. app.Settings.Prefork = true
  5. app.Settings.CaseSensitive = true
  6. app.Settings.StrictRouting = true
  7. app.Settings.ServerHeader = "Fiber"
  8. // ...
  9. app.Listen(3000)
  10. }

Settings fields

PropertyTypeDescriptionDefault
PreforkboolEnables use of theSO_REUSEPORTsocket option. This will spawn multiple Go processes listening on the same port. learn more about socket sharding.false
ServerHeaderstringEnables the Server HTTP header with the given value.“”
StrictRoutingboolWhen enabled, the router treats /foo and /foo/ as different. Otherwise, the router treats /foo and /foo/ as the same.false
CaseSensitiveboolWhen enabled, /Foo and /foo are different routes. When disabled, /Fooand /foo are treated the same.false
ImmutableboolWhen enabled, all values returned by context methods are immutable. By default, they are valid until you return from the handler; see the issue #185.false
UnescapePathboolConverts all encoded characters in the route back before setting the path for the context, so that the routing can also work with urlencoded special charactersfalse
BodyLimitintSets the maximum allowed size for a request body, if the size exceeds the configured limit, it sends 413 - Request Entity Too Large response.4 1024 1024
CompressedFileSuffixstringAdds suffix to the original file name and tries saving the resulting compressed file under the new file name.“.fiber.gz”
ConcurrencyintMaximum number of concurrent connections.256 * 1024
DisableKeepaliveboolDisable keep-alive connections, the server will close incoming connections after sending the first response to clientfalse
DisableDefaultDateboolWhen set to true causes the default date header to be excluded from the response.false
DisableDefaultContentTypeboolWhen set to true, causes the default Content-Type header to be excluded from the Response.false
DisableStartupMessageboolWhen set to true, it will not print out the fiber ASCII and “listening” on messagefalse
DisableHeaderNormalizingboolBy default all header names are normalized: conteNT-tYPE -> Content-Typefalse
ETagboolEnable or disable ETag header generation, since both weak and strong etags are generated using the same hashing method (CRC-32). Weak ETags are the default when enabled.false
ViewsViewsViews is the interface that wraps the Render function. See our Template Middleware for supported engines.nil
ReadTimeouttime.DurationThe amount of time allowed to read the full request, including body. The default timeout is unlimited.nil
WriteTimeouttime.DurationThe maximum duration before timing out writes of the response. The default timeout is unlimited.nil
IdleTimeouttime.DurationThe maximum amount of time to wait for the next request when keep-alive is enabled. If IdleTimeout is zero, the value of ReadTimeout is used.nil
ReadBufferSizeintper-connection buffer size for requests’ reading. This also limits the maximum header size. Increase this buffer if your clients send multi-KB RequestURIs and/or multi-KB headers (for example, BIG cookies).4096
WriteBufferSizeintPer-connection buffer size for responses’ writing.4096

Static

Use the Static method to serve static files such as images, CSS and JavaScript.

By default, Static will serve index.html files in response to a request on a directory.
  1. app.Static(prefix, root string, config ...Static) // => with prefix

Use the following code to serve files in a directory named ./public

  1. app.Static("/", "./public")
  2. // => http://localhost:3000/hello.html
  3. // => http://localhost:3000/js/jquery.js
  4. // => http://localhost:3000/css/style.css

To serve from multiple directories, you can use Static numerous times.

  1. // Serve files from "./public" directory:
  2. app.Static("/", "./public")
  3. // Serve files from "./files" directory:
  4. app.Static("/", "./files")
Use a reverse proxy cache like NGINX to improve performance of serving static assets.

You can use any virtual path prefix (where the path does not actually exist in the file system) for files that are served by the Static method, specify a prefix path for the static directory, as shown below:

  1. app.Static("/static", "./public")
  2. // => http://localhost:3000/static/hello.html
  3. // => http://localhost:3000/static/js/jquery.js
  4. // => http://localhost:3000/static/css/style.css

If you want to have a little bit more control regarding the settings for serving static files. You could use the fiber.Static struct to enable specific settings.

  1. // Static represents settings for serving static files
  2. type Static struct {
  3. // Transparently compresses responses if set to true
  4. // This works differently than the github.com/gofiber/compression middleware
  5. // The server tries minimizing CPU usage by caching compressed files.
  6. // It adds ".fiber.gz" suffix to the original file name.
  7. // Optional. Default value false
  8. Compress bool
  9. // Enables byte-range requests if set to true.
  10. // Optional. Default value false
  11. ByteRange bool
  12. // Enable directory browsing.
  13. // Optional. Default value false.
  14. Browse bool
  15. // File to serve when requesting a directory path.
  16. // Optional. Default value "index.html".
  17. Index string
  18. }
  1. app.Static("/", "./public", fiber.Static{
  2. Compress: true,
  3. ByteRange: true,
  4. Browse: true,
  5. Index: "john.html"
  6. })

HTTP Methods

Routes an HTTP request, where METHOD is the HTTP method of the request.

  1. // Add allows you to specifiy a method as value
  2. app.Add(method, path string, handlers ...func(*Ctx)) Router
  3. // All will register the route on all methods
  4. app.All(path string, handlers ...func(*Ctx)) Router
  5. // HTTP methods
  6. app.Get(path string, handlers ...func(*Ctx)) Router
  7. app.Put(path string, handlers ...func(*Ctx)) Router
  8. app.Post(path string, handlers ...func(*Ctx)) Router
  9. app.Head(path string, handlers ...func(*Ctx)) Router
  10. app.Patch(path string, handlers ...func(*Ctx)) Router
  11. app.Trace(path string, handlers ...func(*Ctx)) Router
  12. app.Delete(path string, handlers ...func(*Ctx)) Router
  13. app.Connect(path string, handlers ...func(*Ctx)) Router
  14. app.Options(path string, handlers ...func(*Ctx)) Router
  15. // Use is mostly used for middleware modules
  16. // These routes will only match the beggining of each path
  17. // i.e. "/john" will match "/john/doe", "/johnnnn"
  18. app.Use(handlers ...func(*Ctx)) Router
  19. app.Use(prefix string, handlers ...func(*Ctx)) Router
  1. app.Use("/api", func(c *fiber.Ctx) {
  2. c.Set("X-Custom-Header", random.String(32))
  3. c.Next()
  4. })
  5. app.Get("/api/list", func(c *fiber.Ctx) {
  6. c.Send("I'm a GET request!")
  7. })
  8. app.Post("/api/register", func(c *fiber.Ctx) {
  9. c.Send("I'm a POST request!")
  10. })

Group

You can group routes by creating a *Group struct.

Signature

  1. app.Group(prefix string, handlers ...func(*Ctx)) Router

Example

  1. func main() {
  2. app := fiber.New()
  3. api := app.Group("/api", handler) // /api
  4. v1 := api.Group("/v1", handler) // /api/v1
  5. v1.Get("/list", handler) // /api/v1/list
  6. v1.Get("/user", handler) // /api/v1/user
  7. v2 := api.Group("/v2", handler) // /api/v2
  8. v2.Get("/list", handler) // /api/v2/list
  9. v2.Get("/user", handler) // /api/v2/user
  10. app.Listen(3000)
  11. }

Stack

This method returns the original router stack

  1. app.Stack() [][]*Route
  1. app := fiber.New()
  2. app.Use(handler)
  3. app.Get("/john", handler)
  4. app.Post("/register", handler)
  5. app.Get("/v1/users", handler)
  6. app.Put("/user/:id", handler)
  7. app.Head("/xhr", handler)
  8. data, _ := json.MarshalIndent(app.Stack(), "", " ")
  9. fmt.Println(string(data))

Listen

Binds and listens for connections on the specified address. This can be an int for port or string for address. This will listen either on tcp4 or tcp6 depending on the address input (i.e. :3000 / [::1]:3000 ).

  1. app.Listen(address interface{}, tls ...*tls.Config) error
  1. app.Listen(8080)
  2. app.Listen("8080")
  3. app.Listen(":8080")
  4. app.Listen("127.0.0.1:8080")
  5. app.Listen("[::1]:8080")

To enable TLS/HTTPS you can append a TLS config.

  1. cer, err := tls.LoadX509KeyPair("server.crt", "server.key")
  2. if err != nil {
  3. log.Fatal(err)
  4. }
  5. config := &tls.Config{Certificates: []tls.Certificate{cer}}
  6. app.Listen(443, config)

Listener

You can pass your own net.Listener using the Listener method.

  1. app.Listener(ln net.Listener, tls ...*tls.Config) error
Listener does not support the Prefork feature.
  1. if ln, err = net.Listen("tcp", ":8080"); err != nil {
  2. log.Fatal(err)
  3. }
  4. app.Listener(ln)

Test

Testing your application is done with the Test method. Use this method for creating _test.go files or when you need to debug your routing logic. The default timeout is 200ms if you want to disable a timeout altogether, pass -1 as a second argument.

  1. app.Test(req *http.Request, msTimeout ...int) (*http.Response, error)
  1. // Create route with GET method for test:
  2. app.Get("/", func(c *Ctx) {
  3. fmt.Println(c.BaseURL()) // => http://google.com
  4. fmt.Println(c.Get("X-Custom-Header")) // => hi
  5. c.Send("hello, World!")
  6. })
  7. // http.Request
  8. req := httptest.NewRequest("GET", "http://google.com", nil)
  9. req.Header.Set("X-Custom-Header", "hi")
  10. // http.Response
  11. resp, _ := app.Test(req)
  12. // Do something with results:
  13. if resp.StatusCode == 200 {
  14. body, _ := ioutil.ReadAll(resp.Body)
  15. fmt.Println(string(body)) // => Hello, World!
  16. }