(in any)
| 91 | } |
| 92 | |
| 93 | func StructToMap(in any) (map[string]any, error) { |
| 94 | // Get value and handle pointer |
| 95 | val := reflect.ValueOf(in) |
| 96 | if val.Kind() == reflect.Ptr { |
| 97 | val = val.Elem() |
| 98 | } |
| 99 | |
| 100 | // Check that we have a struct |
| 101 | if val.Kind() != reflect.Struct { |
| 102 | return nil, fmt.Errorf("input must be a struct or pointer to struct, got %v", val.Kind()) |
| 103 | } |
| 104 | |
| 105 | // Get type information |
| 106 | typ := val.Type() |
| 107 | out := make(map[string]any) |
| 108 | |
| 109 | // For each field in the struct |
| 110 | for i := 0; i < typ.NumField(); i++ { |
| 111 | field := typ.Field(i) |
| 112 | |
| 113 | // Skip unexported fields |
| 114 | if !field.IsExported() { |
| 115 | continue |
| 116 | } |
| 117 | |
| 118 | name := getJSONName(field) |
| 119 | out[name] = val.Field(i).Interface() |
| 120 | } |
| 121 | |
| 122 | return out, nil |
| 123 | } |
| 124 | |
| 125 | // getJSONName returns the field name to use for JSON mapping |
| 126 | func getJSONName(field reflect.StructField) string { |
no test coverage detected