This repository has been archived by the owner on Jul 18, 2020. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathminify.go
64 lines (52 loc) · 1.35 KB
/
minify.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
// Package minify provides middlewarefor minifying each request before being
// sent to the browser.
package minify
import (
"net/http"
"github.com/caddyserver/caddy/caddyhttp/httpserver"
"github.com/tdewolff/minify/v2"
)
var minifier *minify.M
// Minify is an http.Handler that is able to minify the request before it's sent
// to the browser.
type Minify struct {
Next httpserver.Handler
Rules []httpserver.RequestMatcher
Paths []string
}
// ServeHTTP is the main function of the whole plugin that routes every single
// request to its function.
func (m Minify) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
// checks if the middlware should handle this request or not
if m.shouldHandle(r) {
mw := minifier.ResponseWriter(w, r)
defer mw.Close()
return m.Next.ServeHTTP(httpserver.ResponseWriterWrapper{
ResponseWriter: mw,
}, r)
}
return m.Next.ServeHTTP(w, r)
}
// shouldHandle checks if the request should be handled with minifier
// using the BasePath and Excludes
func (m Minify) shouldHandle(r *http.Request) bool {
included := false
if len(m.Paths) > 0 {
for _, path := range m.Paths {
if httpserver.Path(r.URL.Path).Matches(path) {
included = true
}
}
} else {
included = true
}
if !included {
return false
}
for _, rule := range m.Rules {
if !rule.Match(r) {
return false
}
}
return true
}