-
Notifications
You must be signed in to change notification settings - Fork 1
/
config.go
93 lines (79 loc) · 2.25 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
92
93
package main
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"strings"
)
// I know, "this should be a struct!"
// But flags need to be parsed first, applying conf file values if not set by flags
// Check the parseConfigFile and validateConfigOrDie functions first
// Then try to convince me to make it a struct for no benefit :)
type Config map[string]string
var config Config
func parseFlags() {
// Parse the flags
version := flag.Bool("version", false, "Print the application version and exit")
configFile := flag.String("config-file", "", "Path to config file")
server := flag.String("server", "", "Matrix homeserver url")
token := flag.String("token", "", "Matrix account access token")
room := flag.String("room", "", "Matrix Room ID")
preface := flag.String("preface", "", "Preface the matrix message with arbitrary text (optional)")
flag.Parse()
// If the version flag is set, print the version and exit
if *version {
fmt.Println(Version)
os.Exit(0)
}
// Put them in the config
config["configFile"] = *configFile
config["server"] = *server
config["token"] = *token
config["room"] = *room
config["preface"] = *preface
}
func getConfig() {
config = make(Config)
// Parse command line arguments. These override config file values.
// We need it parsed before for the --config-file flag
parseFlags()
// Parse config file (if set)
if config["configFile"] != "" {
parseConfigFile(config["configFile"])
}
}
func parseConfigFile(path string) {
var confFile Config
// Read config file
content, err := ioutil.ReadFile(path)
if err != nil {
log.Fatal("Error when opening file: ", err)
}
// Unmarshall the contents
err = json.Unmarshal(content, &confFile)
if err != nil {
log.Fatal("Error trying to parse JSON file: ", err)
}
// Set the values only if they weren't already set by flags
keys := []string{"server", "token", "room", "preface"}
for _, key := range keys {
if config[key] == "" {
config[key] = confFile[key]
}
}
}
func validateConfigOrDie() {
var missing []string
required := []string{"server", "token", "room"}
for _, key := range required {
if config[key] == "" {
missing = append(missing, key)
}
}
if len(missing) > 0 {
log.Fatal("Missing required parameters: ", strings.Join(missing, ", "))
}
}