65 lines
1.1 KiB
Go
65 lines
1.1 KiB
Go
package config
|
|
|
|
import (
|
|
"errors"
|
|
"log"
|
|
|
|
"github.com/spf13/viper"
|
|
)
|
|
|
|
// Load config file from given path
|
|
func LoadConfig(file string) (*viper.Viper, error) {
|
|
|
|
v := viper.New()
|
|
v.SetConfigName("./" + file)
|
|
v.AddConfigPath(".")
|
|
v.AutomaticEnv()
|
|
if err := v.ReadInConfig(); err != nil {
|
|
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
|
|
return nil, errors.New("config file not found")
|
|
}
|
|
return nil, err
|
|
}
|
|
|
|
return v, nil
|
|
}
|
|
|
|
// Parse config file
|
|
func ParseConfig(v *viper.Viper) (*Config, error) {
|
|
var c Config
|
|
err := v.Unmarshal(&c)
|
|
if err != nil {
|
|
log.Printf("unable to decode into struct, %v", err)
|
|
return nil, err
|
|
}
|
|
return &c, nil
|
|
}
|
|
|
|
// Get config
|
|
func GetConfig() (*Config, error) {
|
|
cfgFile, err := LoadConfig("settings")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
cfg, err := ParseConfig(cfgFile)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return cfg, nil
|
|
}
|
|
|
|
func GetReply() (*Reply, error) {
|
|
cfgFile, err := LoadConfig("reply")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
reply := Reply{}
|
|
_err := cfgFile.Unmarshal(&reply)
|
|
if _err != nil {
|
|
log.Printf("unable to decode into struct, %v", err)
|
|
return nil, err
|
|
}
|
|
return &reply, nil
|
|
}
|