Idea: Use reflect to populate default config values #37

Open
opened 2021-03-19 16:39:36 +01:00 by leon · 2 comments
leon commented 2021-03-19 16:39:36 +01:00 (Migrated from git.leon.wtf)

Idea:

// A Config is an instance of an unmarshalled
// configuration file
type Config struct {
	BindAddress    string `json:"host_address" default:"0.0.0.0:3002"`
	MongoDBAddress string `json:"mongodb_address" default:"localhost:27017"`
	Test           int    `default:"2"`
}

// setDefaults sets all uninitialized fields
// to their default values
func (c *Config) setDefaults() {
	t := reflect.TypeOf(c)
	v := reflect.ValueOf(c)
	for i := 0; i < t.Elem().NumField(); i++ { // iterate over struct fields
		tag, _ := t.Elem().Field(i).Tag.Lookup("default") // get "default" tag value
		if v.Elem().Field(i).Kind() == reflect.String && v.Elem().Field(i).String() == "" { // check if field is string and empty
			v.Elem().Field(i).SetString(tag) // set string
		} else if v.Elem().Field(i).Kind() == reflect.Int && v.Elem().Field(i).Int() == 0 { // check if field is int and zero
			if i, err := strconv.Atoi(tag); err == nil { // cast tag string to int
				v.Elem().Field(i).SetInt(int64(i)) // set int
			} else {
				panic(err)
			}
		}
	}
}
Idea: ```go // A Config is an instance of an unmarshalled // configuration file type Config struct { BindAddress string `json:"host_address" default:"0.0.0.0:3002"` MongoDBAddress string `json:"mongodb_address" default:"localhost:27017"` Test int `default:"2"` } // setDefaults sets all uninitialized fields // to their default values func (c *Config) setDefaults() { t := reflect.TypeOf(c) v := reflect.ValueOf(c) for i := 0; i < t.Elem().NumField(); i++ { // iterate over struct fields tag, _ := t.Elem().Field(i).Tag.Lookup("default") // get "default" tag value if v.Elem().Field(i).Kind() == reflect.String && v.Elem().Field(i).String() == "" { // check if field is string and empty v.Elem().Field(i).SetString(tag) // set string } else if v.Elem().Field(i).Kind() == reflect.Int && v.Elem().Field(i).Int() == 0 { // check if field is int and zero if i, err := strconv.Atoi(tag); err == nil { // cast tag string to int v.Elem().Field(i).SetInt(int64(i)) // set int } else { panic(err) } } } } ```
leon commented 2021-03-19 16:40:05 +01:00 (Migrated from git.leon.wtf)

changed the description

changed the description
leon commented 2021-03-19 18:01:38 +01:00 (Migrated from git.leon.wtf)

changed the description

changed the description
Sign in to join this conversation.
No description provided.