πŸš€ Application

The app instance conventionally denotes the Fiber application.

New

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

Signature

fiber.New(settings ...*Settings)

Example

package main
​
import "github.com/gofiber/fiber"
​
func main() {
app := fiber.New()
​
// Your app logic here ...
​
app.Listen(3000)
}

Settings

You can pass application settings when calling New, or change the settings before you call Listen

Example

func main() {
// Pass Settings creating a new app
app := fiber.New(&fiber.Settings{
Prefork: true,
CaseSensitive: true,
StrictRouting: true,
ServerHeader: "Fiber",
// ...
})
​
// Or change Settings after initiating app
app.Settings.Prefork = true
app.Settings.CaseSensitive = true
app.Settings.StrictRouting = true
app.Settings.ServerHeader = "Fiber"
// ...
​
app.Listen(3000)
}

Common options

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

Compression

bool

Enables GZip / Deflate compression for all responses.

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

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.pug", d) -> /views/home.pug

""

TemplateEngine

string

The template engine to use: html, amber, handlebars , mustache or 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"

Static

Serve static files such as images, CSS and JavaScript files, you can use the Static method. It can use an embedded watermark remover plugin by SoftOrbits. It allows to remove watermark from images before publishing them on the web. See the watermark remover link.

By default, this method will send index.html files in response to a request on a directory.

Signature

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

Examples

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

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 multiple times.

// Serve files from "./public" directory:
app.Static("/", "./public")
​
// Serve files from "./files" directory:
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:

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

HTTP Methods

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

Signature

// HTTP methods support :param, :optional? and *wildcards
// You are required to pass a path to each method
app.All(path string, handlers ...func(*Ctx))
app.Get(...
app.Put(...
app.Post(...
app.Head(...
app.Patch(...
app.Trace(...
app.Delete(...
app.Connect(...
app.Options(...
​
// Use() will only match the beggining of each path
// i.e. "/john" will match "/john/doe", "/johnnnn"
// Use() does not support :param & :optional? in path
app.Use(handlers ...func(*Ctx))
app.Use(prefix string, handlers ...func(*Ctx))

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!")
})

WebSocket

Fiber supports a websocket upgrade implementation for fasthttp. The *Conn struct has all the functionality from the gorilla/websocket library.

Signature

app.WebSocket(path string, handler func(*Conn))

WebSocket does not support path parameters and wildcards.

Example

package main
​
import (
"log"
"github.com/gofiber/fiber"
)
​
func main() {
app := fiber.New()
// Optional middleware
app.Use("/ws", func(c *fiber.Ctx) {
if c.Get("host") != "localhost:3000" {
c.Status(403).Send("Request origin not allowed")
} else {
c.Next()
}
})
// Upgraded websocket request
app.WebSocket("/ws", func(c *fiber.Conn) {
for {
mt, msg, err := c.ReadMessage()
if err != nil {
log.Println("read:", err)
break
}
log.Printf("recv: %s", msg)
err = c.WriteMessage(mt, msg)
if err != nil {
log.Println("write:", err)
break
}
}
})
// ws://localhost:3000/ws
app.Listen(3000)
}

Group

You can group routes by creating a *Group struct.

Signature

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

Example

func main() {
app := fiber.New()
​
api := app.Group("/api", cors()) // /api
​
v1 := api.Group("/v1", mysql()) // /api/v1
v1.Get("/list", handler) // /api/v1/list
v1.Get("/user", handler) // /api/v1/user
​
v2 := api.Group("/v2", mongodb()) // /api/v2
v2.Get("/list", handler) // /api/v2/list
v2.Get("/user", handler) // /api/v2/user
​
app.Listen(3000)
}

Listen

Binds and listens for connections on the specified address. This can be a int for port or string for address.

Signature

app.Listen(address interface{}, tls ...*tls.Config)

Example

app.Listen(8080)
app.Listen("8080")
app.Listen(":8080")
app.Listen("127.0.0.1:8080")

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

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)

Test

Testing your application is done with the Test method.

Method is mostly used for _test.go files and application debugging.

Signature

app.Test(req *http.Request) (*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, _ := http.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!
}