96 lines
1.5 KiB
Go
96 lines
1.5 KiB
Go
package config
|
|
|
|
import (
|
|
"errors"
|
|
"io/ioutil"
|
|
"os"
|
|
"path"
|
|
"strconv"
|
|
|
|
"git.trj.tw/golang/utils"
|
|
yaml "gopkg.in/yaml.v2"
|
|
)
|
|
|
|
// Config -
|
|
type Config struct {
|
|
Port int `yaml:"port"`
|
|
AWS struct {
|
|
SharedConfig bool `yaml:"shared_config"`
|
|
AccessKey string `yaml:"access_key"`
|
|
SecretKey string `yaml:"secret_key"`
|
|
} `yaml:"aws"`
|
|
}
|
|
|
|
var conf *Config
|
|
|
|
// LoadConfig -
|
|
func LoadConfig(p ...string) (err error) {
|
|
fp := ""
|
|
if len(p) > 0 && len(p[0]) > 0 {
|
|
fp = p[0]
|
|
} else {
|
|
wd, err := os.Getwd()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
fp = path.Join(wd, "config.yml")
|
|
}
|
|
|
|
fp = utils.ParsePath(fp)
|
|
if exists := utils.CheckExists(fp, false); !exists {
|
|
return errors.New("config file not exists")
|
|
}
|
|
data, err := ioutil.ReadFile(fp)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
conf = &Config{}
|
|
err = yaml.Unmarshal(data, conf)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
envOverride()
|
|
|
|
return
|
|
}
|
|
|
|
func envOverride() {
|
|
var str string
|
|
// set port
|
|
str = os.Getenv("PORT")
|
|
if len(str) > 0 {
|
|
num, err := strconv.Atoi(str)
|
|
if err == nil && num > 0 && num < 65536 {
|
|
conf.Port = num
|
|
}
|
|
}
|
|
|
|
// set aws use shared config
|
|
str = os.Getenv("AWS_SHARED_CONF")
|
|
if len(str) > 0 {
|
|
if str == "1" {
|
|
conf.AWS.SharedConfig = true
|
|
} else if str == "0" {
|
|
conf.AWS.SharedConfig = false
|
|
}
|
|
}
|
|
|
|
// set aws access key
|
|
str = os.Getenv("AWS_ACCESS_KEY")
|
|
if len(str) > 0 {
|
|
conf.AWS.AccessKey = str
|
|
}
|
|
|
|
// set aws secret key
|
|
str = os.Getenv("AWS_SECRET_KEY")
|
|
if len(str) > 0 {
|
|
conf.AWS.SecretKey = str
|
|
}
|
|
}
|
|
|
|
// GetConfig -
|
|
func GetConfig() *Config {
|
|
return conf
|
|
}
|