-
Notifications
You must be signed in to change notification settings - Fork 20
/
main.go
115 lines (101 loc) · 2.44 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
package main
import (
"sheetServerApi/global"
model "sheetServerApi/internal/model/db"
"sheetServerApi/internal/routers"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
"github.com/spf13/viper"
"log"
"net/http"
"time"
)
type Setting struct {
vp *viper.Viper
}
// init初始化函数
func init() {
// 注入全局系统配置文件
if err := setupSetting();err!=nil {
log.Fatal(err)
return
}
// 注入数据库连接池
if err := setupDBEngine();err!=nil {
log.Fatal(err)
return
}
logrus.Info("init success...")
}
// 主函数
func main() {
// 设置运行模式(release or debug ?)
gin.SetMode(global.ServerSetting.RunMode)
// 打印日志
log.SetFlags(log.Lshortfile | log.LstdFlags)
// 挂载路由
router := routers.NewRouter()
s := &http.Server{
Addr: ":"+global.ServerSetting.HttpPort,
Handler: router,
ReadTimeout: global.ServerSetting.ReadTimeout,
WriteTimeout: global.ServerSetting.WriteTimeout,
MaxHeaderBytes: 1 << 20,
}
log.Println("listen in " + global.ServerSetting.HttpPort)
s.ListenAndServe()
}
//初始化全局服务器配置文件
func setupSetting() error {
setting,err := NewSettings()
if err != nil {
return err
}
if err := setting.ReadSection("Server",&global.ServerSetting);err!=nil {
return err
}
if err := setting.ReadSection("App",&global.AppSetting);err!=nil {
return err
}
if err := setting.ReadSection("DatabaseOrm",&global.DatabaseOrmSetting);err!=nil {
return err
}
if err := setting.ReadSection("DatabaseSqlx",&global.DatabaseSqlxSetting);err!=nil {
return err
}
global.ServerSetting.ReadTimeout *= time.Second
global.ServerSetting.WriteTimeout *= time.Second
return nil
}
//初始化全局数据库连接池
func setupDBEngine() error {
var err error
global.DBOrmEngine,err = model.NewDBOrmEngine(global.DatabaseOrmSetting)
if err!=nil {
return err
}
global.DBSqlxEngine,err = model.NewDBSqlxEngine(global.DatabaseSqlxSetting)
if err!=nil {
return err
}
return nil
}
// 读取配置文件
func NewSettings() (*Setting,error) {
vp := viper.New()
vp.SetConfigName("config")
// 载入全局配置文件
vp.AddConfigPath("/Users/mac/go/src/sheetServerApi/configs")
//vp.AddConfigPath(constants.Release_config_dir)
vp.SetConfigType("yaml")
if err := vp.ReadInConfig();err!=nil {
return nil ,err
}
return &Setting{vp},nil
}
func (s *Setting) ReadSection(k string,v interface{}) error {
if err := s.vp.UnmarshalKey(k,v);err!=nil {
return err
}
return nil
}