-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgin-example.go
83 lines (73 loc) · 2.12 KB
/
gin-example.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
package main
import (
"context"
"net/http"
"os"
"os/signal"
"time"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"gin-example/models"
"gin-example/pkg/cache"
"gin-example/pkg/database"
"gin-example/pkg/logging"
"gin-example/pkg/setting"
"gin-example/routers"
)
func init() {
// 配置初始化
if err := setting.Setup(); err != nil {
panic(err)
}
// 初始化日志
logging.Setup()
// 初始化缓存
if err := cache.Setup(); err != nil {
logging.Logger.Fatal("cache initialization failed", zap.Error(err))
}
// 初始化数据库
if err := database.Setup(); err != nil {
logging.Logger.Fatal("database initialization failed", zap.Error(err))
}
// 数据库表结构变更
if err := models.Setup(); err != nil {
logging.Logger.Fatal("models initialization failed", zap.Error(err))
}
}
// @title API swagger
// @version 1.0
// @description smp ops system.
// @termsOfService http://github.com/zqyangchn
// @contact.name API Support
// @contact.url http://github.com/zqyangchn
// @contact.email [email protected]
func main() {
gin.SetMode(setting.ServerSetting.RunMode)
router := routers.NewRouter()
srv := &http.Server{
Addr: ":" + setting.ServerSetting.HttpPort,
Handler: router,
ReadTimeout: setting.ServerSetting.ReadTimeout,
WriteTimeout: setting.ServerSetting.WriteTimeout,
MaxHeaderBytes: 1 << 20,
}
go func() {
logging.Logger.Info("web server starting ...")
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
logging.Logger.Fatal("web Server start Failed", zap.Error(err))
}
}()
// 等待中断信号以优雅地关闭服务器(设置 15 秒的超时时间)
osSignal := make(chan os.Signal)
signal.Notify(osSignal, os.Interrupt)
<-osSignal
// 启动服务器关闭流程
logging.Logger.Info("shutdown server ...")
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
// srv.Shutdown(ctx) 关闭服务器监听端口, 不再接受新的请求
if err := srv.Shutdown(ctx); err != nil {
logging.Logger.Fatal("Server Shutdown:", zap.Error(err))
}
logging.Logger.Info("server shutdown completed !")
}