diff options
author | nirav <nirav@teisuu.com> | 2021-10-10 06:48:37 +0000 |
---|---|---|
committer | nirav <nirav@teisuu.com> | 2021-10-10 06:48:37 +0000 |
commit | ea6350e4ea7d1978dee0bbeba5fcaaace539aa4c (patch) | |
tree | ab516a8000601fa48d369e01421a12103415edc9 /handler.go | |
download | gziphandler-ea6350e4ea7d1978dee0bbeba5fcaaace539aa4c.tar.gz gziphandler-ea6350e4ea7d1978dee0bbeba5fcaaace539aa4c.zip |
Initial commit
Diffstat (limited to 'handler.go')
-rw-r--r-- | handler.go | 53 |
1 files changed, 53 insertions, 0 deletions
diff --git a/handler.go b/handler.go new file mode 100644 index 0000000..ab21180 --- /dev/null +++ b/handler.go @@ -0,0 +1,53 @@ +package gziphandler + +import ( + "compress/gzip" + "net/http" + "strings" +) + +type gw struct { + http.ResponseWriter + w *gzip.Writer +} + +func (w *gw) Write(d []byte) (int, error) { + return w.w.Write(d) +} + +func (w *gw) Close() error { + return w.w.Close() +} + +func acceptsGzip(r *http.Request) bool { + ae := r.Header.Get("Accept-Encoding") + for _, e := range strings.Split(ae, ",") { + vals := strings.Split(e, ";") + if len(vals) < 1 { + continue + } + if strings.TrimSpace(vals[0]) == "gzip" { + return true + } + } + return false +} + +// Handler returns an http.Handler that compresses the response data written +// by an existing handler h, using the compress/gzip.Writer with default +// compression level. +func Handler(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !acceptsGzip(r) { + h.ServeHTTP(w, r) + return + } + w.Header().Set("Content-Encoding", "gzip") + gw := &gw{ + ResponseWriter: w, + w: gzip.NewWriter(w), + } + h.ServeHTTP(gw, r) + gw.Close() + }) +} |