1
0
mirror of https://github.com/gofiber/fiber.git synced 2025-02-20 22:52:53 +00:00

🧹 Pre-initialize all compress handlers

This commit is contained in:
Larry Lv 2020-07-31 22:19:19 -07:00
parent d38419ebbc
commit d18689558e
No known key found for this signature in database
GPG Key ID: 8500335BD174D408
2 changed files with 13 additions and 11 deletions

View File

@ -27,6 +27,13 @@ var CompressConfigDefault = CompressConfig{
Level: CompressLevelDefault,
}
var compressHandlers = map[int]fasthttp.RequestHandler{
CompressLevelDisabled: fasthttp.CompressHandlerBrotliLevel(func(c *fasthttp.RequestCtx) {}, fasthttp.CompressBrotliNoCompression, fasthttp.CompressNoCompression),
CompressLevelDefault: fasthttp.CompressHandlerBrotliLevel(func(c *fasthttp.RequestCtx) {}, fasthttp.CompressBrotliDefaultCompression, fasthttp.CompressDefaultCompression),
CompressLevelBestSpeed: fasthttp.CompressHandlerBrotliLevel(func(c *fasthttp.RequestCtx) {}, fasthttp.CompressBrotliBestSpeed, fasthttp.CompressBestSpeed),
CompressLevelBestCompression: fasthttp.CompressHandlerBrotliLevel(func(c *fasthttp.RequestCtx) {}, fasthttp.CompressBrotliBestCompression, fasthttp.CompressBestCompression),
}
/*
Compress allows the following config arguments in any order:
- Compress()
@ -58,17 +65,12 @@ func Compress(options ...interface{}) fiber.Handler {
func compress(config CompressConfig) fiber.Handler {
// Init middleware settings
var compressHandler fasthttp.RequestHandler
switch config.Level {
case -1: // Disabled
compressHandler = fasthttp.CompressHandlerBrotliLevel(func(c *fasthttp.RequestCtx) {}, fasthttp.CompressBrotliNoCompression, fasthttp.CompressNoCompression)
case 1: // Best speed
compressHandler = fasthttp.CompressHandlerBrotliLevel(func(c *fasthttp.RequestCtx) {}, fasthttp.CompressBrotliBestSpeed, fasthttp.CompressBestSpeed)
case 2: // Best compression
compressHandler = fasthttp.CompressHandlerBrotliLevel(func(c *fasthttp.RequestCtx) {}, fasthttp.CompressBrotliBestCompression, fasthttp.CompressBestCompression)
default: // Default
compressHandler = fasthttp.CompressHandlerBrotliLevel(func(c *fasthttp.RequestCtx) {}, fasthttp.CompressBrotliDefaultCompression, fasthttp.CompressDefaultCompression)
compressHandler, ok := compressHandlers[config.Level]
if !ok {
// Use default level if provided level is invalid
compressHandler = compressHandlers[CompressLevelDefault]
}
// Return handler
return func(c *fiber.Ctx) {
// Don't execute the middleware if Next returns false

View File

@ -144,7 +144,7 @@ func Test_Middleware_Compress_Panic(t *testing.T) {
Compress("invalid")
}
// go test -v -run=^$ -bench=Benchmark_Middleware_Compress -benchmem -count=4
// go test -v ./... -run=^$ -bench=Benchmark_Middleware_Compress -benchmem -count=4
func Benchmark_Middleware_Compress(b *testing.B) {
app := fiber.New()
app.Use(Compress())