/
ginloader.go
112 lines (90 loc) · 2.38 KB
/
ginloader.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
package ginmodule
import (
"context"
"github.com/acexy/golang-toolkit/logger"
"github.com/gin-gonic/gin"
"github.com/golang-acexy/starter-parent/parentmodule/declaration"
"net/http"
"time"
)
var server *http.Server
const (
defaultListenAddress = ":8080"
)
type GinModule struct {
// 自定义Module配置
GinModuleConfig *declaration.ModuleConfig
GinInterceptor func(instance *gin.Engine)
// * 注册业务路由
Routers []Router
// * 注册服务监听地址 :8080 (默认)
ListenAddress string // ip:port
UseErrorCodeHandler bool // 使用错误包装处理器 在出现非200响应码或者异常时,将自动进行转化
// gin config
DebugModule bool
MaxMultipartMemory int64
DisableMethodNotAllowedError bool
ForwardedByClientIP bool
}
func (g *GinModule) ModuleConfig() *declaration.ModuleConfig {
if g.GinModuleConfig != nil {
return g.GinModuleConfig
}
return &declaration.ModuleConfig{
ModuleName: "Gin",
UnregisterPriority: 0,
UnregisterAllowAsync: true,
UnregisterMaxWaitSeconds: 30,
LoadInterceptor: func(instance interface{}) {
if g.GinInterceptor != nil {
g.GinInterceptor(instance.(*gin.Engine))
}
},
}
}
func (g *GinModule) Register() (interface{}, error) {
var err error
ginEngin := gin.New()
if g.DebugModule {
gin.SetMode(gin.DebugMode)
} else {
gin.SetMode(gin.ReleaseMode)
}
if g.MaxMultipartMemory > 0 {
ginEngin.MaxMultipartMemory = g.MaxMultipartMemory
}
ginEngin.ForwardedByClientIP = g.ForwardedByClientIP
if !g.DisableMethodNotAllowedError {
ginEngin.HandleMethodNotAllowed = true
}
if g.UseErrorCodeHandler {
ginEngin.Use(ErrorCodeHandler())
}
ginEngin.Use(Recover())
if len(g.Routers) > 0 {
loadRouter(ginEngin, g.Routers)
}
if g.ListenAddress == "" {
g.ListenAddress = defaultListenAddress
}
server = &http.Server{
Addr: g.ListenAddress,
Handler: ginEngin,
}
go func() {
logger.Logrus().Traceln(g.ModuleConfig().ModuleName, "started")
if err = server.ListenAndServe(); err != nil {
}
}()
return ginEngin, err
}
func (g *GinModule) Unregister(maxWaitSeconds uint) (gracefully bool, err error) {
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(maxWaitSeconds)*time.Second)
defer cancel()
if err = server.Shutdown(ctx); err != nil {
gracefully = false
} else {
gracefully = true
}
return
}