Skip to content

Commit

Permalink
compress: allow config level (#145)
Browse files Browse the repository at this point in the history
* compress: allow config level

* refactor
  • Loading branch information
acoshift committed Jun 10, 2023
1 parent bbe5ebb commit da4a4d3
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 5 deletions.
15 changes: 12 additions & 3 deletions pkg/compress/br.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,17 @@ import (

// Br creates new brotli compress middleware
func Br() *Compress {
return BrWithOption(cbrotli.WriterOptions{Quality: 4})
}

func BrWithQuality(quality int) *Compress {
return BrWithOption(cbrotli.WriterOptions{Quality: quality})
}

func BrWithOption(opt cbrotli.WriterOptions) *Compress {
return &Compress{
New: func() Compressor {
return &brWriter{quality: 4}
return &brWriter{opt: &opt}
},
Encoding: "br",
Vary: defaultCompressVary,
Expand All @@ -22,10 +30,11 @@ func Br() *Compress {
}

type brWriter struct {
quality int
*cbrotli.Writer

opt *cbrotli.WriterOptions
}

func (w *brWriter) Reset(p io.Writer) {
w.Writer = cbrotli.NewWriter(p, cbrotli.WriterOptions{Quality: w.quality})
w.Writer = cbrotli.NewWriter(p, *w.opt)
}
2 changes: 1 addition & 1 deletion pkg/compress/compress.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ func (m Compress) ServeHandler(h http.Handler) http.Handler {
}

pool := &sync.Pool{
New: func() interface{} {
New: func() any {
return m.New()
},
}
Expand Down
6 changes: 5 additions & 1 deletion pkg/compress/gzip.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,13 @@ import (

// Gzip creates new gzip compress middleware
func Gzip() *Compress {
return GzipWithLevel(gzip.DefaultCompression)
}

func GzipWithLevel(level int) *Compress {
return &Compress{
New: func() Compressor {
g, err := gzip.NewWriterLevel(io.Discard, gzip.DefaultCompression)
g, err := gzip.NewWriterLevel(io.Discard, level)
if err != nil {
panic(err)
}
Expand Down

0 comments on commit da4a4d3

Please sign in to comment.