forked from dnsjia/luban
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
117 lines (102 loc) · 2.63 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
package main
import (
"context"
"fmt"
"io"
"os"
"os/signal"
"pigs/common"
phttp "pigs/http"
"pigs/middleware"
"pigs/models"
"pigs/routers"
"pigs/routers/cmdb"
"pigs/tasks"
"pigs/tools"
"syscall"
"time"
"github.com/gin-gonic/gin"
"github.com/toolkits/pkg/logger"
)
func main() {
// 创建记录日志的文件
f, _ := os.Create("gin.log")
//gin.DefaultWriter = io.MultiWriter(f)
// 如果需要将日志同时写入文件和控制台,请使用以下代码
gin.DefaultWriter = io.MultiWriter(f, os.Stdout)
common.VP = tools.Viper() // 初始化Viper
common.LOG = tools.Zap() // 初始化zap日志库
common.DB = common.GormMysql() // gorm连接数据库
common.MysqlTables(common.DB) // 初始化表
// 程序结束前关闭数据库链接
db, _ := common.DB.DB()
defer db.Close()
parseConf()
models.InitLdap(common.Config.LDAP)
models.InitError()
InitServer()
}
func InitServer() {
r := gin.Default()
//gin.ForceConsoleColor()
r.Use(middleware.Cors())
r.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {
// 你的自定义格式
return fmt.Sprintf("%s - [%s] \"%s %s %s %d %s \"%s\" %s\"\n",
param.ClientIP,
param.TimeStamp.Format(time.RFC3339),
param.Method,
param.Path,
param.Request.Proto,
param.StatusCode,
param.Latency,
param.Request.UserAgent(),
param.ErrorMessage,
)
}))
PublicGroup := r.Group("/api/v1/")
{
// 注册基础功能路由 不做鉴权
routers.User(PublicGroup)
}
PrivateGroup := r.Group("/api/v1/")
PrivateGroup.Use(gin.Recovery()).Use(middleware.AuthMiddleware()).Use(middleware.CasBinHandler())
{
routers.InitUserRouter(PrivateGroup)
// 权限相关路由
routers.InitCasBinRouter(PrivateGroup)
// 容器相关
routers.InitContainerRouter(PrivateGroup)
// 主机
cmdb.InitHostRouter(PrivateGroup)
//云资产管理
routers.InitCloudRouter(PrivateGroup)
}
// 任务调度
go tasks.TaskBeta()
go tasks.TaskWorker()
address := fmt.Sprintf(":%d", common.CONFIG.System.Addr)
err := r.Run(address)
if err != nil {
panic(fmt.Sprintf("start server err: %v", err))
}
_, cancelFunc := context.WithCancel(context.Background())
endingProc(cancelFunc)
}
func parseConf() {
if err := common.Parse(); err != nil {
fmt.Println("cannot parse configuration file:", err)
os.Exit(1)
}
}
func endingProc(cancelFunc context.CancelFunc) {
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
<-c
fmt.Printf("stop signal caught, stopping... pid=%d\n", os.Getpid())
// 执行清理工作
cancelFunc()
logger.Close()
phttp.Shutdown()
fmt.Println("process stopped successfully")
}