-
Notifications
You must be signed in to change notification settings - Fork 1
/
route.go
62 lines (55 loc) · 1.29 KB
/
route.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 meta_gin
import (
"net/http"
"github.com/gin-gonic/gin"
)
type RouteInfo struct {
Path string
Method string
Handler gin.HandlerFunc
Middlewares []gin.HandlerFunc
}
type RouteConfig struct {
Version string
GroupName string
Routes []RouteInfo
}
func RegisterRoutes[M Model](router *RouteHandler[M], config RouteConfig) {
api := router.Router.Group("/api")
if config.Version != "" {
api = api.Group(config.Version)
}
if config.GroupName != "" {
api = api.Group(config.GroupName)
}
for _, route := range config.Routes {
handlers := make([]gin.HandlerFunc, 0, len(route.Middlewares)+1)
handlers = append(handlers, route.Middlewares...)
handlers = append(handlers, route.Handler)
switch route.Method {
case http.MethodGet:
api.GET(route.Path, handlers...)
case http.MethodPost:
api.POST(route.Path, handlers...)
case http.MethodPut:
api.PUT(route.Path, handlers...)
case http.MethodPatch:
api.PATCH(route.Path, handlers...)
case http.MethodDelete:
api.DELETE(route.Path, handlers...)
}
}
}
type RouteHandler[M Model] struct {
Handler Handler[M]
Router *gin.Engine
}
func NewRouteHandler[M Model](
handler Handler[M],
router *gin.Engine,
) *RouteHandler[M] {
return &RouteHandler[M]{
Handler: handler,
Router: router,
}
}