-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
requestfilters.go
88 lines (74 loc) · 2.36 KB
/
requestfilters.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
package gzip
import (
"net/http"
"path"
"strings"
"github.com/signalsciences/ac/acascii"
)
// RequestFilter decide whether or not to compress response judging by request
type RequestFilter interface {
// ShouldCompress decide whether or not to compress response,
// judging by request
ShouldCompress(req *http.Request) bool
}
// interface guards
var (
_ RequestFilter = (*CommonRequestFilter)(nil)
_ RequestFilter = (*ExtensionFilter)(nil)
)
// CommonRequestFilter judge via common easy criteria like
// http method, accept-encoding header, etc.
type CommonRequestFilter struct{}
// NewCommonRequestFilter ...
func NewCommonRequestFilter() *CommonRequestFilter {
return &CommonRequestFilter{}
}
// ShouldCompress implements RequestFilter interface
func (c *CommonRequestFilter) ShouldCompress(req *http.Request) bool {
return req.Method != http.MethodHead &&
req.Method != http.MethodOptions &&
req.Header.Get("Upgrade") == "" &&
strings.Contains(req.Header.Get("Accept-Encoding"), "gzip")
}
// ExtensionFilter judge via the extension in path
//
// Omit this filter if you want to compress all extension.
type ExtensionFilter struct {
Exts *acascii.Matcher
AllowEmpty bool
}
// NewExtensionFilter returns a extension or panics
func NewExtensionFilter(extensions []string) *ExtensionFilter {
var (
exts = make([]string, 0, len(extensions))
allowEmpty bool
)
for _, item := range extensions {
if item == "" {
allowEmpty = true
continue
}
exts = append(exts, item)
}
return &ExtensionFilter{
Exts: acascii.MustCompileString(exts),
AllowEmpty: allowEmpty,
}
}
// ShouldCompress implements RequestFilter interface
func (e *ExtensionFilter) ShouldCompress(req *http.Request) bool {
ext := path.Ext(req.URL.Path)
if ext == "" {
return e.AllowEmpty
}
return e.Exts.MatchString(ext)
}
// defaultExtensions is the list of default extensions for which to enable gzip.
// original source:
// https://github.com/caddyserver/caddy/blob/7fa90f08aee0861187236b2fbea16b4fa69c5a28/caddyhttp/gzip/requestfilter.go#L32
var defaultExtensions = []string{"", ".txt", ".htm", ".html", ".css", ".php", ".js", ".json",
".md", ".mdown", ".xml", ".svg", ".go", ".cgi", ".py", ".pl", ".aspx", ".asp", ".m3u", ".m3u8", ".wasm"}
// DefaultExtensionFilter permits
func DefaultExtensionFilter() *ExtensionFilter {
return NewExtensionFilter(defaultExtensions)
}