/
app.go
93 lines (76 loc) · 2.01 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
package app
import (
"encoding/json"
"errors"
"github.com/go-co-op/gocron"
"github.com/reaper47/heavy-metal-notifier/internal/constants"
"github.com/reaper47/heavy-metal-notifier/internal/models"
"github.com/reaper47/heavy-metal-notifier/internal/utils/regex"
"log"
"os"
"path/filepath"
"time"
)
var (
Calendar models.Calendar
Config ConfigFile
Scheduler *gocron.Scheduler
)
// ConfigFile holds the contents of config.json.
type ConfigFile struct {
Email ConfigEmail `json:"email"`
Port int `json:"port"`
URL string `json:"url"`
}
// Valid verifies whether the configuration is correct.
func (c *ConfigFile) Valid() (bool, error) {
isValid, err := c.Email.valid()
if !isValid {
return isValid, err
}
if c.Port < 1024 {
return false, errors.New("configuration file has invalid port")
}
if c.URL == "" {
return false, errors.New("configuration file missing url")
}
return true, nil
}
// ConfigEmail holds email configuration variables.
type ConfigEmail struct {
From string `json:"from"`
MaxNumberUsers int `json:"maxNumberUsers"`
SendGridAPIKey string `json:"sendGridAPIKey"`
}
func (c *ConfigEmail) valid() (bool, error) {
if !regex.Email.MatchString(c.From) {
return false, errors.New("configuration file has invalid email.from")
}
if c.MaxNumberUsers == 0 {
return false, errors.New("configuration file missing email.maxNumberUsers")
}
if c.SendGridAPIKey == "" {
return false, errors.New("configuration file missing email.sendGridAPIKey")
}
return true, nil
}
// Init initializes the application by reading the config file and starting chron jobs.
func Init() {
exe, err := os.Executable()
if err != nil {
log.Fatal(err)
}
xb, err := os.ReadFile(filepath.Join(filepath.Dir(exe), constants.ConfigFile))
if err != nil {
log.Fatal(err)
}
if err := json.Unmarshal(xb, &Config); err != nil {
log.Fatal(err)
}
isValid, err := Config.Valid()
if !isValid {
log.Fatal(err.Error())
}
Scheduler = gocron.NewScheduler(time.Local)
Scheduler.StartAsync()
}