common icon indicating copy to clipboard operation
common copied to clipboard

Add gzip compression middleware to server

Open yvrhdn opened this issue 4 years ago • 0 comments

Hi, we noticed that Server by default does not compress its responses, even if the client accepts this. I.e. when a http client sends a request with Accept-Encoding: gzip, the server can choose to compress the response (using gzip in this case) which will save bandwidth and is usually more efficient.

I suggest adding this to the middleware that is added by default. I'm basically echoing @bboreham's comments:

  • If it's not enabled by default, most users won't be able to profit from this
  • The Go http client will request compression and decompress responses by default, so a user will not even notice compression is used.

To implement this we can use nytimes/gziphandler. It's interface matches very closely with middleware.Interface so the entire implementation would be pretty small. gziphandler will by default only compress responses larger than 1400 bytes.

package middleware

import (
	"net/http"

	"github.com/NYTimes/gziphandler"
)

type Gzip struct {
}

func (g Gzip) Wrap(next http.Handler) http.Handler {
	return gziphandler.GzipHandler(next)
}

gziphandler is already being used by Cortex, so it has been battle tested with Server.

If this makes sense I can create a PR for this with tests etc.

yvrhdn avatar Jul 26 '21 18:07 yvrhdn