-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.go
91 lines (79 loc) · 1.78 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 main
import (
"fmt"
"os"
"path/filepath"
"gopkg.in/yaml.v3"
)
type Config struct {
Redis struct {
Addr string `yaml:"addr"`
Password string `yaml:"password"`
DB int `yaml:"db"`
} `yaml:"redis"`
LogFile string `yaml:"logFile"`
Channels []struct {
Name string `yaml:"name"`
Ratelimit string `yaml:"ratelimit"`
} `yaml:"channels"`
}
func LoadConfig(fp string) (*Config, error) {
// create config file if not exists
if _, err := os.Stat(fp); os.IsNotExist(err) {
if err := createConfigFile(fp); err != nil {
return nil, fmt.Errorf("failed to create config file: %w", err)
}
}
// open config file
file, err := os.Open(fp)
if err != nil {
return nil, fmt.Errorf("failed to open config file: %w", err)
}
defer file.Close()
// decode config file
var config Config
decoder := yaml.NewDecoder(file)
if err := decoder.Decode(&config); err != nil {
return nil, fmt.Errorf("failed to decode config file: %w", err)
}
return &config, nil
}
func createConfigFile(fp string) error {
config := Config{
Redis: struct {
Addr string `yaml:"addr"`
Password string `yaml:"password"`
DB int `yaml:"db"`
}{
Addr: "localhost:6379",
Password: "",
DB: 0,
},
LogFile: "/var/log/asynchook.log",
Channels: []struct {
Name string `yaml:"name"`
Ratelimit string `yaml:"ratelimit"`
}{
{
Name: "default",
Ratelimit: "2/s",
},
},
}
// create directory if not exists
if err := os.MkdirAll(filepath.Dir(fp), os.ModePerm); err != nil {
return err
}
// create file
file, err := os.Create(fp)
if err != nil {
return err
}
defer file.Close()
// write config to file
encoder := yaml.NewEncoder(file)
if err := encoder.Encode(config); err != nil {
return err
}
return nil
}