/
gin_brotli.go
102 lines (84 loc) · 2.15 KB
/
gin_brotli.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package gbrotli
import (
"fmt"
"net/http"
"path/filepath"
"strings"
"github.com/andybalholm/brotli"
"github.com/gin-gonic/gin"
)
type brotliWriter struct {
gin.ResponseWriter
writer *brotli.Writer
}
func (br *brotliWriter) WriteString(s string) (int, error) {
return br.writer.Write([]byte(s))
}
func (br *brotliWriter) Write(data []byte) (int, error) {
return br.writer.Write(data)
}
// Fix: https://github.com/mholt/caddy/issues/38
func (br *brotliWriter) WriteHeader(code int) {
br.Header().Del("Content-Length")
br.ResponseWriter.WriteHeader(code)
}
var (
// DefaultCompression Quality: 4 LGWin: 11
// from 0-11. 4 will bring the files faster than 11. the higher quality the slower compression time
DefaultCompression = Options{
WriterOptions: brotli.WriterOptions{
Quality: 4,
LGWin: 11,
},
SkipExtensions: []string{".png", ".gif", ".jpeg", ".jpg", ".mp3", ".mp4"},
}
)
// Options is a wrapper for cbrotli.WriterOptions
type Options struct {
brotli.WriterOptions
SkipExtensions []string
}
// Brotli is a middleware function
func Brotli(options Options) gin.HandlerFunc {
return func(c *gin.Context) {
if !shouldCompress(c.Request, &options) {
return
}
brWriter := brotli.NewWriterOptions(c.Writer, brotli.WriterOptions{
Quality: options.Quality,
LGWin: options.LGWin,
})
c.Header("Content-Encoding", "br")
c.Header("Vary", "Accept-Encoding")
c.Writer = &brotliWriter{c.Writer, brWriter}
defer func() {
brWriter.Close()
c.Header("Content-Length", fmt.Sprint(c.Writer.Size()))
}()
c.Next()
}
}
func containsString(s []string, e string) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
func shouldCompress(req *http.Request, options *Options) bool {
if !strings.Contains(req.Header.Get("Accept-Encoding"), "br") ||
strings.Contains(req.Header.Get("Connection"), "Upgrade") ||
strings.Contains(req.Header.Get("Content-Type"), "text/event-stream") {
return false
}
extension := filepath.Ext(req.URL.Path)
if len(extension) < 4 { // fast path
return true
}
if skip := containsString(options.SkipExtensions, extension); skip {
return false
} else {
return true
}
}