-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
99 lines (80 loc) · 2.32 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 (
"errors"
"fmt"
"github.com/MuXiFresh-be/model/form"
"github.com/MuXiFresh-be/model/schedule"
"github.com/MuXiFresh-be/model"
"github.com/MuXiFresh-be/model/comment"
"github.com/MuXiFresh-be/model/file"
"github.com/MuXiFresh-be/model/user"
"net/http"
"time"
"github.com/MuXiFresh-be/config"
"github.com/MuXiFresh-be/log"
"github.com/MuXiFresh-be/router"
"github.com/MuXiFresh-be/router/middleware"
"github.com/gin-gonic/gin"
"github.com/spf13/pflag"
"github.com/spf13/viper"
"go.uber.org/zap"
)
var (
cfg = pflag.StringP("config", "c", "", "apiserver config file path.")
)
// @title MuXiFresh-be
// @version 1.0
// @description The
// @host work.test.muxi-tech.xyz
// @BasePath /api/v1
// @tag.name user
// @tag.description 用户服务
func main() {
pflag.Parse()
// init config
if err := config.Init(*cfg, "fresh"); err != nil {
panic(err)
}
// logger sync
defer log.SyncLogger()
//model.InitSelfDB()
model.DB.Init()
defer model.DB.Close()
if err := model.DB.Self.AutoMigrate(&user.UserModel{}, &comment.Comment{}, &file.Homework{}, &file.HomeworkPublished{}, &schedule.ScheduleModel{}, &form.FormModel{}).Error; err != nil {
fmt.Println("error", err)
}
// Set gin mode.
gin.SetMode(viper.GetString("runmode"))
// Create the Gin engine.
g := gin.New()
// Routes.
router.Load(
// Cores.
g,
// MiddleWares.
middleware.Logging(),
middleware.RequestId(),
)
// Ping the server to make sure the router is working.
go func() {
if err := pingServer(); err != nil {
log.Fatal("The router has no response, or it might took too long to start up.", zap.String("reason", err.Error()))
}
log.Info(fmt.Sprintf("The router has been deployed on %s successfully.", viper.GetString("addr")))
}()
log.Info(http.ListenAndServe(viper.GetString("addr"), g).Error())
}
// pingServer pings the http server to make sure the router is working.
func pingServer() error {
for i := 0; i < viper.GetInt("max_ping_count"); i++ {
// Ping the server by sending a GET request to `/health`.
resp, err := http.Get(viper.GetString("url") + "/sd/health")
if err == nil && resp.StatusCode == 200 {
return nil
}
// Sleep for a second to continue the next ping.
log.Info("Waiting for the router, retry in 1 second.")
time.Sleep(time.Second)
}
return errors.New("cannot connect to the router")
}