File: util.go

package info (click to toggle)
golang-github-gophercloud-utils 0.0~git20200508.b0167b9-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 784 kB
  • sloc: sh: 20; makefile: 7
file content (34 lines) | stat: -rw-r--r-- 932 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package internal

import (
	"reflect"
	"strings"
)

// RemainingKeys will inspect a struct and compare it to a map. Any struct
// field that does not have a JSON tag that matches a key in the map or
// a matching lower-case field in the map will be returned as an extra.
//
// This is useful for determining the extra fields returned in response bodies
// for resources that can contain an arbitrary or dynamic number of fields.
func RemainingKeys(s interface{}, m map[string]interface{}) (extras map[string]interface{}) {
	extras = make(map[string]interface{})
	for k, v := range m {
		extras[k] = v
	}

	valueOf := reflect.ValueOf(s)
	typeOf := reflect.TypeOf(s)
	for i := 0; i < valueOf.NumField(); i++ {
		field := typeOf.Field(i)

		lowerField := strings.ToLower(field.Name)
		delete(extras, lowerField)

		if tagValue := field.Tag.Get("json"); tagValue != "" && tagValue != "-" {
			delete(extras, tagValue)
		}
	}

	return
}