Basic function that can be used with structs that need to implement the exportable interface. It has numerous limitations so verify that it works as expected with the struct and fields you want to export. If it does not, then implementing a custom ExportData method is necessary. Perhaps this should
(s interface{}, fields []string)
| 305 | // a struct does not implement the exportable interface, but for now it will |
| 306 | // need to be explicitly used. |
| 307 | func StructExportData(s interface{}, fields []string) map[string]interface{} { |
| 308 | v := reflect.ValueOf(s) |
| 309 | if v.Kind() == reflect.Ptr { |
| 310 | v = v.Elem() |
| 311 | } |
| 312 | if v.Kind() != reflect.Struct { |
| 313 | // If s is not a struct or pointer to a struct return nil. |
| 314 | return nil |
| 315 | } |
| 316 | data := make(map[string]interface{}, len(fields)) |
| 317 | for _, f := range fields { |
| 318 | sf := fieldByName(v, f) |
| 319 | if sf.IsValid() && sf.CanInterface() { |
| 320 | data[f] = sf.Interface() |
| 321 | } |
| 322 | } |
| 323 | return data |
| 324 | } |
| 325 | |
| 326 | func fieldByName(v reflect.Value, field string) reflect.Value { |
| 327 | return v.FieldByNameFunc(func(s string) bool { |