From 2b5565a2e724f8473fe3e42b378690a6a2e500cd Mon Sep 17 00:00:00 2001 From: Cory LaNou Date: Wed, 4 Feb 2015 16:16:37 -0700 Subject: [PATCH] add gzip response capability to httpd endpoints. fixes #1449 --- httpd/handler.go | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/httpd/handler.go b/httpd/handler.go index d42b4748b8..508bcc06eb 100644 --- a/httpd/handler.go +++ b/httpd/handler.go @@ -4,6 +4,7 @@ import ( "encoding/json" "errors" "fmt" + "io" "log" "net/http" "net/url" @@ -12,6 +13,8 @@ import ( "strings" "time" + "compress/gzip" + "code.google.com/p/go-uuid/uuid" "github.com/bmizerany/pat" @@ -92,6 +95,7 @@ func NewHandler(s *influxdb.Server, requireAuthentication bool, version string) handler = http.HandlerFunc(hf) } + handler = gzipFilter(handler) handler = versionHeader(handler, version) handler = cors(handler) handler = requestID(handler) @@ -376,6 +380,29 @@ func authenticate(inner func(http.ResponseWriter, *http.Request, *influxdb.User) }) } +type gzipResponseWriter struct { + io.Writer + http.ResponseWriter +} + +func (w gzipResponseWriter) Write(b []byte) (int, error) { + return w.Writer.Write(b) +} + +// determines if the client can accept compressed responses, and encodes accordingly +func gzipFilter(inner http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") { + inner.ServeHTTP(w, r) + } + w.Header().Set("Content-Encoding", "gzip") + gz := gzip.NewWriter(w) + defer gz.Close() + gzw := gzipResponseWriter{Writer: gz, ResponseWriter: w} + inner.ServeHTTP(gzw, r) + }) +} + // versionHeader taks a HTTP handler and returns a HTTP handler // and adds the X-INFLUXBD-VERSION header to outgoing responses. func versionHeader(inner http.Handler, version string) http.Handler {