-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler_static.go
62 lines (52 loc) · 1.42 KB
/
handler_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
52
53
54
55
56
57
58
59
60
61
62
package httpu
import (
"net/http"
"os"
"path"
"strings"
)
//StaticHandler serves file or execute handler if file not found
// httpu.StaticHandler("assets", "index.html") // if not found goes to index.html
//
func StaticHandler(assetsPath string, catch interface{}) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
urlPath := "" // FilePath
server := r.Context().Value(http.ServerContextKey).(*http.Server)
// this is Like solving handler twice
mux, ok := server.Handler.(*http.ServeMux)
if ok { //
_, handlerPath := mux.Handler(r)
urlPath = strings.TrimPrefix(r.URL.String(), handlerPath)
}
sPath := path.Join(assetsPath, urlPath)
fstat, err := os.Stat(sPath)
if err != nil || fstat.IsDir() {
switch t := catch.(type) {
case http.HandlerFunc:
t(w, r) // catchHandler
case string:
http.ServeFile(w, r, path.Join(assetsPath, t))
}
return
}
http.ServeFile(w, r, sPath)
})
}
type catchHelper struct {
http.ResponseWriter
statusCode int
}
func (c *catchHelper) WriteHeader(code int) {
c.statusCode = code
}
// CatchAllHandler will execute catch handler if error >= 400
// Might not work if handler uses Write on 404
func CatchAllHandler(next http.HandlerFunc, catch http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
c := &catchHelper{w, 200}
next(c, r)
if c.statusCode >= 400 {
catch(w, r)
}
}
}