Joe Topjian | 1e9551c | 2017-06-03 10:35:33 -0600 | [diff] [blame^] | 1 | package internal |
| 2 | |
| 3 | import ( |
| 4 | "reflect" |
| 5 | ) |
| 6 | |
| 7 | // RemainingKeys will inspect a struct and compare it to a map. Any key that |
| 8 | // is not defined in a JSON tag of the struct will be added to the extras map |
| 9 | // and returned. |
| 10 | // |
| 11 | // This is useful for determining the extra fields returned in response bodies |
| 12 | // for resources that can contain an arbitrary or dynamic number of fields. |
| 13 | func RemainingKeys(s interface{}, m map[string]interface{}) (extras map[string]interface{}) { |
| 14 | extras = make(map[string]interface{}) |
| 15 | valueOf := reflect.ValueOf(s) |
| 16 | typeOf := reflect.TypeOf(s) |
| 17 | for i := 0; i < valueOf.NumField(); i++ { |
| 18 | field := typeOf.Field(i) |
| 19 | tagValue := field.Tag.Get("json") |
| 20 | if _, ok := m[tagValue]; !ok { |
| 21 | extras[tagValue] = m[tagValue] |
| 22 | } |
| 23 | } |
| 24 | |
| 25 | return |
| 26 | } |