-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathfile.go
73 lines (64 loc) · 1.37 KB
/
file.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
package bon
import (
"net/http"
"os"
"path/filepath"
"strings"
)
type fileServer struct {
mux *Mux
depth int
root string
dirIndex string
}
func contentsHandle(r Router, pattern string, handlerFunc http.HandlerFunc, middlewares ...Middleware) {
p := resolvePattern(pattern)
for _, v := range []string{p, p + "*"} {
r.Handle(http.MethodGet, v, handlerFunc, middlewares...)
r.Handle(http.MethodHead, v, handlerFunc, middlewares...)
}
}
func (m *Mux) newFileServer(pattern, root string) *fileServer {
return &fileServer{
mux: m,
root: root,
depth: strings.Count(resolvePattern(pattern), "/"),
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)
}