-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
75 lines (62 loc) · 1.63 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
package main
import (
"errors"
"os"
"os/user"
"path"
"path/filepath"
"strings"
"time"
"gopkg.in/yaml.v2"
)
type Config struct {
HostMap map[string]string `yaml:"hostMap"`
ListenAddress string `yaml:"listenAddress"`
PrivateKeyPath string `yaml:"privateKeyPath"`
PrivateKeyPass string `yaml:"privateKeyPass"`
GZip bool `yaml:"gzip"`
Tls bool `yaml:"tls"`
TlsCertFile string `yaml:"certFile"`
TlsKeyFile string `yaml:"keyFile"`
Tunnel string `yaml:"tunnel"`
file string
}
func (c *Config) reload() error {
contents, err := os.ReadFile(c.file)
if err != nil {
return err
}
err = yaml.Unmarshal(contents, c)
if err == nil {
if c.Tls {
c.TlsCertFile = resolvePath(c.TlsCertFile, c.file)
c.TlsKeyFile = resolvePath(c.TlsKeyFile, c.file)
}
}
return err
}
func LoadConfig(configFile string) (*Config, error) {
cfg := &Config{file: configFile}
err := cfg.reload()
go func(c *Config) {
for {
err := c.reload()
logs.FatalIf(err, "reloading content")
time.Sleep(time.Second * 10)
}
}(cfg)
return cfg, err
}
func resolvePath(checkPath string, configPath string) string {
if checkPath == "~" || strings.HasPrefix(checkPath, "~/") {
usr, _ := user.Current()
checkPath = path.Join(usr.HomeDir, checkPath[1:])
}
if !filepath.IsAbs(checkPath) {
checkPath, _ = filepath.Abs(path.Join(filepath.Dir(configPath), checkPath))
}
if _, err := os.Stat(checkPath); errors.Is(err, os.ErrNotExist) {
logs.Fatal(checkPath + ": file does not exist")
}
return checkPath
}