-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile_server.go
More file actions
77 lines (70 loc) · 1.63 KB
/
file_server.go
File metadata and controls
77 lines (70 loc) · 1.63 KB
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
package mux
import (
"io"
"io/fs"
"mime"
"net/http"
"os"
"path"
"strconv"
"strings"
)
// CacheControlFS represents the ability to associate
// a Cache-Control response header with a file name.
type CacheControlFS interface {
fs.FS
CacheControl(name string) string
}
// assetCacheFS implements the CacheControlFS interface.
type assetCacheFS struct {
fs.FS
}
// CacheControl implements the CacheControlFS interface.
func (c *assetCacheFS) CacheControl(name string) string {
return "public, max-age=31536000"
}
// AssetCacheFS returns the fs as an implementation of CacheControlFS.
// All files will be cached with the "public, max-age=31536000" policy.
func AssetCacheFS(fs fs.FS) fs.FS {
return &assetCacheFS{fs}
}
// fileServer is a simplified file server.
type fileServer struct {
h *Handler
fs fs.FS
}
// ServeHTTP implements the http.Handler interface.
func (h *fileServer) ServeHTTP(w http.ResponseWriter, req *http.Request) {
name := path.Clean(req.URL.Path)
name = strings.TrimPrefix(name, "/")
f, err := h.fs.Open(name)
if err != nil {
if os.IsNotExist(err) {
h.h.Abort(w, req, ErrNotFound)
return
}
h.h.Abort(w, req, err)
return
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
h.h.Abort(w, req, err)
return
}
if fi.IsDir() {
h.h.Abort(w, req, ErrNotFound)
return
}
cfs, ok := h.fs.(CacheControlFS)
if ok {
w.Header().Set("Cache-Control", cfs.CacheControl(name))
}
w.Header().Set("Content-Length", strconv.FormatInt(fi.Size(), 10))
w.Header().Set("Content-Type", mime.TypeByExtension(path.Ext(name)))
w.WriteHeader(http.StatusOK)
if req.Method == http.MethodHead {
return
}
io.Copy(w, f)
}