github.com/ppphp/yayagf@v0.0.1/pkg/config/config.go (about) 1 package config 2 3 import ( 4 "errors" 5 "io/ioutil" 6 "os" 7 "reflect" 8 "strconv" 9 "strings" 10 11 "github.com/BurntSushi/toml" 12 ) 13 14 var ErrorNoToml = errors.New("toml not found") 15 16 func LoadTomlFile(name string, conf interface{}) error { 17 18 b, err := ioutil.ReadFile(name) 19 if err != nil { 20 return ErrorNoToml 21 } 22 23 if err := toml.Unmarshal(b, conf); err != nil { 24 return err 25 } 26 27 return nil 28 } 29 30 func LoadEnv(conf interface{}) { 31 val := reflect.ValueOf(conf).Elem() 32 for i := 0; i < val.NumField(); i++ { 33 name := val.Type().Field(i).Name 34 v, ok := os.LookupEnv(strings.ToUpper(name)) 35 if ok && v != "" { 36 switch val.Type().Field(i).Type.Kind() { 37 case reflect.Struct: 38 panic("shall not") 39 case reflect.String: 40 val.Field(i).SetString(v) 41 case reflect.Int: 42 vi, _ := strconv.Atoi(v) 43 val.Field(i).SetInt(int64(vi)) 44 } 45 } 46 } 47 } 48 49 // only support ini like config in env and no lock 50 func LoadConfig(conf interface{}) error { 51 if err := LoadTomlFile("conf.toml", conf); err != nil { 52 return err 53 } 54 55 LoadEnv(conf) 56 57 return nil 58 }