fork download
  1. package main
  2.  
  3. import (
  4. "fmt"
  5. "reflect"
  6. )
  7.  
  8. type Config struct {
  9. AppName string `json:"app_name"`
  10. Port int `json:"port"`
  11. Debug bool `json:"debug"`
  12. }
  13.  
  14. func LoadConfig(config *Config, configData map[string]interface{}) {
  15. v := reflect.ValueOf(config).Elem()
  16. for key, value := range configData {
  17. field := v.FieldByName(key)
  18. if field.IsValid() {
  19. fieldType := field.Type()
  20. if fieldType.Kind() == reflect.Ptr {
  21. fieldType = fieldType.Elem()
  22. }
  23. if fieldType.AssignableTo(reflect.TypeOf(value)) {
  24. field.Set(reflect.ValueOf(value))
  25. }
  26. }
  27. }
  28. }
  29.  
  30. func main() {
  31. configData := map[string]interface{}{
  32. "app_name": "MyApp",
  33. "port": 8080,
  34. "debug": true,
  35. }
  36.  
  37. var config Config
  38. LoadConfig(&config, configData)
  39.  
  40. fmt.Println("App Name:", config.AppName)
  41. fmt.Println("Port:", config.Port)
  42. fmt.Println("Debug:", config.Debug)
  43. }
Success #stdin #stdout 0s 5284KB
stdin
Standard input is empty
stdout
App Name: 
Port: 0
Debug: false