description: The app instance conventionally denotes the Fiber application.

🚀 App

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. func (app *App) Static(prefix, root string, config ...Static) Router

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
  1. // Serve files from multiple directories
  2. app.Static("/", "./public")
  3. // Serve files from "./files" directory:
  4. app.Static("/", "./files")

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 defines configuration options when defining static assets.
  2. type Static struct {
  3. // When set to true, the server tries minimizing CPU usage by caching compressed files.
  4. // This works differently than the github.com/gofiber/compression middleware.
  5. // Optional. Default value false
  6. Compress bool `json:"compress"`
  7. // When set to true, enables byte range requests.
  8. // Optional. Default value false
  9. ByteRange bool `json:"byte_range"`
  10. // When set to true, enables directory browsing.
  11. // Optional. Default value false.
  12. Browse bool `json:"browse"`
  13. // The name of the index file for serving a directory.
  14. // Optional. Default value "index.html".
  15. Index string `json:"index"`
  16. // Expiration duration for inactive file handlers.
  17. // Use a negative time.Duration to disable it.
  18. //
  19. // Optional. Default value 10 * time.Second.
  20. CacheDuration time.Duration `json:"cache_duration"`
  21. // The value for the Cache-Control HTTP-header
  22. // that is set on the file response. MaxAge is defined in seconds.
  23. //
  24. // Optional. Default value 0.
  25. MaxAge int `json:"max_age"`
  26. // Next defines a function to skip this middleware when returned true.
  27. //
  28. // Optional. Default: nil
  29. Next func(c *Ctx) bool
  30. }
  1. // Custom config
  2. app.Static("/", "./public", fiber.Static{
  3. Compress: true,
  4. ByteRange: true,
  5. Browse: true,
  6. Index: "john.html"
  7. CacheDuration: 10 * time.Second,
  8. MaxAge: 3600,
  9. })

Route Handlers

Registeres a route bound to a specific HTTP method.

  1. // HTTP methods
  2. func (app *App) Get(path string, handlers ...Handler) Router
  3. func (app *App) Head(path string, handlers ...Handler) Router
  4. func (app *App) Post(path string, handlers ...Handler) Router
  5. func (app *App) Put(path string, handlers ...Handler) Router
  6. func (app *App) Delete(path string, handlers ...Handler) Router
  7. func (app *App) Connect(path string, handlers ...Handler) Router
  8. func (app *App) Options(path string, handlers ...Handler) Router
  9. func (app *App) Trace(path string, handlers ...Handler) Router
  10. func (app *App) Patch(path string, handlers ...Handler) Router
  11. // Add allows you to specifiy a method as value
  12. func (app *App) Add(method, path string, handlers ...Handler) Router
  13. // All will register the route on all HTTP methods
  14. // Almost the same as app.Use but not bound to prefixes
  15. func (app *App) All(path string, handlers ...Handler) Router
  1. // Simple GET handler
  2. app.Get("/api/list", func(c *fiber.Ctx)error{
  3. return c.SendString("I'm a GET request!")
  4. })
  5. // Simple POST handler
  6. app.Post("/api/register", func(c *fiber.Ctx) error {
  7. return c.SendString("I'm a POST request!")
  8. })

Use can be used for middleware packages and prefix catchers. These routes will only match the beginning of each path i.e. /john will match /john/doe, /johnnnnn etc

  1. func (app *App) Use(args ...interface{}) Router
  1. // Match any request
  2. app.Use(func(c *fiber.Ctx) error {
  3. return c.Next()
  4. })
  5. // Match request starting with /api
  6. app.Use("/api", func(c *fiber.Ctx) error {
  7. return c.Next()
  8. })
  9. // Attach multiple handlers
  10. app.Use("/api",func(c *fiber.Ctx) error {
  11. c.Set("X-Custom-Header", random.String(32))
  12. return c.Next()
  13. }, func(c *fiber.Ctx) error {
  14. return c.Next()
  15. })

Mount

You can Mount Fiber instance by creating a *Mount

Signature

  1. func (a *App) Mount(prefix string, app *App) Router

Example

  1. func main() {
  2. micro := fiber.New()
  3. micro.Get("/doe", func(c *fiber.Ctx) error {
  4. return c.SendStatus(fiber.StatusOK)
  5. })
  6. app := fiber.New()
  7. app.Mount("/john", micro) // GET /john/doe -> 200 OK
  8. log.Fatal(app.Listen(":3000"))
  9. }

Group

You can group routes by creating a *Group struct.

Signature

  1. func (app *App) Group(prefix string, handlers ...Handler) 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. log.Fatal(app.Listen(":3000"))
  11. }

Server

Server returns the underlying fasthttp server

  1. func (app *App) Server() *fasthttp.Server
  1. func main() {
  2. app := fiber.New()
  3. app.Server().MaxConnsPerIP = 1
  4. // ...
  5. }

Stack

This method returns the original router stack

  1. func (app *App) Stack() [][]*Route
  1. var handler = func(c *fiber.Ctx) error { return nil }
  2. func main() {
  3. app := fiber.New()
  4. app.Get("/john/:age", handler)
  5. app.Post("/register", handler)
  6. data, _ := json.MarshalIndent(app.Stack(), "", " ")
  7. fmt.Println(string(data))
  8. app.Listen(":3000")
  9. }
  1. [
  2. [
  3. {
  4. "method": "GET",
  5. "path": "/john/:age",
  6. "params": [
  7. "age"
  8. ]
  9. }
  10. ],
  11. [
  12. {
  13. "method": "HEAD",
  14. "path": "/john/:age",
  15. "params": [
  16. "age"
  17. ]
  18. }
  19. ],
  20. [
  21. {
  22. "method": "POST",
  23. "path": "/register",
  24. "params": null
  25. }
  26. ]
  27. ]

Config

Config returns the app config as value ( read-only ).

  1. func (app *App) Config() Config

Handler

Handler returns the server handler that can be used to serve custom *fasthttp.RequestCtx requests.

  1. func (app *App) Handler() fasthttp.RequestHandler

Listen

Listen serves HTTP requests from the given address.

  1. func (app *App) Listen(addr string) error
  1. // Listen on port :8080
  2. app.Listen(":8080")
  3. // Custom host
  4. app.Listen("127.0.0.1:8080")

ListenTLS

ListenTLS serves HTTPs requests from the given address using certFile and keyFile paths to as TLS certificate and key file.

  1. func (app *App) ListenTLS(addr, certFile, keyFile string) error
  1. app.ListenTLS(":443", "./cert.pem", "./cert.key");

Using ListenTLS defaults to the following config ( use Listener to provide your own config )

  1. &tls.Config{
  2. MinVersion: tls.VersionTLS12,
  3. PreferServerCipherSuites: true,
  4. Certificates: []tls.Certificate{
  5. cert,
  6. },
  7. }

Listener

You can pass your own net.Listener using the Listener method. This method can be used to enable TLS/HTTPS with a custom tls.Config.

  1. func (app *App) Listener(ln net.Listener) error
  1. ln, _ := net.Listen("tcp", ":3000")
  2. cer, _:= tls.LoadX509KeyPair("server.crt", "server.key")
  3. ln = tls.NewListener(ln, &tls.Config{Certificates: []tls.Certificate{cer}})
  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 1s if you want to disable a timeout altogether, pass -1 as a second argument.

  1. func (app *App) Test(req *http.Request, msTimeout ...int) (*http.Response, error)
  1. // Create route with GET method for test:
  2. app.Get("/", func(c *fiber.Ctx) error {
  3. fmt.Println(c.BaseURL()) // => http://google.com
  4. fmt.Println(c.Get("X-Custom-Header")) // => hi
  5. return c.SendString("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. }