description: >- Middleware is a function chained in the HTTP request cycle with access to the Context which it uses to perform a specific action, for example, logging every

request or enabling CORS.

🧬 Middleware

Basic Auth

Basic auth middleware provides an HTTP basic authentication. It calls the next handler for valid credentials and 401 Unauthorized for missing or invalid credentials.

Installation

  1. go get -u github.com/gofiber/basicauth

Signature

  1. basicauth.New(config ...Config) func(*fiber.Ctx)

Config

Property Type Description Default
Filter func(*fiber.Ctx) bool Defines a function to skip middleware nil
Users map[string][string] Users defines the allowed credentials nil
Realm string Realm is a string to define the realm attribute Restricted
Authorizer func(string, string) bool A function you can pass to check the credentials however you want. nil
Unauthorized func(*fiber.Ctx) Custom response body for unauthorized responses nil

Example

  1. package main
  2. import (
  3. "log"
  4. "github.com/gofiber/fiber/v2"
  5. "github.com/gofiber/basicauth"
  6. )
  7. func main() {
  8. app := fiber.New()
  9. cfg := basicauth.Config{
  10. Users: map[string]string{
  11. "john": "doe",
  12. "admin": "123456",
  13. },
  14. }
  15. app.Use(basicauth.New(cfg))
  16. app.Get("/", func(c *fiber.Ctx) {
  17. c.Send("Welcome!")
  18. })
  19. log.Fatal(app.Listen(":3000"))
  20. }

CORS

CORS middleware implements CORS specification. CORS gives web servers cross-domain access controls, which enable secure cross-domain data transfers.

Installation

  1. go get -u github.com/gofiber/cors

Signature

  1. cors.New(config ...Config) func(*fiber.Ctx)

Config

Property Type Description Default
Filter func(*Ctx) bool Defines a function to skip middleware nil
AllowOrigins []string AllowOrigin defines a list of origins that may access the resource. []string{"*"}
AllowMethods []string AllowMethods defines a list methods allowed when accessing the resource. This is used in response to a preflight request. []string{"GET", "POST", "HEAD", "PUT", "DELETE", "PATCH"}
AllowCredentials string AllowCredentials indicates whether or not the response to the request can be exposed when the credentials flag is true. When used as part of a response to a preflight request, this indicates whether or not the actual request can be made using credentials. nil
ExposeHeaders []string ExposeHeaders defines a whitelist headers that clients are allowed to access. nil
MaxAge int MaxAge indicates how long (in seconds) the results of a preflight request can be cached. 0
  1. package main
  2. import (
  3. "log"
  4. "github.com/gofiber/fiber/v2"
  5. "github.com/gofiber/cors"
  6. )
  7. func main() {
  8. app := fiber.New()
  9. app.Use(cors.New())
  10. app.Get("/", func(c *fiber.Ctx) {
  11. c.Send("Welcome!")
  12. })
  13. log.Fatal(app.Listen(":3000"))
  14. // curl -H "Origin: http://example.com" --verbose http://localhost:3000
  15. }

Compression

This middleware allows dynamic compression for gzip & deflate if you your responses are bigger than 4kb. If you want to enable compression for static files only, please use the Compression setting inside the Static method.

Installation

  1. go get -u github.com/gofiber/compression

Signature

  1. compression.New(config ...Config) func(*fiber.Ctx)

Config

Property Type Description Default
Filter func(*Ctx) bool Defines a function to skip middleware nil
Level int Level of compression, 0, 1, 2, 3, 4 0
  1. package main
  2. import
  3. "log"
  4. "github.com/gofiber/fiber/v2"
  5. "github.com/gofiber/compression"
  6. )
  7. func main() {
  8. app := fiber.New()
  9. app.Use(compression.New())
  10. app.Get("/", func(c *fiber.Ctx) {
  11. c.Send("Welcome!")
  12. })
  13. log.Fatal(app.Listen(":3000"))
  14. }

Limiter

Use to limit repeated requests to public APIs and/or endpoints such as password reset. This middleware does not share state with other processes/servers.

Installation

  1. go get -u github.com/gofiber/limiter

Signature

  1. limiter.New(config ...Config) func(*Ctx)

Config

Property Type Description Default
Filter func(*fiber.Ctx) bool Defines a function to skip middleware nil
Timeout int Timeout in seconds on how long to keep records of requests in memory 60
Max int Max number of recent connections during Timeout seconds before sending a 429 response 10
Message string Response body "Too many requests, please try again later."
StatusCode int Response status code 429
Key func(*Ctx) string A function that allows to create custom keys. By default c.IP() is used. nil
Handler func(*Ctx) Handler is called when a request hits the limit nil

Example

  1. package main
  2. import (
  3. "log"
  4. "github.com/gofiber/fiber/v2"
  5. "github.com/gofiber/limiter"
  6. )
  7. func main() {
  8. app := fiber.New()
  9. // 3 requests per 10 seconds max
  10. cfg := limiter.Config{
  11. Timeout: 10,
  12. Max: 3,
  13. }
  14. app.Use(limiter.New(cfg))
  15. app.Get("/", func(c *fiber.Ctx) {
  16. c.Send("Welcome!")
  17. })
  18. log.Fatal(app.Listen(":3000"))
  19. }

Logger

Logger middleware logs the information about each HTTP request.

Installation

  1. go get -u github.com/gofiber/logger

Signature

  1. logger.new(config ...Config) func(*Ctx)

Config

Property Type Description Default
Filter func(*fiber.Ctx) bool Defines a function to skip middleware nil
Format string Possible values: time, ip, url, host, method, path, route, protocol, referer, ua, bytesSent, bytesReceived, header:<key>, query:<key>, form:<key>, cookie:<key> "${time} - ${ip} - ${method} ${path}\t${ua}\n"
TimeFormat string TimeFormat read more here 15:04:05
Output io.Writer Output is a writter where logs are written os.Stderr

Example

  1. package main
  2. import (
  3. "log"
  4. "github.com/gofiber/fiber/v2"
  5. "github.com/gofiber/logger"
  6. )
  7. func main() {
  8. app := fiber.New()
  9. app.Use(logger.New())
  10. app.Get("/", func(c *fiber.Ctx) {
  11. c.Send("Welcome!")
  12. })
  13. log.Fatal(app.Listen(":3000"))
  14. }

Recover

You can recover from panic errors within any route. By default the Recover middleware will respond with 500 Internal Server Error when a panic occurs. You can also provide your own error handler.

Installation

  1. go get -u github.com/gofiber/recover

Signature

  1. recover.New(config ...Config) func(*Ctx)

Example

  1. package main
  2. import (
  3. "log"
  4. "github.com/gofiber/fiber/v2"
  5. "github.com/gofiber/recover"
  6. )
  7. func main() {
  8. app := fiber.New()
  9. // Optional
  10. cfg := recover.Config{
  11. Handler: func(c *fiber.Ctx, err error) {
  12. c.SendString(err.Error())
  13. c.SendStatus(500)
  14. },
  15. }
  16. app.Use(recover.New(cfg))
  17. app.Get("/", func(c *fiber.Ctx) {
  18. panic("Hi, I'm a error!")
  19. })
  20. log.Fatal(app.Listen(":3000"))
  21. }

Template

By default Fiber comes with the default HTML template engine, but this middleware contains third party rendering engines.

Installation

  1. go get -u github.com/gofiber/template

Signature

  1. template.Engine() func(raw string, bind interface{}) (out string, err error)

Template Engines

Keyword Engine
Amber() github.com/eknkc/amber
Handlebars() github.com/aymerick/raymond
Mustache() github.com/cbroglie/mustache
Pug() github.com/Joker/jade

Example

  1. package main
  2. import (
  3. "log"
  4. "github.com/gofiber/fiber/v2"
  5. "github.com/gofiber/template"
  6. )
  7. func main() {
  8. app := fiber.New()
  9. app.Settings.TemplateEngine = template.Mustache()
  10. // app.Settings.TemplateEngine = template.Amber()
  11. // app.Settings.TemplateEngine = template.Handlebars()
  12. // app.Settings.TemplateEngine = template.Pug()
  13. app.Get("/", func(c *fiber.Ctx) {
  14. bind := fiber.Map{
  15. "name": "John",
  16. "age": 35,
  17. }
  18. if err := c.Render("./views/index.mustache", bind); err != nil {
  19. c.Status(500).Send(err.Error())
  20. }
  21. // <html><head><title>Template Demo</title></head>
  22. // <body>Hi, my name is John and im 35 years old
  23. // </body></html>
  24. })
  25. log.Fatal(app.Listen(":3000"))
  26. }

WebSocket

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

Installation

  1. go get -u github.com/gofiber/websocket

Signature

  1. websocket.New(handler func(*Conn), config ...Config) func(*Ctx)

Config

Property Type Description Default
HandshakeTimeout time.Duration Specifies the duration for the handshake to complete. 0
Subprotocols []string specifies the server’s supported protocols in order of preference. If this field is not nil, then the Upgrade method negotiates a subprotocol by selecting the first match in this list with a protocol requested by the client. nil
Origins []string Origins is a string slice of origins that are acceptable, by default all origins are allowed. []string{"*"}
ReadBufferSize int ReadBufferSize specify I/O buffer sizes in bytes. 1024
WriteBufferSize int WriteBufferSize specify I/O buffer sizes in bytes. 1024
EnableCompression bool EnableCompression specify if the server should attempt to negotiate per message compression (RFC 7692) false

Example

  1. package main
  2. import (
  3. "log"
  4. "github.com/gofiber/fiber/v2"
  5. "github.com/gofiber/websocket"
  6. )
  7. func main() {
  8. app := fiber.New()
  9. app.Use(func(c *fiber.Ctx) {
  10. c.Locals("Hello", "World")
  11. c.Next()
  12. })
  13. app.Get("/ws", websocket.New(func(c *websocket.Conn) {
  14. fmt.Println(c.Locals("Hello")) // "World"
  15. // Websocket logic...
  16. for {
  17. mt, msg, err := c.ReadMessage()
  18. if err != nil {
  19. log.Println("read:", err)
  20. break
  21. }
  22. log.Printf("recv: %s", msg)
  23. err = c.WriteMessage(mt, msg)
  24. if err != nil {
  25. log.Println("write:", err)
  26. break
  27. }
  28. }
  29. }))
  30. log.Fatal(app.Listen(":3000")) // ws://localhost:3000/ws
  31. }

Request ID

Request ID adds an identifier to the request using the X-Request-ID header

Installation

  1. go get -u github.com/gofiber/requestid

Signature

  1. requestid.New(config ...Config) func(*Ctx)

Config

Property Type Description Default
Filter func(*fiber.Ctx) bool Defines a function to skip middleware nil
Generator func(*fiber.Ctx) string Generator defines a function to generate an ID. return uuid.New().String()

Example

  1. package main
  2. import (
  3. "log"
  4. "github.com/gofiber/fiber/v2"
  5. "github.com/gofiber/requestid"
  6. )
  7. func main() {
  8. app := fiber.New()
  9. app.Use(requestid.New())
  10. app.Get("/", func(c *fiber.Ctx) {
  11. c.Send(requestid.Get(c))
  12. })
  13. log.Fatal(app.Listen(":3000"))
  14. }

Helmet

Helmet middleware provides protection against cross-site scripting (XSS) attack, content type sniffing, clickjacking, insecure connection and other code injection attacks.

Installation

  1. go get -u github.com/gofiber/helmet

Signature

  1. helmet.New(config ...Config) func(*Ctx)

Config

Property Type Description Default
Filter func(*fiber.Ctx) bool Defines a function to skip middleware nil
XSSProtection string XSSProtection provides protection against cross-site scripting attack (XSS) by setting the X-XSS-Protection header. 1; mode=block"
ContentTypeNosniff string ContentTypeNosniff provides protection against overriding Content-Type header by setting the X-Content-Type-Options header. "nosniff"
XFrameOptions string XFrameOptions can be used to indicate whether or not a browser should be allowed to render a page in a , or . Sites can use this to avoid clickjacking attacks, by ensuring that their content is not embedded into other sites.provides protection against clickjacking. Possible values: SAMEORIGIN, DENY, ALLOW-FROM uri "SAMEORIGIN"
HSTSMaxAge int HSTSMaxAge sets the Strict-Transport-Security header to indicate how long (in seconds) browsers should remember that this site is only to be accessed using HTTPS. This reduces your exposure to some SSL-stripping man-in-the-middle (MITM) attacks. ``
HSTSExcludeSubdomains bool HSTSExcludeSubdomains won’t include subdomains tag in the Strict Transport Security header, excluding all subdomains from security policy. It has no effect unless HSTSMaxAge is set to a non-zero value. ``
ContentSecurityPolicy string ContentSecurityPolicy sets the Content-Security-Policy header providing security against cross-site scripting (XSS), clickjacking and other code injection attacks resulting from execution of malicious content in the trusted web page context ``
CSPReportOnly bool ``
HSTSPreloadEnabled bool ``
ReferrerPolicy string ``

Example

  1. package main
  2. import (
  3. "log"
  4. "github.com/gofiber/fiber/v2"
  5. "github.com/gofiber/helmet"
  6. )
  7. func main() {
  8. app := fiber.New()
  9. app.Use(helmet.New())
  10. app.Get("/", func(c *fiber.Ctx) {
  11. c.Send("Welcome!")
  12. })
  13. log.Fatal(app.Listen(":3000"))
  14. // curl -I http://localhost:3000
  15. }

Redirect

Redirects middleware provides an HTTP redirect to the URL derived from the specified path, with specified status, a positive integer that corresponds to an HTTP status code.

Installation

  1. go get -u github.com/gofiber/redirect

Signature

  1. redirect.New(config ...Config) func(*Ctx)

Example

  1. package main
  2. import (
  3. "log"
  4. "github.com/gofiber/fiber/v2"
  5. "github.com/gofiber/redirect"
  6. )
  7. func main() {
  8. app := fiber.New()
  9. app.Use(redirect.New(redirect.Config{
  10. Rules: map[string]string{
  11. "/old": "/new",
  12. "/old/*": "/new/$1",
  13. },
  14. StatusCode: 301,
  15. }))
  16. app.Get("/new", func(c *fiber.Ctx) {
  17. c.Send("Hello, World!")
  18. })
  19. app.Get("/new/*", func(c *fiber.Ctx) {
  20. c.Send("Wildcard: ", c.Params("*"))
  21. })
  22. log.Fatal(app.Listen(":3000"))
  23. }