forked from xinliangnote/go-gin-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
122 lines (102 loc) · 2.62 KB
/
main.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
package main
import (
"context"
"fmt"
"net/http"
"time"
"github.com/xinliangnote/go-gin-api/configs"
"github.com/xinliangnote/go-gin-api/internal/router"
"github.com/xinliangnote/go-gin-api/pkg/env"
"github.com/xinliangnote/go-gin-api/pkg/logger"
"github.com/xinliangnote/go-gin-api/pkg/shutdown"
"github.com/xinliangnote/go-gin-api/pkg/timeutil"
"go.uber.org/zap"
)
// @title swagger 接口文档
// @version 2.0
// @description
// @contact.name
// @contact.url
// @contact.email
// @license.name MIT
// @license.url https://github.com/xinliangnote/go-gin-api/blob/master/LICENSE
// @securityDefinitions.apikey LoginToken
// @in header
// @name token
// @BasePath /
func main() {
// 初始化 access logger
accessLogger, err := logger.NewJSONLogger(
logger.WithDisableConsole(),
logger.WithField("domain", fmt.Sprintf("%s[%s]", configs.ProjectName, env.Active().Value())),
logger.WithTimeLayout(timeutil.CSTLayout),
logger.WithFileP(configs.ProjectAccessLogFile),
)
if err != nil {
panic(err)
}
// 初始化 cron logger
cronLogger, err := logger.NewJSONLogger(
logger.WithDisableConsole(),
logger.WithField("domain", fmt.Sprintf("%s[%s]", configs.ProjectName, env.Active().Value())),
logger.WithTimeLayout(timeutil.CSTLayout),
logger.WithFileP(configs.ProjectCronLogFile),
)
if err != nil {
panic(err)
}
defer func() {
_ = accessLogger.Sync()
_ = cronLogger.Sync()
}()
// 初始化 HTTP 服务
s, err := router.NewHTTPServer(accessLogger, cronLogger)
if err != nil {
panic(err)
}
server := &http.Server{
Addr: configs.ProjectPort,
Handler: s.Mux,
}
go func() {
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
accessLogger.Fatal("http server startup err", zap.Error(err))
}
}()
// 优雅关闭
shutdown.NewHook().Close(
// 关闭 http server
func() {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
accessLogger.Error("server shutdown err", zap.Error(err))
}
},
// 关闭 db
func() {
if s.Db != nil {
if err := s.Db.DbWClose(); err != nil {
accessLogger.Error("dbw close err", zap.Error(err))
}
if err := s.Db.DbRClose(); err != nil {
accessLogger.Error("dbr close err", zap.Error(err))
}
}
},
// 关闭 cache
func() {
if s.Cache != nil {
if err := s.Cache.Close(); err != nil {
accessLogger.Error("cache close err", zap.Error(err))
}
}
},
// 关闭 cron Server
func() {
if s.CronServer != nil {
s.CronServer.Stop()
}
},
)
}