Skip to main content
Version: v1.x

🚀 App

New

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

Signature
fiber.New(settings ...*Settings) *App
Example
package main

import "github.com/gofiber/fiber"

func main() {
app := fiber.New()

// ...

app.Listen(3000)
}

Settings

You can pass application settings when calling New.

Example
func main() {
// Pass Settings creating a new instance
app := fiber.New(&fiber.Settings{
Prefork: true,
CaseSensitive: true,
StrictRouting: true,
ServerHeader: "Fiber",
})

// ...

app.Listen(3000)
}

Or change the settings after initializing an app.

Example
func main() {
app := fiber.New()

// Or change Settings after creating an instance
app.Settings.Prefork = true
app.Settings.CaseSensitive = true
app.Settings.StrictRouting = true
app.Settings.ServerHeader = "Fiber"

// ...

app.Listen(3000)
}

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.

info

By default, Static will serve index.html files in response to a request on a directory.

Signature
app.Static(prefix, root string, config ...Static) // => with prefix

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

Example
app.Static("/", "./public")

// => http://localhost:3000/hello.html
// => http://localhost:3000/js/jquery.js
// => http://localhost:3000/css/style.css

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

Example
// Serve files from "./public" directory:
app.Static("/", "./public")

// Serve files from "./files" directory:
app.Static("/", "./files")
info

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:

Example
app.Static("/static", "./public")

// => http://localhost:3000/static/hello.html
// => http://localhost:3000/static/js/jquery.js
// => 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.

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

HTTP Methods

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

Signatures
// Add allows you to specifiy a method as value
app.Add(method, path string, handlers ...func(*Ctx)) Router

// All will register the route on all methods
app.All(path string, handlers ...func(*Ctx)) Router

// HTTP methods
app.Get(path string, handlers ...func(*Ctx)) Router
app.Put(path string, handlers ...func(*Ctx)) Router
app.Post(path string, handlers ...func(*Ctx)) Router
app.Head(path string, handlers ...func(*Ctx)) Router
app.Patch(path string, handlers ...func(*Ctx)) Router
app.Trace(path string, handlers ...func(*Ctx)) Router
app.Delete(path string, handlers ...func(*Ctx)) Router
app.Connect(path string, handlers ...func(*Ctx)) Router
app.Options(path string, handlers ...func(*Ctx)) Router

// Use is mostly used for middleware modules
// These routes will only match the beggining of each path
// i.e. "/john" will match "/john/doe", "/johnnnn"
app.Use(handlers ...func(*Ctx)) Router
app.Use(prefix string, handlers ...func(*Ctx)) Router
Example
app.Use("/api", func(c *fiber.Ctx) {
c.Set("X-Custom-Header", random.String(32))
c.Next()
})
app.Get("/api/list", func(c *fiber.Ctx) {
c.Send("I'm a GET request!")
})
app.Post("/api/register", func(c *fiber.Ctx) {
c.Send("I'm a POST request!")
})

Group

You can group routes by creating a *Group struct.

Signature

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

Example

func main() {
app := fiber.New()

api := app.Group("/api", handler) // /api

v1 := api.Group("/v1", handler) // /api/v1
v1.Get("/list", handler) // /api/v1/list
v1.Get("/user", handler) // /api/v1/user

v2 := api.Group("/v2", handler) // /api/v2
v2.Get("/list", handler) // /api/v2/list
v2.Get("/user", handler) // /api/v2/user

app.Listen(3000)
}

Stack

This method returns the original router stack

Signature
app.Stack() [][]*Route
Example
app := fiber.New()

app.Use(handler)
app.Get("/john", handler)
app.Post("/register", handler)
app.Get("/v1/users", handler)
app.Put("/user/:id", handler)
app.Head("/xhr", handler)

data, _ := json.MarshalIndent(app.Stack(), "", " ")
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 ).

Signature
app.Listen(address interface{}, tls ...*tls.Config) error
Examples
app.Listen(8080)
app.Listen("8080")
app.Listen(":8080")
app.Listen("127.0.0.1:8080")
app.Listen("[::1]:8080")

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

Example
cer, err := tls.LoadX509KeyPair("server.crt", "server.key")
if err != nil {
log.Fatal(err)
}
config := &tls.Config{Certificates: []tls.Certificate{cer}}

app.Listen(443, config)

Listener

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

Signature
app.Listener(ln net.Listener, tls ...*tls.Config) error
caution

Listener does not support the Prefork feature.

Example
if ln, err = net.Listen("tcp", ":8080"); err != nil {
log.Fatal(err)
}

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.

Signature
app.Test(req *http.Request, msTimeout ...int) (*http.Response, error)
Example
// Create route with GET method for test:
app.Get("/", func(c *Ctx) {
fmt.Println(c.BaseURL()) // => http://google.com
fmt.Println(c.Get("X-Custom-Header")) // => hi

c.Send("hello, World!")
})

// http.Request
req := httptest.NewRequest("GET", "http://google.com", nil)
req.Header.Set("X-Custom-Header", "hi")

// http.Response
resp, _ := app.Test(req)

// Do something with results:
if resp.StatusCode == 200 {
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(body)) // => Hello, World!
}