Skip to content

Instantly share code, notes, and snippets.

@cadmuxe
Created November 11, 2019 21:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cadmuxe/927f1e93a7b411a58367012ecc383e8b to your computer and use it in GitHub Desktop.
Save cadmuxe/927f1e93a7b411a58367012ecc383e8b to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"reflect"
"strings"
)
func loadValue(i interface{}, m map[string]string) {
rconfigPtr := reflect.ValueOf(i)
rconfig := reflect.Indirect(rconfigPtr)
for k, v := range m {
_, ok := rconfig.Type().FieldByName(k)
if ok {
field := rconfig.FieldByName(k)
fieldType := field.Kind()
if fieldType == reflect.Bool {
if v == "True" {
field.SetBool(true)
} else if v == "False" {
field.SetBool(false)
} else {
fmt.Printf("The map provided a unvalid value for field: %s, value: %s, valid values are: True/False", k, v)
}
} else if fieldType == reflect.String {
field.SetString(v)
} else if fieldType == reflect.Slice {
if field.Type().Elem().Kind() == reflect.String {
values := strings.Split(v, ",")
field.Set(reflect.ValueOf(values))
} else {
fmt.Printf("struct using a unsupported slice type: %s, only support []string", field.Elem().Kind().String())
}
} else {
fmt.Printf("struct using a unsupported type: %s, only support bool/string.", fieldType)
}
} else {
fmt.Printf("The map contains a unknown key-value pair: %s:%s", k, v)
}
}
}
type Config struct {
T bool
SL []string
}
func main() {
c := Config{}
fmt.Println(c)
loadValue(&c, map[string]string{"T": "True", "SL": "v1,v2"})
fmt.Println(c)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment