-
Notifications
You must be signed in to change notification settings - Fork 3
/
setup.go
185 lines (160 loc) · 5.05 KB
/
setup.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
package ginKit
import (
"context"
"errors"
"github.com/gin-contrib/pprof"
"github.com/gin-gonic/gin"
"github.com/richelieu-yang/chimera/v3/src/core/errorKit"
"github.com/richelieu-yang/chimera/v3/src/core/signalKit"
"github.com/richelieu-yang/chimera/v3/src/core/strKit"
"github.com/richelieu-yang/chimera/v3/src/log/logrusKit"
"github.com/richelieu-yang/chimera/v3/src/netKit"
"github.com/richelieu-yang/chimera/v3/src/time/timeKit"
"github.com/richelieu-yang/chimera/v3/src/validateKit"
"github.com/sirupsen/logrus"
"net/http"
"os"
"sync"
)
// serviceInfo e.g."Agent-127.0.0.1:12345"
var serviceInfo = ""
func MustSetUp(config *Config, businessLogic func(engine *gin.Engine) error, options ...GinOption) {
err := SetUp(config, businessLogic, options...)
if err != nil {
logrusKit.DisableQuote(nil)
logrus.Fatalf("%+v", err)
}
}
// SetUp
/*
PS: 正常执行的情况下,此方法会阻塞调用的协程.
@param config 不能为nil(否则将返回error)
@param businessLogic 业务逻辑,可以在其中进行 路由绑定 等操作...(可以为nil,但不推荐这么干)
*/
func SetUp(config *Config, businessLogic func(engine *gin.Engine) error, options ...GinOption) error {
if err := validateKit.Struct(config); err != nil {
return err
}
opts := loadOptions(options...)
serviceInfo = opts.ServiceInfo
// Gin的模式,后续也可以在 businessLogic 里面调整
if strKit.IsEmpty(config.Mode) {
// 默认: debug模式
gin.SetMode(gin.DebugMode)
} else {
gin.SetMode(config.Mode)
}
/*
gin框架中如何让日志文字带颜色输出?
https://mp.weixin.qq.com/s/eHtIC5egDoqx4LdAvcE5Qw
PS: 如果 Gin.ForceConsoleColor() 和 Gin.DisableConsoleColor() 都不调用,那么默认是在终端中输出日志是带颜色的,输出到其他地方是不带颜色的.
*/
if config.DisableColor {
// 禁用日志带颜色输出
gin.DisableConsoleColor()
} else {
// 强制日志带颜色输出(无论是在终端还是其他输出设备)
gin.ForceConsoleColor()
}
// 通过logrus输出Gin的日志.
// Richelieu:从目前表现来看,虽然gin和logrus都可以设置颜色,但在此处,只要gin允许了,logrus的logger是否允许就无效了
gin.DefaultWriter = logrus.StandardLogger().Out
engine := DefaultEngine()
// pprof
if config.Pprof {
pprof.Register(engine, pprof.DefaultPrefix) // 等价于 pprof.Register(engine)
}
// middleware
if err := attachMiddlewares(engine, config.Middleware, opts); err != nil {
return err
}
/* favicon.ico */
if opts.DefaultFavicon {
DefaultFavicon(engine)
}
/* 404 */
if opts.DefaultNoRouteHtml {
if err := DefaultNoRouteHtml(engine); err != nil {
return err
}
}
/* 405(不设置的话,就会走到404) */
engine.HandleMethodNotAllowed = opts.DefaultNoMethod
if engine.HandleMethodNotAllowed {
DefaultNoMethod(engine)
}
/* 业务逻辑 */
if businessLogic != nil {
if err := businessLogic(engine); err != nil {
return errorKit.Wrapf(err, "Fail to execute businessLogic().")
}
}
/* http */
httpPort := config.Port
var httpSrv *http.Server
if httpPort != 0 {
httpSrv = &http.Server{
Addr: netKit.JoinToHost(config.HostName, httpPort),
Handler: engine.Handler(),
}
logrus.Infof("Listening and serving HTTP on [%s]", httpSrv.Addr)
go func() {
if err := httpSrv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
logrus.Fatalf("Fail to start http server with port(%d).", httpPort)
}
}()
}
/* https */
sslConfig := config.SSL
httpsPort := sslConfig.Port
var httpsSrv *http.Server
if httpsPort != 0 {
httpsSrv = &http.Server{
Addr: netKit.JoinToHost(config.HostName, httpsPort),
Handler: engine.Handler(),
}
logrus.Infof("Listening and serving HTTPS on [%s]", httpsSrv.Addr)
go func() {
if err := httpsSrv.ListenAndServeTLS(sslConfig.CertFile, sslConfig.KeyFile); err != nil && !errors.Is(err, http.ErrServerClosed) {
logrus.Fatalf("Fail to start https server with port(%d).", httpsPort)
}
}()
}
if httpPort == 0 && httpsPort == 0 {
return errorKit.Newf("both httpPort and httpsPort are invalid")
}
/*
优雅地重启或停止
https://gin-gonic.com/zh-cn/docs/examples/graceful-restart-or-stop/
https://github.com/gin-gonic/examples/blob/master/graceful-shutdown/graceful-shutdown/notify-without-context/server.go
*/
signalKit.MonitorExitSignalsSynchronously(func(sig os.Signal) {
var wg sync.WaitGroup
ctx, cancel := context.WithTimeout(context.TODO(), timeKit.Second*5)
defer cancel()
if httpSrv != nil {
wg.Add(1)
go func() {
defer wg.Done()
if err := httpSrv.Shutdown(ctx); err != nil {
logrus.WithError(err).Error("Fail to shut down http server.")
return
}
logrus.Info("Manager to shut down http server.")
}()
}
if httpsSrv != nil {
wg.Add(1)
go func() {
defer wg.Done()
if err := httpsSrv.Shutdown(ctx); err != nil {
logrus.WithError(err).Error("Fail to shut down https server.")
return
}
logrus.Info("Manager to shut down https server.")
}()
}
wg.Wait()
})
return nil
}