-
Notifications
You must be signed in to change notification settings - Fork 0
/
MotionGo.go
82 lines (66 loc) · 2.07 KB
/
MotionGo.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
package config
import (
"fmt"
"log"
"github.com/ribeirosaimon/motion-go/internal/middleware"
"github.com/gin-gonic/gin"
"github.com/magiconair/properties"
)
type RoutersVersion struct {
Version string
Handlers []func() MotionController
}
type MotionGo struct {
MotionEngine *gin.Engine
PropertiesFile *properties.Properties
Routers []RoutersVersion
}
func NewMotionGo(propertiesFile string) *MotionGo {
//gin.DefaultWriter = ioutil.Discard
var engine *gin.Engine
engine = gin.New()
return &MotionGo{
MotionEngine: engine,
PropertiesFile: properties.MustLoadFile(propertiesFile, properties.UTF8),
}
}
func (m *MotionGo) AddRouter(version ...RoutersVersion) {
m.Routers = append(m.Routers, version...)
}
func (m *MotionGo) CreateRouters() {
m.MotionEngine.Use(middleware.NewLogger())
for _, routerVersions := range m.Routers {
apiVersion := m.MotionEngine.Group(fmt.Sprintf("/api/%s", routerVersions.Version))
for _, routersFunc := range routerVersions.Handlers {
routers := routersFunc()
pathEngineer := apiVersion.Group(routers.Path)
for _, controller := range routers.Handlers {
if m.MotionEngine.Routes() != nil {
path := fmt.Sprintf("%s%s", pathEngineer.BasePath(), controller.Path)
if !existRouter(m.MotionEngine.Routes(), path, controller.Method) {
addHandlerToEngine(controller, pathEngineer)
}
} else {
addHandlerToEngine(controller, pathEngineer)
}
}
}
}
}
func existRouter(routes gin.RoutesInfo, path string, method string) bool {
for _, v := range routes {
if v.Path == path && v.Method == method {
return true
}
}
return false
}
func addHandlerToEngine(controller MotionRouter, pathEngineer *gin.RouterGroup) {
handlerFunc := gin.HandlerFunc(controller.Service)
controller.Middleware = append(controller.Middleware, handlerFunc)
pathEngineer.Handle(controller.Method, controller.Path, controller.Middleware...)
log.Printf("Add %s with path: %s", controller.Method, controller.Path)
}
func (m *MotionGo) RunEngine(serverPort int) {
m.MotionEngine.Run(fmt.Sprintf(":%d", serverPort))
}