-
Notifications
You must be signed in to change notification settings - Fork 1
/
middleware.go
90 lines (75 loc) · 1.87 KB
/
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
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
78
79
80
81
82
83
84
85
86
87
88
89
90
package main
import (
"log"
"net/http"
"path"
"strings"
"github.com/zenazn/goji/web"
)
func SessionMiddleware(e *Env) func(*web.C, http.Handler) http.Handler {
return func(c *web.C, h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
e.Session = getSession(w, r)
h.ServeHTTP(w, r)
})
}
}
func StaticMiddleware(e *Env, directory string) func(*web.C, http.Handler) http.Handler {
dir := http.Dir(directory)
indexFile := "index.html"
logStaticFilesServed := false
return func(c *web.C, h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != "HEAD" && r.Method != "GET" {
h.ServeHTTP(w, r)
return
}
if r.URL.Path == "/" && requireAuth(e, w, r) {
return
}
// Get the file name from the path
file := r.URL.Path
// Open the file and get the stats
f, err := dir.Open(file)
if err != nil {
h.ServeHTTP(w, r)
return
}
defer f.Close()
fs, err := f.Stat()
if err != nil {
h.ServeHTTP(w, r)
return
}
// if the requested resource is a directory, try to serve the index file
if fs.IsDir() {
// redirect if trailling "/"" is missing
if !strings.HasSuffix(r.URL.Path, "/") {
http.Redirect(w, r, r.URL.Path+"/", http.StatusFound)
return
}
file = path.Join(file, indexFile)
f, err = dir.Open(file)
if err != nil {
h.ServeHTTP(w, r)
return
}
defer f.Close()
fs, err = f.Stat()
if err != nil || fs.IsDir() {
h.ServeHTTP(w, r)
return
}
}
if logStaticFilesServed {
log.Println("[Static] Serving " + file)
}
// Add an Expires header to the static content
// if opt.Expires != nil {
// w.Header().Set("Expires", opt.Expires())
// }
http.ServeContent(w, r, file, fs.ModTime(), f)
h.ServeHTTP(w, r)
})
}
}