/
config.go
50 lines (40 loc) · 918 Bytes
/
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
package config
import (
"log"
"os"
"path"
"path/filepath"
"runtime"
"github.com/kelseyhightower/envconfig"
yaml "gopkg.in/yaml.v2"
"github.com/ermusthofa/randomname/backend/api/model"
)
// Read yaml configuration file, if there are any environment variable
// replace the value from environment variable
func readConfigFile(cfg *model.Config) {
_, b, _, _ := runtime.Caller(0)
basepath := filepath.Dir(b)
f, err := os.Open(path.Join(basepath, "../../config.yaml"))
if err != nil {
failedToLoad(err)
}
defer f.Close()
decoder := yaml.NewDecoder(f)
err = decoder.Decode(cfg)
if err != nil {
failedToLoad(err)
}
}
func readEnvironmentVariable(cfg *model.Config) {
err := envconfig.Process("", cfg)
if err != nil {
failedToLoad(err)
}
}
func LoadConfiguration(cfg *model.Config) {
readConfigFile(cfg)
readEnvironmentVariable(cfg)
}
func failedToLoad(err error) {
log.Fatalln(err)
}