package config import ( "fmt" "maps" "reflect" "slices" "strings" "time" ) // Value returns the setting at the dotted key, such as "webserver.port", in // the form a config file or an environment variable gives it: durations such // as "15s", lists comma-separated, and tables as name=value entries, sorted // and comma-separated. Key names match case-insensitively. func (c *Config) Value(key string) (string, error) { v := reflect.ValueOf(*c) for part := range strings.SplitSeq(key, ".") { field, ok := fieldByKey(v, part) if !ok { return "", fmt.Errorf("unknown key %q", key) } v = field } if v.Kind() == reflect.Struct { return "", fmt.Errorf("%q is a section; name one of its settings", key) } if v.Kind() == reflect.Slice && v.Type().Elem().Kind() == reflect.Struct { return "", fmt.Errorf("%q is a list of tables, which has no single value", key) } switch value := v.Interface().(type) { case time.Duration: return value.String(), nil case []string: return strings.Join(value, ","), nil case map[string]string: entries := make([]string, 0, len(value)) for _, name := range slices.Sorted(maps.Keys(value)) { entries = append(entries, name+"="+value[name]) } return strings.Join(entries, ","), nil default: return fmt.Sprint(value), nil } } // fieldByKey returns the field of the struct v whose mapstructure tag is // name. func fieldByKey(v reflect.Value, name string) (reflect.Value, bool) { if v.Kind() != reflect.Struct { return reflect.Value{}, false } t := v.Type() for i := range t.NumField() { if tag := t.Field(i).Tag.Get("mapstructure"); tag != "" && tag == strings.ToLower(name) { return v.Field(i), true } } return reflect.Value{}, false }