/
config.go
91 lines (75 loc) · 2 KB
/
config.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
package config
import (
"errors"
"fmt"
"io/ioutil"
"time"
"gopkg.in/yaml.v2"
)
// NewAppFromYaml returns the app data from provided yaml file
func NewAppFromYaml(path string) (*App, error) {
app := new(App)
// Get data from provided yaml file
raw, err := ioutil.ReadFile(path)
if err != nil {
errstr := fmt.Sprintf("Error while reading config file: %v", err)
return nil, errors.New(errstr)
}
err = yaml.Unmarshal(raw, app)
if err != nil {
return nil, err
}
err = app.Validate()
if err != nil {
return nil, err
}
return app, nil
}
// App represents the app's configuration
type App struct {
Bots map[string]*Bot `yaml:"bots"`
Messages map[string]*Message `yaml:"messages"`
}
// Validate validates an app config
func (a *App) Validate() error {
if len(a.Messages) == 0 {
return fmt.Errorf("config file doesn't contain Messages")
}
if len(a.Bots) == 0 {
return fmt.Errorf("config file doesn't contain messengers")
}
for msgName, msg := range a.Messages {
for _, msgr := range msg.Messengers {
if _, ok := a.Bots[msgr.Bot]; !ok {
return fmt.Errorf("bot %s not defined", msgr)
}
}
if msg.ExpireTime != "" {
if _, err := time.ParseDuration(msg.ExpireTime); err != nil {
return fmt.Errorf("Invalid expiretime %s", msg.ExpireTime)
}
}
if msg.Body == "" {
return fmt.Errorf("message %s does not contain a body", msgName)
}
}
return nil
}
// Message represents the configuration of a single Messaged message
type Message struct {
Messengers []Messenger `yaml:"messengers"`
Schedule string `yaml:"schedule"`
Body string `yaml:"body"`
ExpireTime string `yaml:"expiretime"`
DisableLinkPreview bool `yaml:"disable_link_preview"`
}
// Messenger represents a messenger of a message
type Messenger struct {
Bot string `yaml:"bot"`
ChatIDs []string `yaml:"chat_ids"`
}
// Bot represents a bot config
type Bot struct {
Platform string `yaml:"platform"`
APIKey string `yaml:"api_key"`
}