-
Notifications
You must be signed in to change notification settings - Fork 0
/
controller.go
115 lines (103 loc) · 2.12 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
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
107
108
109
110
111
112
113
114
115
package vibe
import (
"reflect"
"github.com/carlmjohnson/truthy"
"github.com/gobeam/stringy"
"github.com/gofiber/fiber/v2"
)
type CtrBase interface {
Setup(ctx *fiber.Ctx)
Routes() map[string]Route
}
type ictr[Ctr CtrBase] interface {
CtrBase
init(app fiber.Router, ctr Ctr)
}
type Route struct {
Method string
Path string
Handler fiber.Handler
}
var Defaults = map[string]Route{
"Index": {
Method: "GET",
Path: "/",
},
"New": {
Method: "GET",
Path: "/new",
},
"Create": {
Method: "POST",
Path: "/",
},
"Edit": {
Method: "GET",
Path: "/:id/edit",
},
"Update": {
Method: "POST",
Path: "/:id",
},
"Destroy": {
Method: "DELETE",
Path: "/:id",
},
"Show": {
Method: "GET",
Path: "/:id",
},
}
type Controller[Ctr CtrBase] struct {
ictr[Ctr]
routemap map[string]Route
ctr Ctr
order []string
}
func (c Controller[Ctr]) Setup(ctx *fiber.Ctx) {}
func (c Controller[Ctr]) Routes() map[string]Route {
return map[string]Route{}
}
func (c *Controller[Ctr]) createRoutes(routes map[string]Route) {
c.routemap = make(map[string]Route)
keys := []string{"Index", "New", "Show", "Create", "Edit", "Update", "Destroy"} // To keep the map in order
v := reflect.ValueOf(c.ctr)
for k, r := range routes {
if m := v.MethodByName(k); m.IsValid() {
t := r
if !truthy.Value(t.Handler) {
t.Handler = m.Interface().(func(*fiber.Ctx) error)
}
if !truthy.Value(t.Method) {
t.Method = "GET"
}
if !truthy.Value(t.Path) {
str := stringy.New(k)
t.Path = "/" + str.KebabCase().ToLower()
}
c.routemap[k] = t
c.order = append(c.order, k)
}
}
for _, k := range keys {
if m := v.MethodByName(k); m.IsValid() && !truthy.Value(c.routemap[k]) {
r := Defaults[k]
t := r
t.Handler = m.Interface().(func(*fiber.Ctx) error)
c.routemap[k] = t
c.order = append(c.order, k)
}
}
}
func (c *Controller[Ctr]) init(app fiber.Router, ctr Ctr) {
c.ctr = ctr
c.createRoutes(ctr.Routes())
app.Use(func(c *fiber.Ctx) error {
ctr.Setup(c)
return c.Next()
})
for _, i := range c.order {
v := c.routemap[i]
app.Add(v.Method, v.Path, v.Handler)
}
}