forked from go-martini/martini
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstatic.go
More file actions
52 lines (44 loc) · 978 Bytes
/
Copy pathstatic.go
File metadata and controls
52 lines (44 loc) · 978 Bytes
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
package martini
import (
"log"
"net/http"
"path"
"strings"
)
// Static returns a middleware handler that serves static files in the given directory.
func Static(directory string) Handler {
dir := http.Dir(directory)
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 !strings.HasSuffix(file, "/") {
http.Redirect(res, req, file+"/", http.StatusFound)
return
}
file = path.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)
}
}