File size: 2,036 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package app

import (
	"compress/gzip"
	"io"
	"net/http"
	"strings"
	"sync"

	"github.com/felixge/httpsnoop"
)

var gzPool = sync.Pool{New: func() interface{} { return gzip.NewWriter(nil) }}

// wrapGzip will wrap an http.Handler to respond with gzip encoding.
func wrapGzip(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		if !strings.Contains(req.Header.Get("Accept-Encoding"), "gzip") || req.Header.Get("Range") != "" {
			// Normal pass-through if gzip isn't accepted, there's no content type, or a Range is requested.
			//
			// Not going to handle the whole Transfer-Encoding vs Content-Encoding stuff -- just disable
			// gzip in this case.
			next.ServeHTTP(w, req)
			return
		}

		// If gzip is asked for, and we're not already replying with gzip
		// then wrap it. This is important as if we are proxying
		// UI assets (for example) we don't want to re-compress an already
		// compressed payload.

		var output io.Writer
		var check sync.Once
		cleanup := func() {}
		getOutput := func() {
			if w.Header().Get("Content-Encoding") != "" || w.Header().Get("Content-Type") == "" {
				// already encoded
				output = w
				return
			}

			gz := gzPool.Get().(*gzip.Writer)
			gz.Reset(w)
			w.Header().Set("Content-Encoding", "gzip")
			w.Header().Set("Vary", "Accept-Encoding")
			w.Header().Del("Content-Length")
			cleanup = func() {
				_ = gz.Close()
				gzPool.Put(gz)
			}
			output = gz
		}

		ww := httpsnoop.Wrap(w, httpsnoop.Hooks{
			WriteHeader: func(next httpsnoop.WriteHeaderFunc) httpsnoop.WriteHeaderFunc { check.Do(getOutput); return next },
			Write: func(next httpsnoop.WriteFunc) httpsnoop.WriteFunc {
				return func(b []byte) (int, error) { check.Do(getOutput); return output.Write(b) }
			},
			ReadFrom: func(next httpsnoop.ReadFromFunc) httpsnoop.ReadFromFunc {
				return func(src io.Reader) (int64, error) { check.Do(getOutput); return io.Copy(output, src) }
			},
		})

		defer func() { cleanup() }()
		next.ServeHTTP(ww, req)
	})
}