/
routing.go
96 lines (79 loc) · 1.92 KB
/
routing.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
package web
import (
"fmt"
"github.com/labstack/echo"
)
type MethodHandler struct {
Method string
Handler echo.HandlerFunc
MiddleWare []echo.MiddlewareFunc
}
type Route struct {
Path string
Handlers []*MethodHandler
Name string
ERoute *echo.Route
}
type RouteConfig struct {
Routes []*Route
MiddleWare []echo.MiddlewareFunc
}
func (route *Route) Handle(m string, hf HandlerFunc, mw ...echo.MiddlewareFunc) *Route {
handler := &MethodHandler{m, wrapApiRoute(hf), mw}
route.Handlers = append(route.Handlers, handler)
return route
}
func (route *Route) SetName(n string) *Route {
route.Name = n
return route
}
func (config *RouteConfig) AddRoute(path string) *Route {
route := &Route{
Path: path,
Handlers: []*MethodHandler{},
}
config.Routes = append(config.Routes, route)
return route
}
func newRouteConfig() *RouteConfig {
return &RouteConfig{[]*Route{}, []echo.MiddlewareFunc{}}
}
var Routing *RouteConfig
func init() {
Routing = &RouteConfig{[]*Route{}, []echo.MiddlewareFunc{}}
}
func AddRoute(path string) *Route {
return Routing.AddRoute(path)
}
func routeByName(cfg *RouteConfig, name string) (*Route, error) {
for _, r := range cfg.Routes {
if r.Name == name {
return r, nil
}
}
return nil, fmt.Errorf("Could not find route with name %v", name)
}
func RouteByName(name string) (*Route, error) {
return routeByName(Routing, name)
}
type HandlerFunc func(ApiContext) error
func wrapApiRoute(f HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
return f(c.(ApiContext))
}
}
func InitRoutes(e *echo.Echo) {
initRoutes(e, Routing)
}
func initRoutes(e *echo.Echo, cfg *RouteConfig) {
for _, route := range cfg.Routes {
initRoute(e, route)
}
}
func initRoute(e *echo.Echo, route *Route) {
for _, handler := range route.Handlers {
er := e.Add(handler.Method, route.Path, handler.Handler, handler.MiddleWare...)
er.Name = route.Name
route.ERoute = er
}
}