№ 11025 В разделе "Programming"
от June 16th, 2020,
В подшивках: Go
Tried to unmarshal enum value from app config file and failed?
DB: masterDB: "ips.sdb" clean: Full
Use strings instead of iota.
const ( CleanRecreate = "Recreate" // completely remove DB file and create again CleanFull = "Full" // delete all and vacuum CleanLastDay = "LastDay" // remove all before last day CleanLastWeek = "LastWeek" CleanLastMonth = "LastMonth" CleanNever = "Never" // do nothing ) type CleanType string type AppConfig struct { DB struct { MasterDB string `yaml:"masterDB"` // master sqlite database Clean CleanType `yaml:"clean,omitempty"` // cleanup at startup } `yaml:"DB"` }
Now load config file:
func main() { flag.Parse() if *configFilename == "" { log.Fatalln("Set configuration filename") } // read settings from file log.Println("Loading config file", *configFilename) appConfig := AppConfig{} yamlFile, err := ioutil.ReadFile(*configFilename) if err != nil { log.Fatalf("Config read error: %v\n", err) } err = yaml.Unmarshal(yamlFile, &appConfig) if err != nil { log.Fatalf("Config format error: %v\n", err) } switch appConfig.DB.Clean { case CleanRecreate: log.Println("Recreate cleanup option set") os.Remove(appConfig.DB.MasterDB) case CleanFull: log.Println("Full cleanup option set") case CleanLastDay: log.Println("Save only last day cleanup option set") case CleanLastWeek: log.Println("Save only last week option set") case CleanLastMonth: log.Println("Save only last month option set") } dbHandler := dbLoadFile(appConfig.DB.MasterDB) defer dbHandler.Close() }
Here is another solution https://gist.github.com/lummie/7f5c237a17853c031a57277371528e87#file-enum-go
Fortune cookie: Today's spam: Win the fa_t fight
Leave a Reply