-
Notifications
You must be signed in to change notification settings - Fork 14
/
config.go
112 lines (91 loc) · 2.26 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package config
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/joho/godotenv"
"github.com/spf13/viper"
)
const configName = "config"
type Config struct {
*viper.Viper
}
func NewViperConfig(appName, mode, localConfigFolder string) (*Config, error) {
viper.SetConfigName(configName)
configFolder, hasConfigFolder := os.LookupEnv("APP_CONFIG_FOLDER")
if !hasConfigFolder {
configFolder = localConfigFolder
}
viper.SetConfigFile(configFolder + "/" + appName + "/config.yaml")
err := viper.ReadInConfig()
if err != nil {
return nil, err
}
configBytes, err := ioutil.ReadFile(configFolder + "/hitrix.yaml")
if err == nil {
err = viper.MergeConfig(bytes.NewBuffer(configBytes))
if err != nil {
return nil, fmt.Errorf("fatal error config file: %s", err)
}
}
viperConfig := &Config{
viper.GetViper(),
}
err = viperConfig.loadEnvConfig(mode)
if err != nil {
return nil, err
}
return viperConfig, nil
}
func (v *Config) loadEnvConfig(mode string) error {
mainConfigFolderPath := v.GetFolderPath()
if _, err := os.Stat(mainConfigFolderPath + "/.env." + mode); !os.IsNotExist(err) {
err := godotenv.Load(mainConfigFolderPath + "/.env." + mode)
if err != nil {
return err
}
}
for _, key := range v.Viper.AllKeys() {
val, ok := v.Viper.Get(key).(string)
if ok && strings.HasPrefix(v.Viper.Get(key).(string), "ENV[") {
envKey := strings.TrimLeft(strings.TrimRight(val, "]"), "ENV[")
_, has := os.LookupEnv(envKey)
if !has {
return errors.New("missing value for ENV variable " + envKey)
}
s := strings.Split(key, ".")
if len(s) > 1 {
subKey := strings.Join(s[0:len(s)-1], ".")
subVal := v.Viper.Get(subKey).(map[string]interface{})
subVal[s[len(s)-1]] = os.Getenv(envKey)
} else {
v.Viper.Set(key, os.Getenv(envKey))
}
}
}
return nil
}
func (v *Config) GetFolderPath() string {
fileUsed := v.ConfigFileUsed()
abs, _ := filepath.Abs(fileUsed)
pathFragments := strings.Split(strings.TrimLeft(abs, "/"), "/")
lastIndex := 0
for i, fragment := range pathFragments {
if fragment == "config" {
lastIndex = i
break
}
}
var path string
for j, fragment := range pathFragments {
path += "/" + fragment
if lastIndex == j {
break
}
}
return path
}