forked from caddyserver/caddy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
requestfilter.go
91 lines (76 loc) · 2.42 KB
/
requestfilter.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
package gzip
import (
"net/http"
"path"
"github.com/mholt/caddy/caddyhttp/httpserver"
)
// RequestFilter determines if a request should be gzipped.
type RequestFilter interface {
// ShouldCompress tells if gzip compression
// should be done on the request.
ShouldCompress(*http.Request) bool
}
// defaultExtensions is the list of default extensions for which to enable gzipping.
var defaultExtensions = []string{"", ".txt", ".htm", ".html", ".css", ".php", ".js", ".json",
".md", ".mdown", ".xml", ".svg", ".go", ".cgi", ".py", ".pl", ".aspx", ".asp"}
// DefaultExtFilter creates an ExtFilter with default extensions.
func DefaultExtFilter() ExtFilter {
m := ExtFilter{Exts: make(Set)}
for _, extension := range defaultExtensions {
m.Exts.Add(extension)
}
return m
}
// ExtFilter is RequestFilter for file name extensions.
type ExtFilter struct {
// Exts is the file name extensions to accept
Exts Set
}
// ExtWildCard is the wildcard for extensions.
const ExtWildCard = "*"
// ShouldCompress checks if the request file extension matches any
// of the registered extensions. It returns true if the extension is
// found and false otherwise.
func (e ExtFilter) ShouldCompress(r *http.Request) bool {
ext := path.Ext(r.URL.Path)
return e.Exts.Contains(ExtWildCard) || e.Exts.Contains(ext)
}
// PathFilter is RequestFilter for request path.
type PathFilter struct {
// IgnoredPaths is the paths to ignore
IgnoredPaths Set
}
// ShouldCompress checks if the request path matches any of the
// registered paths to ignore. It returns false if an ignored path
// is found and true otherwise.
func (p PathFilter) ShouldCompress(r *http.Request) bool {
return !p.IgnoredPaths.ContainsFunc(func(value string) bool {
return httpserver.Path(r.URL.Path).Matches(value)
})
}
// Set stores distinct strings.
type Set map[string]struct{}
// Add adds an element to the set.
func (s Set) Add(value string) {
s[value] = struct{}{}
}
// Remove removes an element from the set.
func (s Set) Remove(value string) {
delete(s, value)
}
// Contains check if the set contains value.
func (s Set) Contains(value string) bool {
_, ok := s[value]
return ok
}
// ContainsFunc is similar to Contains. It iterates all the
// elements in the set and passes each to f. It returns true
// on the first call to f that returns true and false otherwise.
func (s Set) ContainsFunc(f func(string) bool) bool {
for k := range s {
if f(k) {
return true
}
}
return false
}