description: The app instance conventionally denotes the Fiber application.

🚀 Application

New

This method creates a new App named instance.
You can pass optional settings when creating a new instance

  1. fiber.New(settings ...Settings) *App
  1. package main
  2. import "github.com/gofiber/fiber/v2"
  3. func main() {
  4. app := fiber.New()
  5. // ...
  6. app.Listen(":3000")
  7. }

Settings

You can pass application settings when calling New.

  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. log.Fatal(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. log.Fatal(app.Listen(":3000"))
  10. }

Settings fields

Property Type Description Default
Prefork bool Enables use of theSO_REUSEPORTsocket option. This will spawn multiple Go processes listening on the same port. learn more about socket sharding. false
ServerHeader string Enables the Server HTTP header with the given value. ""
StrictRouting bool When enabled, the router treats /foo and /foo/ as different. Otherwise, the router treats /foo and /foo/ as the same. false
CaseSensitive bool When enabled, /Foo and /foo are different routes. When disabled, /Fooand /foo are treated the same. false
Immutable bool When enabled, all values returned by context methods are immutable. By default they are valid until you return from the handler, see issue #185. false
BodyLimit int Sets 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
Concurrency int Maximum number of concurrent connections. 256 * 1024
DisableKeepalive bool Disable keep-alive connections, the server will close incoming connections after sending the first response to client false
DisableDefaultDate bool When set to true causes the default date header to be excluded from the response. false
DisableDefaultContentType bool When set to true, causes the default Content-Type header to be excluded from the Response. false
TemplateEngine func(raw string, bind interface{}) (string, error) You can specify a custom template function to render different template languages. See our Template Middleware _**_for presets. nil
TemplateFolder string A directory for the application’s views. If a directory is set, this will be the prefix for all template paths. c.Render("home", data) -> ./views/home.pug ""
TemplateExtension string If you preset the template file extension, you do not need to provide the full filename in the Render function: c.Render("home", data) -> home.pug "html"
ReadTimeout time.Duration The amount of time allowed to read the full request including body. Default timeout is unlimited. nil
WriteTimeout time.Duration The maximum duration before timing out writes of the response. Default timeout is unlimited. nil
IdleTimeout time.Duration The 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

Static

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

By default, Static will serveindex.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 multiple 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. // Index file for serving a directory.
  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. // HTTP methods support :param, :optional? and *wildcards
  2. // You are required to pass a path to each method
  3. app.All(path string, handlers ...func(*Ctx)) *Fiber
  4. app.Get
  5. app.Put
  6. app.Post
  7. app.Head
  8. app.Patch
  9. app.Trace
  10. app.Delete
  11. app.Connect
  12. app.Options
  13. // Use() will only match the beggining of each path
  14. // i.e. "/john" will match "/john/doe", "/johnnnn"
  15. // Use() does not support :param & :optional? in path
  16. app.Use(handlers ...func(*Ctx))
  17. app.Use(prefix string, handlers ...func(*Ctx)) *Fiber
  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)) *Group

Example

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

Listen

Binds and listens for connections on the specified address.

  1. app.Listen(address string, tls ...*tls.Config) error
  1. app.Listen(":8080")
  2. app.Listen("8080")
  3. app.Listen(":8080")
  4. app.Listen("127.0.0.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)

Serve

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

  1. app.Serve(ln net.Listener, tls ...*tls.Config) error

Serve does not support the **[Prefork** ]($original-application.md#settings)feature.

  1. if ln, err = net.Listen("tcp4", ":8080"); err != nil {
  2. log.Fatal(err)
  3. }
  4. app.Serve(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 completely, 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, _ := http.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. }