Compress

Compression middleware for Fiber that will compress the response using gzip, deflate and brotli compression depending on the Accept-Encoding header.

Signatures

  1. func New(config ...Config) fiber.Handler

Examples

Import the middleware package that is part of the Fiber web framework

  1. import (
  2. "github.com/gofiber/fiber/v2"
  3. "github.com/gofiber/fiber/v2/middleware/compress"
  4. )

After you initiate your Fiber app, you can use the following possibilities:

  1. // Default middleware config
  2. app.Use(compress.New())
  3. // Provide a custom compression level
  4. app.Use(compress.New(compress.Config{
  5. Level: compress.LevelBestSpeed, // 1
  6. }))
  7. // Skip middleware for specific routes
  8. app.Use(compress.New(compress.Config{
  9. Next: func(c *fiber.Ctx) bool {
  10. return c.Path() == "/dont_compress"
  11. },
  12. Level: compress.LevelBestSpeed, // 1
  13. }))

Config

  1. // Config defines the config for middleware.
  2. type Config struct {
  3. // Next defines a function to skip this middleware when returned true.
  4. //
  5. // Optional. Default: nil
  6. Next func(c *fiber.Ctx) bool
  7. // CompressLevel determines the compression algoritm
  8. //
  9. // Optional. Default: LevelDefault
  10. // LevelDisabled: -1
  11. // LevelDefault: 0
  12. // LevelBestSpeed: 1
  13. // LevelBestCompression: 2
  14. Level int
  15. }

Default Config

  1. var ConfigDefault = Config{
  2. Next: nil,
  3. Level: LevelDefault,
  4. }

Constants

  1. // Compression levels
  2. const (
  3. LevelDisabled = -1
  4. LevelDefault = 0
  5. LevelBestSpeed = 1
  6. LevelBestCompression = 2
  7. )