Repository: thrift Updated Branches: refs/heads/master 9a745aa4a -> b67cad46e
THRIFT-4197 Implement transparent gzip compression for HTTP transport Client: Go Patch: D. Can Celasun <[email protected]> This closes #1266 Project: http://git-wip-us.apache.org/repos/asf/thrift/repo Commit: http://git-wip-us.apache.org/repos/asf/thrift/commit/b67cad46 Tree: http://git-wip-us.apache.org/repos/asf/thrift/tree/b67cad46 Diff: http://git-wip-us.apache.org/repos/asf/thrift/diff/b67cad46 Branch: refs/heads/master Commit: b67cad46e43c2a88e6f9cc986a9f0c3b6b300971 Parents: 9a745aa Author: D. Can Celasun <[email protected]> Authored: Thu May 11 12:04:01 2017 +0200 Committer: Jens Geyer <[email protected]> Committed: Sat May 13 13:58:02 2017 +0200 ---------------------------------------------------------------------- lib/go/thrift/http_transport.go | 33 +++++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) ---------------------------------------------------------------------- http://git-wip-us.apache.org/repos/asf/thrift/blob/b67cad46/lib/go/thrift/http_transport.go ---------------------------------------------------------------------- diff --git a/lib/go/thrift/http_transport.go b/lib/go/thrift/http_transport.go index f6d7458..e395d20 100644 --- a/lib/go/thrift/http_transport.go +++ b/lib/go/thrift/http_transport.go @@ -19,16 +19,45 @@ package thrift -import "net/http" +import ( + "compress/gzip" + "io" + "net/http" + "strings" +) // NewThriftHandlerFunc is a function that create a ready to use Apache Thrift Handler function func NewThriftHandlerFunc(processor TProcessor, inPfactory, outPfactory TProtocolFactory) func(w http.ResponseWriter, r *http.Request) { - return func(w http.ResponseWriter, r *http.Request) { + return gz(func(w http.ResponseWriter, r *http.Request) { w.Header().Add("Content-Type", "application/x-thrift") transport := NewStreamTransport(r.Body, w) processor.Process(inPfactory.GetProtocol(transport), outPfactory.GetProtocol(transport)) + }) +} + +// gz transparently compresses the HTTP response if the client supports it. +func gz(handler http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") { + handler(w, r) + return + } + w.Header().Set("Content-Encoding", "gzip") + gz := gzip.NewWriter(w) + defer gz.Close() + gzw := gzipResponseWriter{Writer: gz, ResponseWriter: w} + handler(gzw, r) } } + +type gzipResponseWriter struct { + io.Writer + http.ResponseWriter +} + +func (w gzipResponseWriter) Write(b []byte) (int, error) { + return w.Writer.Write(b) +}
