/
compress.go
49 lines (44 loc) · 1.36 KB
/
compress.go
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
package httpcompress
import (
"compress/gzip"
"io"
"net/http"
"strings"
"github.com/andybalholm/brotli"
)
// CompressResponseWriter is a Struct for manipulating io writer
type CompressResponseWriter struct {
io.Writer
http.ResponseWriter
}
func (res CompressResponseWriter) Write(b []byte) (int, error) {
if "" == res.Header().Get("Content-Type") {
// If no content type, apply sniffing algorithm to un-gzipped body.
res.Header().Set("Content-Type", http.DetectContentType(b))
}
return res.Writer.Write(b)
}
// Middleware force - bool, whether or not to force Compression regardless of the sent headers.
func Middleware(fn http.HandlerFunc, force bool) http.HandlerFunc {
return func(res http.ResponseWriter, req *http.Request) {
if !strings.Contains(req.Header.Get("Accept-Encoding"), "br") {
if !strings.Contains(req.Header.Get("Accept-Encoding"), "gzip") && !force {
fn(res, req)
return
}
res.Header().Set("Vary", "Accept-Encoding")
res.Header().Set("Content-Encoding", "gzip")
gz := gzip.NewWriter(res)
defer gz.Close()
cw := CompressResponseWriter{Writer: gz, ResponseWriter: res}
fn(cw, req)
return
}
res.Header().Set("Vary", "Accept-Encoding")
res.Header().Set("Content-Encoding", "br")
br := brotli.NewWriter(res)
defer br.Close()
cw := CompressResponseWriter{Writer: br, ResponseWriter: res}
fn(cw, req)
}
}