-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
62 lines (51 loc) · 1.3 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
package config
import (
"encoding/json"
"errors"
"io/fs"
"log"
"os"
"path/filepath"
)
type ReadFileFunc func(string) ([]byte, error)
type WriteFileFunc func(string, []byte, fs.FileMode) error
var readFile ReadFileFunc = os.ReadFile
var writeFile WriteFileFunc = os.WriteFile
type Config struct {
ServerUrl string `json:"serverurl"`
}
func NewConfig(configFile string) Config {
c := Config{}
c.ServerUrl = "http://localhost:2006"
c.readConfigFile(configFile)
return c
}
func (c *Config) createConfigFile(p string) {
log.Printf("Could not find config file, generating one using defaults in %v", p)
b, err := json.MarshalIndent(c, "", " ")
if err != nil {
log.Fatal("Could not marshal config data to json")
}
writeFile(p, b, 0600)
}
func (c *Config) loadConfigFile(p string) {
b, err := readFile(p)
if err != nil {
log.Fatalf("Could not open config file %v", p)
}
json.Unmarshal(b, c)
}
func (c *Config) readConfigFile(configFile string) {
log.Println("Loading config file")
p, err := filepath.Abs(configFile)
if err != nil {
log.Println("Failed to get the absolute config file path, using", configFile)
p = configFile
}
if _, err := os.Stat(p); errors.Is(err, os.ErrNotExist) {
c.createConfigFile(p)
} else {
c.loadConfigFile(p)
}
log.Println("Successfully read config file", p)
}