-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontroller.go
62 lines (51 loc) · 1.34 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
package sender
import (
"context"
"io"
"net/http"
)
type (
Options struct {
ErrorMap func(error) int
}
JSONOptions struct {
Options
}
Controller struct {
errorMap func(error) int
handlers map[string]func(w http.ResponseWriter, r *http.Request)
}
)
func NewController(
errorMap func(error) int,
) *Controller {
return &Controller{
errorMap: errorMap,
}
}
func (c *Controller) Init(mux *http.ServeMux) {
for route, handler := range c.handlers {
mux.HandleFunc(route, handler)
}
}
func (c *Controller) initHandlers() {
if c.handlers == nil {
c.handlers = make(map[string]func(w http.ResponseWriter, r *http.Request))
}
}
func (c *Controller) Handler(route string, handler func(context.Context, Sender)) {
c.initHandlers()
c.handlers[route] = Handler(handler)
}
func (c *Controller) JsonHandler(route string, handler func(context.Context, Sender) (any, error)) {
c.initHandlers()
c.handlers[route] = JsonHandler(c.errorMap, handler)
}
func (c *Controller) StreamHandler(route string, handler func(context.Context, Sender) (io.Reader, error)) {
c.initHandlers()
c.handlers[route] = StreamHandler(c.errorMap, handler)
}
func (c *Controller) TemplateHandler(route string, template *Template, handler func(context.Context, Sender) (any, error)) {
c.initHandlers()
c.handlers[route] = TemplateHandler(c.errorMap, template, handler)
}