/
config.go
42 lines (34 loc) · 878 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
package internal
import (
"flag"
"fmt"
"strings"
"github.com/spf13/viper"
)
// Config contains the full config structure of this application
type Config struct {
AppName string
Port string
}
// GetConfig gets the config setup from env or yaml file source
func GetConfig() (*Config, error) {
v := viper.New()
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
v.SetTypeByDefaultValue(true)
v.AutomaticEnv()
v.SetConfigType("yaml")
configFile := flag.String("config", "config.yaml", "path to configuration file")
flag.Parse()
if *configFile == "" {
return nil, fmt.Errorf("required flag -config not set")
}
v.SetConfigFile(*configFile)
if err := v.ReadInConfig(); err != nil {
return nil, fmt.Errorf("error loading config file: %w", err)
}
cfg := &Config{
AppName: v.GetString("app_name"),
Port: v.GetString("port"),
}
return cfg, nil
}