-
Notifications
You must be signed in to change notification settings - Fork 0
/
jerry.go
84 lines (69 loc) · 1.77 KB
/
jerry.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
package main
import (
"errors"
"github.com/PedroGao/jerry/config"
"github.com/PedroGao/jerry/libs/token"
lv "github.com/PedroGao/jerry/libs/validator"
"github.com/PedroGao/jerry/model"
"github.com/PedroGao/jerry/router"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
log "github.com/sirupsen/logrus"
"github.com/spf13/pflag"
"github.com/spf13/viper"
"net/http"
"time"
)
var (
wcfg = pflag.StringP("config", "c", "", "config file path")
)
func main() {
// parse the flags
pflag.Parse()
// init config from file
if err := config.Init(*wcfg); err != nil {
log.Fatalf("read config file error : %s \n", err)
}
// init db
model.Init()
model.Sync()
defer model.Close()
// jwt
token.New()
// set gin app run mode
gin.SetMode(viper.GetString("runmode"))
// 更换 v8 至 v9
binding.Validator = lv.New()
app := gin.Default()
// load middleware and routes
router.Load(app)
// test api
app.GET("/", func(c *gin.Context) {
c.JSON(200, gin.H{
"msg": "greeting from pedro",
})
})
// ping goroutine for check app is alive or not
go func() {
if err := ping(); err != nil {
log.Fatalf("The router has no response, or it might took too long to start up. erro: %s \n", err)
}
log.Infoln("The app has been deployed successfully.")
}()
// run
log.Fatalln(app.Run(viper.GetString("addr")))
}
// check app self when start
func ping() error {
for i := 0; i < 10; i++ {
// Ping the server by sending a GET request to `/health`.
resp, err := http.Get("http://localhost" + viper.GetString("addr") + "/")
if err == nil && resp.StatusCode == 200 {
return nil
}
// Sleep for a second to continue the next ping.
log.Infoln("Waiting for the router, retry in 1 second.")
time.Sleep(time.Second)
}
return errors.New("app is not working")
}