package main
import (
"fmt"
"reflect"
)
type Config struct {
AppName string `json:"app_name"`
Port int `json:"port"`
Debug bool `json:"debug"`
}
func LoadConfig(config *Config, configData map[string]interface{}) {
v := reflect.ValueOf(config).Elem()
for key, value := range configData {
field := v.FieldByName(key)
if field.IsValid() {
fieldType := field.Type()
if fieldType.Kind() == reflect.Ptr {
fieldType = fieldType.Elem()
}
if fieldType.AssignableTo(reflect.TypeOf(value)) {
field.Set(reflect.ValueOf(value))
}
}
}
}
func main() {
configData := map[string]interface{}{
"app_name": "MyApp",
"port": 8080,
"debug": true,
}
var config Config
LoadConfig(&config, configData)
fmt.Println("App Name:", config.AppName)
fmt.Println("Port:", config.Port)
fmt.Println("Debug:", config.Debug)
}
cGFja2FnZSBtYWluCgppbXBvcnQgKAoJImZtdCIKCSJyZWZsZWN0IgopCgp0eXBlIENvbmZpZyBzdHJ1Y3QgewoJQXBwTmFtZSAgICAgc3RyaW5nIGBqc29uOiJhcHBfbmFtZSJgCglQb3J0ICAgICAgICBpbnQgICAgYGpzb246InBvcnQiYAoJRGVidWcgICAgICAgYm9vbCAgIGBqc29uOiJkZWJ1ZyJgCn0KCmZ1bmMgTG9hZENvbmZpZyhjb25maWcgKkNvbmZpZywgY29uZmlnRGF0YSBtYXBbc3RyaW5nXWludGVyZmFjZXt9KSB7Cgl2IDo9IHJlZmxlY3QuVmFsdWVPZihjb25maWcpLkVsZW0oKQoJZm9yIGtleSwgdmFsdWUgOj0gcmFuZ2UgY29uZmlnRGF0YSB7CgkJZmllbGQgOj0gdi5GaWVsZEJ5TmFtZShrZXkpCgkJaWYgZmllbGQuSXNWYWxpZCgpIHsKCQkJZmllbGRUeXBlIDo9IGZpZWxkLlR5cGUoKQoJCQlpZiBmaWVsZFR5cGUuS2luZCgpID09IHJlZmxlY3QuUHRyIHsKCQkJCWZpZWxkVHlwZSA9IGZpZWxkVHlwZS5FbGVtKCkKCQkJfQoJCQlpZiBmaWVsZFR5cGUuQXNzaWduYWJsZVRvKHJlZmxl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