Hey guys I am trying to create a middleware that compresses the response depending on the "Accept-Encoding" header. I have created this logic according:
func compress(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
for _, enc := range strings.Split(r.Header.Get("Accept-Encoding"), ",") {
switch strings.TrimSpace(enc) {
case "br":
fmt.Println("br")
w.Header().Set("Content-Encoding", "br")
r.Header.Del("Accept-Encoding")
w.Header().Add("Vary", "Accept-Encoding")
compressor := chi.NewCompressor(5, "/*")
compressor.SetEncoder("br", func(w io.Writer, level int) io.Writer {
params := brotli_enc.NewBrotliParams()
params.SetQuality(level)
return brotli_enc.NewBrotliWriter(params, w)
})
compressor.Handler(h).ServeHTTP(w, r)
case "gzip":
fmt.Println("gzip")
w.Header().Set("Content-Encoding", "gzip")
r.Header.Del("Accept-Encoding")
w.Header().Add("Vary", "Accept-Encoding")
h.ServeHTTP(w, r)
}
}
})
}
And then I use the middleware on the handler like such:
compress(handler)
However this returns the response body uncompressed. Am I missing something?