package config import ( "errors" "io/ioutil" "os" "path" "strconv" "gopkg.in/yaml.v2" "git.trj.tw/golang/utils" ) // Config struct type Config struct { Port int `yaml:"port"` FilePath string `yaml:"file_path"` } var conf *Config // LoadConfig - func LoadConfig(p ...interface{}) (err error) { var confPath string if len(p) > 0 { if str, ok := p[0].(string); ok && len(str) > 0 { confPath = str } } if len(confPath) == 0 { root, err := os.Getwd() if err != nil { return err } confPath = path.Join(root, "config.yml") } if !utils.CheckExists(confPath, false) { return errors.New("config file not found") } fileByte, err := ioutil.ReadFile(confPath) if err != nil { return err } conf = &Config{} err = yaml.Unmarshal(fileByte, conf) overrideConfgWithEnv() if !utils.IsDir(conf.FilePath) { return errors.New("file path not folder") } return } func overrideConfgWithEnv() { port := os.Getenv("PORT") if len(port) > 0 { if port, err := strconv.Atoi(port); err == nil { conf.Port = port } } filePath := os.Getenv("FILE_PATH") if len(filePath) > 0 { if utils.CheckExists(filePath, true) { conf.FilePath = filePath } } } // GetConf - func GetConf() *Config { return conf }