0

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?

Accio
  • 74
  • 1
  • 8
  • What request are you making you're expecting to be compressed (try to show a `curl` command)? And how do you know it's not compressed? – icza Jul 07 '22 at 09:41
  • 2
    Some errors in your code: if the client accepts both `gzip` and `br`, your loop will serve the handler twice, attempting to write headers twice. Setting up `chi.NewCompressor()` should only be done once in your app lifetime, not in every request handling. Also the compressor middleware handlers headers, you shouldn't need to check / alter them. – icza Jul 07 '22 at 10:09
  • @icza you are right, I will not create the compressor everytime but at this point I am just trying to get compressed response which does not work. I am not sure if this part works: compressor.Handler(h).ServeHTTP(w, r) – Accio Jul 07 '22 at 10:16

0 Answers0