-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
99 lines (87 loc) · 2.3 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
package main
import (
"apiserver/config"
version2 "apiserver/pkg/version"
"apiserver/router"
"encoding/json"
"errors"
"fmt"
"github.com/gin-gonic/gin"
"github.com/spf13/pflag"
"github.com/spf13/viper"
"os"
"apiserver/model"
"apiserver/router/middleware"
"github.com/lexkong/log"
"net/http"
"time"
)
var (
//配置文件
cfg = pflag.StringP("config", "c", "", "api config file path")
version = pflag.BoolP("version", "v", false, "show version info.")
)
func main() {
//version
pflag.Parse()
if *version {
v := version2.Get()
marshaled, err := json.MarshalIndent(&v, "", " ")
if err != nil {
fmt.Printf("%v\n", err)
os.Exit(1)
}
fmt.Println(string(marshaled))
return
}
//viper初始化调用
if err := config.Init(*cfg); err != nil {
panic(err)
}
//int db
model.DB.Init()
defer model.DB.Close()
//Set gin mode使用
gin.SetMode(viper.GetString("runmode"))
//Set the Gin engine
g := gin.New()
//外部加入的中间件
middlewares := []gin.HandlerFunc{middleware.RequestId(), middleware.Logging()}
//路由加载
router.Load(
g,
middlewares...,
)
//router健康检查
go func() {
if err := pingServer(); err != nil {
log.Fatal("The router has no response, or it might took too long to start up.", err)
}
log.Infof("The router has been deployed successfully.")
}()
//start https listen if certificate exists
cert := viper.GetString("tls.cert")
key := viper.GetString("tls.key")
if key != "" && cert != "" {
go func() {
log.Infof("Start to listening the incoming requests on https address: %s", viper.GetString("tls.addr"))
log.Infof(http.ListenAndServeTLS(viper.GetString("tls.addr"), cert, key, g).Error())
}()
}
log.Infof("Start to listening the incoming requests on http address: %s", viper.GetString("addr"))
log.Infof(http.ListenAndServe(viper.GetString("addr"), g).Error())
}
//pingServer pings the http server to make sure the routers is working
func pingServer() error {
for i := 0; i < viper.GetInt("max_ping_count"); i++ {
resp, err := http.Get(viper.GetString("url") + "/sd/health")
/*runtime.Breakpoint()
debug.PrintStack()*/
if err == nil && resp.StatusCode == 200 {
return nil
}
log.Infof("waiting for the router, retry in 1 second.")
time.Sleep(5 * time.Second)
}
return errors.New("can't connect to the route")
}