github.com/gofiber/fiber/v2@v2.47.0/middleware/compress/compress.go (about)

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