-
Notifications
You must be signed in to change notification settings - Fork 0
/
filesystem.go
60 lines (50 loc) · 1.37 KB
/
filesystem.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
// Package filesystem handles open files and folder directories.
// This implementation specifically disallows directory listings.
package filesystem
import (
"net/http"
"strings"
"github.com/go-chi/chi"
)
// FileSystem interface to allow access to local files
type FileSystem interface {
Open(name string) (http.File, error)
}
// Myfs is the accessible directory
type Myfs struct {
Dir http.Dir
}
// Open returns the file if available.
// It will not return directory listings
func (m Myfs) Open(name string) (result http.File, err error) {
f, err := m.Dir.Open(name)
if err != nil {
return
}
fi, err := f.Stat()
if err != nil {
return
}
if fi.IsDir() {
// Return a response that would have occured if directory didn't exist
return m.Dir.Open("does-not-exist")
}
return f, nil
}
// FileServer serves the requested file
func FileServer(r chi.Router, path string, root http.FileSystem) {
if strings.ContainsAny(path, "{}*") {
panic("FileServer does not permit URL parameters")
}
if path != "/" && path[len(path)-1] != '/' {
r.Get(path, http.RedirectHandler(path+"/", 301).ServeHTTP)
path += "/"
}
path += "*"
r.Get(path, func(w http.ResponseWriter, r *http.Request) {
rctx := chi.RouteContext(r.Context())
pathPrefix := strings.TrimSuffix(rctx.RoutePattern(), "/*")
fs := http.StripPrefix(pathPrefix, http.FileServer(root))
fs.ServeHTTP(w, r)
})
}