-
Notifications
You must be signed in to change notification settings - Fork 9
/
config.go
84 lines (71 loc) · 1.7 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
package config
import (
"errors"
"fmt"
"github.com/codilime/floodgate/config/auth"
"io/ioutil"
"os"
"os/user"
"path/filepath"
log "github.com/sirupsen/logrus"
"github.com/ghodss/yaml"
)
var location string
// Config is the default configuration for the app
type Config struct {
Endpoint string `json:"endpoint"`
Insecure bool `json:"insecure"`
Auth auth.Config `json:"auth"`
Libraries []string `json:"libraries"`
Resources []string `json:"resources"`
}
// LoadConfig function is used to load configuration from file
func LoadConfig(locations ...string) (*Config, error) {
if len(locations) == 0 {
return nil, fmt.Errorf("no config file provided")
}
location = locations[0]
if location == "" {
userHome := ""
usr, err := user.Current()
if err != nil {
// Fallback by trying to read $HOME
userHome = os.Getenv("HOME")
if userHome != "" {
err = nil
} else {
return nil, fmt.Errorf("failed to read current user from environment: %w", err)
}
} else {
userHome = usr.HomeDir
}
location = filepath.Join(userHome, ".config", "floodgate", "config.yaml")
}
conf := &Config{}
configFile, err := ioutil.ReadFile(location)
if err != nil {
return nil, err
}
err = yaml.Unmarshal(configFile, &conf)
if err != nil {
return nil, err
}
if !conf.Auth.IsValid() {
return nil, errors.New("incorrect auth configuration")
}
return conf, nil
}
// SaveConfig function is used to save configuration file
func SaveConfig(config *Config) error {
configFile, err := yaml.Marshal(&config)
if err != nil {
log.Fatal(err)
return err
}
err = ioutil.WriteFile(location, configFile, 0644)
if err != nil {
log.Fatal(err)
return err
}
return nil
}