compress.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package compress
  2. import (
  3. "github.com/gofiber/fiber/v2"
  4. "github.com/valyala/fasthttp"
  5. )
  6. // New creates a new middleware handler
  7. func New(config ...Config) fiber.Handler {
  8. // Set default config
  9. cfg := configDefault(config...)
  10. // Setup request handlers
  11. var (
  12. fctx = func(c *fasthttp.RequestCtx) {}
  13. compressor fasthttp.RequestHandler
  14. )
  15. // Setup compression algorithm
  16. switch cfg.Level {
  17. case LevelDefault:
  18. // LevelDefault
  19. compressor = fasthttp.CompressHandlerBrotliLevel(fctx,
  20. fasthttp.CompressBrotliDefaultCompression,
  21. fasthttp.CompressDefaultCompression,
  22. )
  23. case LevelBestSpeed:
  24. // LevelBestSpeed
  25. compressor = fasthttp.CompressHandlerBrotliLevel(fctx,
  26. fasthttp.CompressBrotliBestSpeed,
  27. fasthttp.CompressBestSpeed,
  28. )
  29. case LevelBestCompression:
  30. // LevelBestCompression
  31. compressor = fasthttp.CompressHandlerBrotliLevel(fctx,
  32. fasthttp.CompressBrotliBestCompression,
  33. fasthttp.CompressBestCompression,
  34. )
  35. default:
  36. // LevelDisabled
  37. return func(c *fiber.Ctx) error {
  38. return c.Next()
  39. }
  40. }
  41. // Return new handler
  42. return func(c *fiber.Ctx) error {
  43. // Don't execute middleware if Next returns true
  44. if cfg.Next != nil && cfg.Next(c) {
  45. return c.Next()
  46. }
  47. // Continue stack
  48. if err := c.Next(); err != nil {
  49. return err
  50. }
  51. // Compress response
  52. compressor(c.Context())
  53. // Return from handler
  54. return nil
  55. }
  56. }