diff options
author | Steve <nilslice@gmail.com> | 2017-02-13 11:06:14 -0800 |
---|---|---|
committer | GitHub <noreply@github.com> | 2017-02-13 11:06:14 -0800 |
commit | 4222b04d45b2932022c71eecf909e0e43f5f9d9d (patch) | |
tree | df0a0cc191834d9220fe5a9f952ad61c9527a43e /system/api/gzip.go | |
parent | 7a85b284dec2bbb462969fb7e9e949b1a2ae720a (diff) | |
parent | 46d7c021d8de124be803b5c10f157c132343ab4e (diff) |
Merge pull request #73 from ponzu-cms/ponzu-dev
[core] Adding support to omit fields from json response, minor code reorganization
Diffstat (limited to 'system/api/gzip.go')
-rw-r--r-- | system/api/gzip.go | 64 |
1 files changed, 64 insertions, 0 deletions
diff --git a/system/api/gzip.go b/system/api/gzip.go new file mode 100644 index 0000000..be5a51b --- /dev/null +++ b/system/api/gzip.go @@ -0,0 +1,64 @@ +package api + +import ( + "compress/gzip" + "net/http" + "strings" + + "github.com/ponzu-cms/ponzu/system/db" +) + +// Gzip wraps a HandlerFunc to compress responses when possible +func Gzip(next http.HandlerFunc) http.HandlerFunc { + return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + if db.ConfigCache("gzip_disabled").(bool) == true { + next.ServeHTTP(res, req) + return + } + + // check if req header content-encoding supports gzip + if strings.Contains(req.Header.Get("Accept-Encoding"), "gzip") { + // gzip response data + res.Header().Set("Content-Encoding", "gzip") + var gzres gzipResponseWriter + if pusher, ok := res.(http.Pusher); ok { + gzres = gzipResponseWriter{res, pusher, gzip.NewWriter(res)} + } else { + gzres = gzipResponseWriter{res, nil, gzip.NewWriter(res)} + } + + next.ServeHTTP(gzres, req) + return + } + + next.ServeHTTP(res, req) + }) +} + +type gzipResponseWriter struct { + http.ResponseWriter + pusher http.Pusher + + gw *gzip.Writer +} + +func (gzw gzipResponseWriter) Write(p []byte) (int, error) { + defer gzw.gw.Close() + return gzw.gw.Write(p) +} + +func (gzw gzipResponseWriter) Push(target string, opts *http.PushOptions) error { + if gzw.pusher == nil { + return nil + } + + if opts == nil { + opts = &http.PushOptions{ + Header: make(http.Header), + } + } + + opts.Header.Set("Accept-Encoding", "gzip") + + return gzw.pusher.Push(target, opts) +} |