package main
import (
"fmt"
"reflect"
)
type Config struct {
AppName string `json:"app_name"`
Port int `json:"port"`
Debug bool `json:"debug"`
}
// LoadConfigFromMap loads configuration from a map[string]interface{}
func LoadConfigFromMap(cfg interface{}, data map[string]interface{}) {
v := reflect.ValueOf(cfg).Elem()
for key, value := range data {
field := v.FieldByName(key)
if field.IsValid() && field.CanSet() {
if field.Kind() == reflect.Ptr {
if field.IsNil() {
field.Set(reflect.New(field.Type().Elem()))
}
field = field.Elem()
}
valueType := reflect.TypeOf(value)
if field.Kind() == valueType.Kind() {
field.Set(reflect.ValueOf(value))
} else if field.Kind() == reflect.Struct {
// Recursively call LoadConfigFromMap if the field is a struct
LoadConfigFromMap(field.Addr().Interface(), value.(map[string]interface{}))
}
}
}
}
func main() {
cfg := &Config{}
configData := map[string]interface{}{
"app_name": "MyApp",
"port": 8080,
"debug": true,
"db": map[string]interface{}{
"host": "localhost",
"port": 3306,
},
}
LoadConfigFromMap(cfg, configData)
fmt.Printf("%#v\n", cfg)
}
cGFja2FnZSBtYWluCgppbXBvcnQgKAoJImZtdCIKCSJyZWZsZWN0IgopCgp0eXBlIENvbmZpZyBzdHJ1Y3QgewoJQXBwTmFtZSBzdHJpbmcgYGpzb246ImFwcF9uYW1lImAKCVBvcnQgICAgaW50ICAgIGBqc29uOiJwb3J0ImAKCURlYnVnICAgYm9vbCAgIGBqc29uOiJkZWJ1ZyJgCn0KCi8vIExvYWRDb25maWdGcm9tTWFwIGxvYWRzIGNvbmZpZ3VyYXRpb24gZnJvbSBhIG1hcFtzdHJpbmddaW50ZXJmYWNle30KZnVuYyBMb2FkQ29uZmlnRnJvbU1hcChjZmcgaW50ZXJmYWNle30sIGRhdGEgbWFwW3N0cmluZ11pbnRlcmZhY2V7fSkgewoJdiA6PSByZWZsZWN0LlZhbHVlT2YoY2ZnKS5FbGVtKCkKCWZvciBrZXksIHZhbHVlIDo9IHJhbmdlIGRhdGEgewoJCWZpZWxkIDo9IHYuRmllbGRCeU5hbWUoa2V5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