-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.go
110 lines (92 loc) · 2.06 KB
/
app.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
package main
import (
"fmt"
"ginStudy/common"
"ginStudy/model"
"ginStudy/router"
"html/template"
"log"
"os"
"strconv"
"time"
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm"
"github.com/robfig/cron/v3"
"github.com/syndtr/goleveldb/leveldb"
)
type MyJob struct{}
func (j MyJob) Run() {
fmt.Println("执行")
}
func newWithSeconds() *cron.Cron {
secondParser := cron.NewParser(cron.Second | cron.Minute |
cron.Hour | cron.Dom | cron.Month | cron.DowOptional | cron.Descriptor)
return cron.New(cron.WithParser(secondParser), cron.WithChain())
}
func startMain() {
// 休眠20s,等待mysql,redis启动
time.Sleep(time.Duration(20) * time.Second)
c := newWithSeconds()
spec := "*/5 * * * * ?"
//_, e := c.AddFunc(spec, func() {
// fmt.Println("定时任务")
//})
_, e := c.AddJob(spec, MyJob{})
if e != nil {
fmt.Println("error:", e)
}
c.Start()
//select {} // 强制阻塞
if os.Getenv("GIN_MODE") != "debug" {
gin.SetMode(gin.ReleaseMode)
}
// Initialize Redis
err := common.InitRedisClient()
if err != nil {
log.Fatal(err.Error())
}
// 初始化 MySQL
db, err := model.InitDB()
if err != nil {
log.Fatal(err)
}
defer func(db *gorm.DB) {
err := db.Close()
if err != nil {
}
}(db)
// 初始化 LevelDB
levelDb, err := model.InitLevelDB()
if err != nil {
log.Fatal(err)
}
defer func(levelDb *leveldb.DB) {
err := levelDb.Close()
if err != nil {
}
}(levelDb)
// Initialize HTTP server
server := gin.Default()
server.SetHTMLTemplate(loadTemplate())
router.SetRouter(server)
var realPort = os.Getenv("PORT")
if realPort == "" { // 环境变量没有,就读constants.go文件
realPort = strconv.Itoa(*common.Port)
}
if *common.Host == "localhost" {
ip := common.GetIp()
if ip != "" {
*common.Host = ip
}
}
serverUrl := "http://" + *common.Host + ":" + realPort + "/"
common.OpenBrowser(serverUrl)
err = server.Run(":" + realPort)
if err != nil {
log.Println(err)
}
}
func loadTemplate() *template.Template {
t := template.Must(template.New("").ParseFS(common.FS, "public/*.html"))
return t
}