forked from go-martini/martini
-
Notifications
You must be signed in to change notification settings - Fork 0
/
static.go
51 lines (43 loc) · 960 Bytes
/
static.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
package martini
import (
"log"
"net/http"
"path/filepath"
)
// Static returns a middleware handler that serves static files in the given path.
func Static(path string) Handler {
dir := http.Dir(path)
return func(res http.ResponseWriter, req *http.Request, log *log.Logger) {
file := req.URL.Path
f, err := dir.Open(file)
if err != nil {
// discard the error?
return
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
return
}
// Try to serve index.html
if fi.IsDir() {
// redirect if missing trailing slash
if file[len(file)-1] != '/' {
http.Redirect(res, req, file+"/", http.StatusFound)
return
}
file = filepath.Join(file, "index.html")
f, err = dir.Open(file)
if err != nil {
return
}
defer f.Close()
fi, err = f.Stat()
if err != nil || fi.IsDir() {
return
}
}
log.Println("[Static] Serving " + file)
http.ServeContent(res, req, file, fi.ModTime(), f)
}
}