-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
98 lines (86 loc) · 2.14 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
package main
import (
"bytes"
"context"
"fmt"
"gin-demo/common/applog"
"gin-demo/config"
"gin-demo/middleware"
"gin-demo/model"
"gin-demo/route"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
"net/http"
"os"
"os/signal"
"time"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
func main() {
// 配置gin是否是Debug模式
if config.C.Debug {
gin.SetMode(gin.DebugMode)
} else {
gin.SetMode(gin.ReleaseMode)
}
// 连接mysql
err := model.InitDB(getConnectMysqlStr())
if err != nil {
return
}
defer func() {
err := model.DB.Close()
if err != nil {
logrus.Error("Failed to close mysql")
}
}()
server := gin.New()
// 注册基本中间件
middleware.RegisterBasicMiddleWare(server)
// 注册路由
route.RegisterRoute(server)
srv := http.Server{
Addr: fmt.Sprintf(":%d", config.C.Port),
Handler: server,
}
// 异步启动server
go func() {
logrus.Infof("starting server at :%d", config.C.Port)
// 使用http启动server
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
logrus.Fatalln("start server failed.", err)
}
}()
// Wait for interrupt signal to gracefully shutdown the server with
// a timeout of 5 seconds.
quit := make(chan os.Signal)
signal.Notify(quit, os.Interrupt)
<-quit
logrus.Infoln("shutdown server ...")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
logrus.Errorln("server shutdown failed:", err)
}
logrus.Info("server exit")
}
func init() {
// 初始化日志设置
applog.ConfigLocalFilesystemLogger(config.C.Log.Path, "app")
}
// 生成mysql连接字符串
func getConnectMysqlStr() string {
var buffer bytes.Buffer
buffer.WriteString(config.C.MysqlConf.User)
buffer.WriteString(":")
buffer.WriteString(config.C.MysqlConf.Pass)
buffer.WriteString("@tcp")
buffer.WriteString("(")
buffer.WriteString(config.C.MysqlConf.Host)
buffer.WriteString(":")
buffer.WriteString(config.C.MysqlConf.Port)
buffer.WriteString(")/")
buffer.WriteString(config.C.MysqlConf.DbName)
buffer.WriteString("?charset=utf8&parseTime=True&loc=Local")
return buffer.String()
}