/
config.go
94 lines (82 loc) · 2.55 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
package main
import (
"os"
"github.com/spf13/viper"
)
// Config holds a reference to any required config. It uses viper to
// unmarshal environment variables into the configuration.
type Config struct {
Port int
OpenWeatherMap struct {
APIKey string `mapstructure:"openweathermap_apikey"`
} `mapstructure:",squash"`
Skill struct {
PrivateKey string `mapstructure:"skill_private_key"`
PublicKey string `mapstructure:"skill_public_key"`
Secret string `mapstructure:"skill_secret"`
} `mapstructure:",squash"`
AWS struct {
Region string `mapstructure:"aws_region"`
AccessKeyID string `mapstructure:"aws_access_key_id"`
SecretAccessKey string `mapstructure:"aws_secret_access_key"`
} `mapstructure:",squash"`
Lex struct {
Alias string `mapstructure:"lex_alias"`
BotName string `mapstructure:"lex_botname"`
} `mapstructure:",squash"`
}
func loadConfig() (*Config, error) {
// Set defaults
viper.SetDefault("port", 8080)
viper.SetDefault("skill_private_key", "")
viper.SetDefault("skill_public_key", "")
viper.SetDefault("skill_secret", "")
viper.SetDefault("aws_region", "")
viper.SetDefault("aws_access_key_id", "")
viper.SetDefault("aws_secret_access_key", "")
viper.SetDefault("lex_alias", "")
viper.SetDefault("lex_botname", "")
viper.SetDefault("openweathermap_apikey", "")
// Set up Viper
viper.SetConfigName(".env")
viper.SetConfigType("env")
viper.AddConfigPath(".")
viper.ReadInConfig() // ignore error since there may not be a config file
viper.AutomaticEnv() // read in environment variables that match
cfg := Config{}
err := viper.Unmarshal(&cfg)
if err != nil {
return nil, err
}
if cfg.OpenWeatherMap.APIKey == "" {
return nil, ErrMissingWeatherEnvironment
}
if cfg.AWS.Region == "" || cfg.AWS.AccessKeyID == "" || cfg.AWS.SecretAccessKey == "" || cfg.Lex.Alias == "" || cfg.Lex.BotName == "" {
return nil, ErrMissingAWSEnvironment
}
if cfg.Skill.PrivateKey == "" || cfg.Skill.PublicKey == "" || cfg.Skill.Secret == "" {
// let's try to find the files instead?
if cfg.Skill.PrivateKey == "" {
f, err := os.ReadFile("private.pem")
if err != nil {
return nil, ErrMissingEnvironment
}
cfg.Skill.PrivateKey = string(f)
}
if cfg.Skill.PublicKey == "" {
f, err := os.ReadFile("public.pem")
if err != nil {
return nil, ErrMissingEnvironment
}
cfg.Skill.PublicKey = string(f)
}
if cfg.Skill.Secret == "" {
f, err := os.ReadFile("secret.txt")
if err != nil {
return nil, ErrMissingEnvironment
}
cfg.Skill.Secret = string(f)
}
}
return &cfg, nil
}