-
Notifications
You must be signed in to change notification settings - Fork 3
/
fs.go
77 lines (67 loc) · 1.52 KB
/
fs.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
package bon
import (
"net/http"
"os"
"path/filepath"
"strings"
)
type fileServer struct {
mux *Mux
depth int
root string
dirIndex string
}
func dirDepth(v string) int {
return strings.Count(resolvePattern(v), "/")
}
func contentsHandle(r Router, pattern string, handlerFunc http.HandlerFunc, middlewares ...Middleware) {
pattern = resolvePattern(pattern)
r.Handle(http.MethodGet, pattern, handlerFunc, middlewares...)
r.Handle(http.MethodGet, pattern+"*", handlerFunc, middlewares...)
r.Handle(http.MethodHead, pattern, handlerFunc, middlewares...)
r.Handle(http.MethodHead, pattern+"*", handlerFunc, middlewares...)
}
func (m *Mux) newFileServer(pattern, root string, depth int) *fileServer {
return &fileServer{
mux: m,
root: root,
depth: depth,
dirIndex: "index.html",
}
}
func (fs *fileServer) resolveFilePath(v string) string {
var s, i int
for ; i < len(v); i++ {
if v[i] == '/' {
s++
if fs.depth == s {
break
}
}
}
return filepath.Join(fs.root, v[i:])
}
func (fs *fileServer) contents(w http.ResponseWriter, r *http.Request) {
file := fs.resolveFilePath(r.URL.Path)
f, err := os.Open(file)
if err != nil {
fs.mux.NotFound(w, r)
return
}
defer f.Close()
fi, _ := f.Stat()
if fi.IsDir() {
file = filepath.Join(file, fs.dirIndex)
f, err = os.Open(file)
if err != nil {
fs.mux.NotFound(w, r)
return
}
defer f.Close()
if fi, err = f.Stat(); err != nil {
fs.mux.NotFound(w, r)
return
}
}
http.ServeContent(w, r, fi.Name(), fi.ModTime(), f)
}