package config import ( "errors" "io/ioutil" "os" "path" "git.trj.tw/golang/utils" "github.com/jesseduffield/yaml" "github.com/otakukaze/envconfig" ) type Server struct { Port int `yaml:"port" env:"SERVER_PORT"` } type Remote struct { WSLoc string `yaml:"ws_loc" env:"REMOTE_WS_LOC"` } type LED struct { Count int `yaml:"count" env:"LED_COUNT"` Pin int `yaml:"pin" env:"LED_PIN"` } type Config struct { Server Server `yaml:"server"` Remote Remote `yaml:"remote"` LED LED `yaml:"led"` } var c *Config func Load(p ...string) error { var fp string if len(p) > 0 && p[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 !utils.CheckExists(fp, false) { return errors.New("config file not found") } // read config file b, err := ioutil.ReadFile(fp) if err != nil { return err } c = &Config{} if err := yaml.Unmarshal(b, c); err != nil { return err } envconfig.Parse(c) return nil } func Get() *Config { if c == nil { panic(errors.New("config not init")) } return c }