forked from gocraft/web
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstatic_middleware.go
46 lines (40 loc) · 890 Bytes
/
static_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
package web
import (
"net/http"
"path/filepath"
)
// StaticMiddleware("public") returns proper middleware
// NOTE: original impl is from github.com/codegangsta/martini
func StaticMiddleware(path string) func(ResponseWriter, *Request, NextMiddlewareFunc) {
dir := http.Dir(path)
return func(w ResponseWriter, req *Request, next NextMiddlewareFunc) {
file := req.URL.Path
f, err := dir.Open(file)
if err != nil {
next(w, req)
return
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
next(w, req)
return
}
// Try to serve index.html
if fi.IsDir() {
file = filepath.Join(file, "index.html")
f, err = dir.Open(file)
if err != nil {
next(w, req)
return
}
defer f.Close()
fi, err = f.Stat()
if err != nil || fi.IsDir() {
next(w, req)
return
}
}
http.ServeContent(w, req.Request, file, fi.ModTime(), f)
}
}