-
Notifications
You must be signed in to change notification settings - Fork 87
/
handler.go
83 lines (71 loc) · 1.59 KB
/
handler.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
package gzip
import (
"compress/gzip"
"fmt"
"io"
"net/http"
"path/filepath"
"strings"
"sync"
"github.com/gin-gonic/gin"
)
type gzipHandler struct {
*Options
gzPool sync.Pool
}
func newGzipHandler(level int, options ...Option) *gzipHandler {
handler := &gzipHandler{
Options: DefaultOptions,
gzPool: sync.Pool{
New: func() interface{} {
gz, err := gzip.NewWriterLevel(io.Discard, level)
if err != nil {
panic(err)
}
return gz
},
},
}
for _, setter := range options {
setter(handler.Options)
}
return handler
}
func (g *gzipHandler) Handle(c *gin.Context) {
if fn := g.DecompressFn; fn != nil && c.Request.Header.Get("Content-Encoding") == "gzip" {
fn(c)
}
if !g.shouldCompress(c.Request) {
return
}
gz := g.gzPool.Get().(*gzip.Writer)
defer g.gzPool.Put(gz)
defer gz.Reset(io.Discard)
gz.Reset(c.Writer)
c.Header("Content-Encoding", "gzip")
c.Header("Vary", "Accept-Encoding")
c.Writer = &gzipWriter{c.Writer, gz}
defer func() {
gz.Close()
c.Header("Content-Length", fmt.Sprint(c.Writer.Size()))
}()
c.Next()
}
func (g *gzipHandler) shouldCompress(req *http.Request) bool {
if !strings.Contains(req.Header.Get("Accept-Encoding"), "gzip") ||
strings.Contains(req.Header.Get("Connection"), "Upgrade") ||
strings.Contains(req.Header.Get("Accept"), "text/event-stream") {
return false
}
extension := filepath.Ext(req.URL.Path)
if g.ExcludedExtensions.Contains(extension) {
return false
}
if g.ExcludedPaths.Contains(req.URL.Path) {
return false
}
if g.ExcludedPathesRegexs.Contains(req.URL.Path) {
return false
}
return true
}