-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
111 lines (90 loc) · 2.24 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
package main
import (
"fmt"
"github.com/foolin/goview/supports/ginview"
"github.com/gin-contrib/cors"
"github.com/gin-contrib/logger"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/joho/godotenv"
"github.com/romanzipp/sprinter/config"
"github.com/romanzipp/sprinter/controllers"
"github.com/romanzipp/sprinter/models"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"os"
"strconv"
"strings"
"time"
)
func main() {
err := godotenv.Load()
if err != nil {
panic("Error loading .env file")
}
zerolog.SetGlobalLevel(zerolog.InfoLevel)
if gin.IsDebugging() {
zerolog.SetGlobalLevel(zerolog.DebugLevel)
}
log.Logger = log.Output(
zerolog.ConsoleWriter{
Out: os.Stderr,
NoColor: false,
},
)
conf := makeConfig()
db := makeDb()
router := makeRouter(db)
go makeCheckScheduler(db, conf)
log.Fatal().Err(router.Run())
}
func makeConfig() config.Config {
interval, _ := strconv.ParseInt(os.Getenv("INTERVAL"), 10, 64)
pingHosts := strings.Split(os.Getenv("PING_HOSTS"), ",")
return config.Config{
Interval: interval,
PingHosts: pingHosts,
PingPrivileged: os.Getenv("PING_PRIVILEGED") == "true",
}
}
func makeDb() *gorm.DB {
db, err := gorm.Open(sqlite.Open("./data/data.db"), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
err = db.AutoMigrate(&models.Check{})
if err != nil {
panic(fmt.Sprintf("error migrating db: %s", err))
}
return db
}
func makeRouter(db *gorm.DB) *gin.Engine {
router := gin.Default()
router.HTMLRender = ginview.Default()
router.Static("/dist", "./dist")
router.Static("/assets", "./static")
router.Use(logger.SetLogger())
router.Use(cors.New(cors.Config{
AllowOrigins: []string{"*"},
AllowMethods: []string{"*"},
AllowHeaders: []string{"*"},
AllowWildcard: true,
}))
routes := router.Group("/")
routes.GET("/", func(c *gin.Context) {
controllers.IndexController(c, db)
})
return router
}
func makeCheckScheduler(db *gorm.DB, conf config.Config) {
for {
id := uuid.NewString()
for _, host := range conf.PingHosts {
log.Info().Msgf("ping check %s", host)
go models.ExecPingCheck(host, id, conf, db)
}
time.Sleep(time.Duration(conf.Interval) * time.Second)
}
}