-
Notifications
You must be signed in to change notification settings - Fork 351
/
etag_middleware.go
78 lines (71 loc) · 1.53 KB
/
etag_middleware.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
package api
import (
"crypto/md5" //nolint:gosec
"encoding/hex"
"io"
"io/fs"
"net/http"
"path"
"strings"
)
// EtagMiddleware returns a new Etag middleware handler.
// It designs to work on embedded FS, where the content doesn't change.
// It calculates the Etag for each file on startup and serves it on each request.
func EtagMiddleware(root fs.FS, next http.Handler) http.Handler {
etags, err := scanFSEtags(root)
if err != nil {
panic(err)
}
return &etagHandler{
root: root,
next: next,
etags: etags,
}
}
type etagHandler struct {
root fs.FS
next http.Handler
etags map[string]string
}
func (e *etagHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
upath := r.URL.Path
if !strings.HasPrefix(upath, "/") {
upath = "/" + upath
}
upath = path.Clean(upath)
if strings.HasSuffix(upath, "/") {
upath += "index.html"
}
etag, ok := e.etags[upath]
if ok {
w.Header().Set("Etag", "\""+etag+"\"")
}
e.next.ServeHTTP(w, r)
}
func scanFSEtags(fSys fs.FS) (map[string]string, error) {
etags := make(map[string]string)
err := fs.WalkDir(fSys, ".", func(fpath string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
f, err := fSys.Open(fpath)
if err != nil {
return err
}
defer func() { _ = f.Close() }()
h := md5.New() //nolint:gosec
if _, err := io.Copy(h, f); err != nil {
return err
}
hashValue := hex.EncodeToString(h.Sum(nil))
etags["/"+fpath] = hashValue
return nil
})
if err != nil {
return nil, err
}
return etags, nil
}