/
controller.go
74 lines (60 loc) · 1.68 KB
/
controller.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
package web
import (
"io/fs"
"log"
"net/http"
"path"
"github.com/go-chi/chi/v5"
)
type Endpoint struct {
Path string
Method string
}
type Handler func(http.ResponseWriter, *http.Request) error
type Controller struct {
BasePath string
Handlers map[Endpoint]Handler
}
func (c *Controller) Register(router chi.Router) {
for endpoint, handler := range c.Handlers {
path := path.Join(c.BasePath, endpoint.Path)
router.Method(endpoint.Method, path, ControllerMiddleware(handler))
log.Printf("Registered handler for %s %s", endpoint.Method, path)
}
}
func NewAssetController(fileSystem fs.FS) *Controller {
return &Controller{
BasePath: "/assets",
Handlers: map[Endpoint]Handler{
{Method: "GET", Path: "/*"}: getAsset(fileSystem),
},
}
}
func getAsset(fileSystem fs.FS) Handler {
return func(w http.ResponseWriter, r *http.Request) error {
next := http.FileServer(http.FS(fileSystem))
next = StaticContentMiddleware(next)
next.ServeHTTP(w, r)
return nil
}
}
const templatePathUrlParam = "templatePath"
func NewTemplateController(fileSystem fs.FS, data any) *Controller {
var templater = NewTemplater(fileSystem)
return &Controller{
BasePath: "/",
Handlers: map[Endpoint]Handler{
{Method: "GET", Path: "/"}: getTemplate(templater, data),
{Method: "GET", Path: "/{" + templatePathUrlParam + ":.*}"}: getTemplate(templater, data),
},
}
}
func getTemplate(templater *Templater, data any) Handler {
return func(w http.ResponseWriter, r *http.Request) error {
templatePath := chi.URLParam(r, templatePathUrlParam)
if templatePath == "" {
templatePath = "index.html"
}
return templater.Write(templatePath, w, data)
}
}