/
frontend.go
106 lines (85 loc) · 2.24 KB
/
frontend.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
98
99
100
101
102
103
104
105
106
package web
import (
"embed"
"errors"
"io/fs"
"net/http"
"path"
"strings"
"github.com/ethpandaops/assertoor/pkg/coordinator/web/types"
"github.com/sirupsen/logrus"
)
var logger = logrus.New().WithField("module", "frontend")
var frontendConfig *types.FrontendConfig
var (
//go:embed static/*
staticEmbedFS embed.FS
//go:embed templates/*
templateEmbedFS embed.FS
)
type Frontend struct {
defaultHandler http.Handler
rootFileSys http.FileSystem
NotFoundHandler func(http.ResponseWriter, *http.Request)
}
func NewFrontend(config *types.FrontendConfig) (*Frontend, error) {
frontendConfig = config
if frontendConfig.SiteName == "" {
frontendConfig.SiteName = "Assertoor"
}
subFs, err := fs.Sub(staticEmbedFS, "static")
if err != nil {
return nil, err
}
fileSys := http.FS(subFs)
templateFiles, err = fs.Sub(templateEmbedFS, "templates")
if err != nil {
return nil, err
}
frontend := Frontend{
defaultHandler: http.FileServer(fileSys),
rootFileSys: fileSys,
NotFoundHandler: HandleNotFound,
}
return &frontend, nil
}
func (frontend *Frontend) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// basically a copy of http.FileServer and of the first lines http.serveFile functions
upath := r.URL.Path
if !strings.HasPrefix(upath, "/") {
upath = "/" + upath
r.URL.Path = upath
}
name := path.Clean(upath)
f, err := frontend.rootFileSys.Open(name)
if err != nil {
handleHTTPError(err, frontend.NotFoundHandler, w, r)
return
}
defer f.Close()
_, err = f.Stat()
if err != nil {
handleHTTPError(err, frontend.NotFoundHandler, w, r)
return
}
if strings.HasSuffix(r.URL.Path, "/") {
handleHTTPError(fs.ErrNotExist, frontend.NotFoundHandler, w, r)
return
}
frontend.defaultHandler.ServeHTTP(w, r)
}
func handleHTTPError(err error, handler func(http.ResponseWriter, *http.Request), w http.ResponseWriter, r *http.Request) {
// If error is 404, use custom handler
if errors.Is(err, fs.ErrNotExist) {
handler(w, r)
return
}
// otherwise serve http error
if errors.Is(err, fs.ErrPermission) {
http.Error(w, "403 Forbidden", http.StatusForbidden)
return
}
// Default:
logrus.WithError(err).Errorf("page handler error")
http.Error(w, "500 Internal Server Error", http.StatusInternalServerError)
}