forked from fragmenta/fragmenta-cms
/
handlers.go
97 lines (79 loc) · 2.38 KB
/
handlers.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
91
92
93
94
95
96
97
package app
import (
"net/http"
"os"
"path"
"strings"
"github.com/fragmenta/server"
"github.com/fragmenta/server/config"
"github.com/fragmenta/server/log"
"github.com/fragmenta/view"
)
// Serve static files (assets, images etc)
func fileHandler(w http.ResponseWriter, r *http.Request) error {
// First try serving assets
err := serveAsset(w, r)
if err == nil {
return nil
}
// If assets fail, try to serve file in public
return serveFile(w, r)
}
// serveFile serves a file from ./public if it exists
func serveFile(w http.ResponseWriter, r *http.Request) error {
// Try a local path in the public directory
localPath := "./public" + path.Clean(r.URL.Path)
s, err := os.Stat(localPath)
if err != nil {
// If file not found return 404
if os.IsNotExist(err) {
return server.NotFoundError(err)
}
// For other errors return not authorised
return server.NotAuthorizedError(err)
}
// If not a file return immediately
if s.IsDir() {
return nil
}
// If the file exists and we can access it, serve it with cache control
w.Header().Set("Cache-Control", "max-age:3456000, public")
http.ServeFile(w, r, localPath)
return nil
}
// serveAsset serves a file from ./public/assets usings appAssets
func serveAsset(w http.ResponseWriter, r *http.Request) error {
p := path.Clean(r.URL.Path)
// It must be under /assets, or we don't serve
if !strings.HasPrefix(p, "/assets/") {
return server.NotFoundError(nil)
}
// Try to find an asset in our list
f := appAssets.File(path.Base(p))
if f == nil {
return server.NotFoundError(nil)
}
// Serve the local file, with cache control
localPath := "./" + f.LocalPath()
w.Header().Set("Cache-Control", "max-age:3456000, public")
http.ServeFile(w, r, localPath)
return nil
}
// errHandler renders an error using error templates if available
func errHandler(w http.ResponseWriter, r *http.Request, e error) {
// Cast the error to a status error if it is one, if not wrap it in a Status 500 error
err := server.ToStatusError(e)
log.Error(log.V{"error": err})
view := view.NewWithPath("", w)
view.AddKey("title", err.Title)
view.AddKey("message", err.Message)
// In production, provide no detail for security reasons
if !config.Production() {
view.AddKey("status", err.Status)
view.AddKey("file", err.FileLine())
view.AddKey("error", err.Err)
}
view.Template("app/views/error.html.got")
w.WriteHeader(err.Status)
view.Render()
}