(in any)
| 46 | } |
| 47 | |
| 48 | func StructToMap(in any) (map[string]any, error) { |
| 49 | // Get value and handle pointer |
| 50 | val := reflect.ValueOf(in) |
| 51 | if val.Kind() == reflect.Ptr { |
| 52 | val = val.Elem() |
| 53 | } |
| 54 | |
| 55 | // Check that we have a struct |
| 56 | if val.Kind() != reflect.Struct { |
| 57 | return nil, fmt.Errorf("input must be a struct or pointer to struct, got %v", val.Kind()) |
| 58 | } |
| 59 | |
| 60 | // Get type information |
| 61 | typ := val.Type() |
| 62 | out := make(map[string]any) |
| 63 | |
| 64 | // For each field in the struct |
| 65 | for i := 0; i < typ.NumField(); i++ { |
| 66 | field := typ.Field(i) |
| 67 | |
| 68 | // Skip unexported fields |
| 69 | if !field.IsExported() { |
| 70 | continue |
| 71 | } |
| 72 | |
| 73 | name := getJSONName(field) |
| 74 | out[name] = val.Field(i).Interface() |
| 75 | } |
| 76 | |
| 77 | return out, nil |
| 78 | } |
| 79 | |
| 80 | // getJSONName returns the field name to use for JSON mapping |
| 81 | func getJSONName(field reflect.StructField) string { |
no test coverage detected