github.com/angenalZZZ/gofunc@v0.0.0-20210507121333-48ff1be3917b/http/fast/middleware/compression/compression.go (about) 1 package compression 2 3 import ( 4 "github.com/angenalZZZ/gofunc/http/fast" 5 "github.com/valyala/fasthttp" 6 ) 7 8 // Supported compression levels 9 const ( 10 LevelNoCompression = -1 11 LevelDefaultCompression = 0 12 LevelBestSpeed = 1 13 LevelBestCompression = 2 14 LevelHuffmanOnly = 3 15 ) 16 17 // Config defines the config for compression middleware 18 type Config struct { 19 // Filter defines a function to skip middleware. 20 // Optional. Default: nil 21 Filter func(*fast.Ctx) bool 22 // Level of compression 23 // Optional. Default value 0. 24 Level int 25 } 26 27 // New middleware. 28 // cfg := compression.Config{ 29 // Level: compression.LevelBestSpeed, 30 // } 31 // app.Use(compression.New(cfg)) 32 func New(config ...Config) func(*fast.Ctx) { 33 // Init config 34 var cfg Config 35 if len(config) > 0 { 36 cfg = config[0] 37 } 38 // Convert compress levels to correct int 39 // https://github.com/valyala/fasthttp/blob/master/compress.go#L17 40 switch cfg.Level { 41 case -1: 42 cfg.Level = 0 43 case 1: 44 cfg.Level = 1 45 case 2: 46 cfg.Level = 9 47 case 3: 48 cfg.Level = -2 49 default: 50 cfg.Level = 6 51 } 52 compress := fasthttp.CompressHandlerLevel(func(c *fasthttp.RequestCtx) { return }, cfg.Level) 53 // Middleware function 54 return func(c *fast.Ctx) { 55 // Filter request to skip middleware 56 if cfg.Filter != nil && cfg.Filter(c) { 57 c.Next() 58 return 59 } 60 c.Next() 61 compress(c.C) 62 } 63 }