This repository has been archived by the owner on Aug 12, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
utils.go
64 lines (56 loc) · 1.6 KB
/
utils.go
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package opentelekomcloud
import (
"encoding/json"
"fmt"
"log"
"reflect"
"regexp"
"strings"
)
func jsonBytesEqual(b1, b2 []byte) bool {
var o1 interface{}
if err := json.Unmarshal(b1, &o1); err != nil {
return false
}
var o2 interface{}
if err := json.Unmarshal(b2, &o2); err != nil {
return false
}
return reflect.DeepEqual(o1, o2)
}
// convertStructToMap converts an instance of struct to a map object, and
// changes each key of fileds to the value of 'nameMap' if the key in it
// or to its corresponding lowercase.
func convertStructToMap(obj interface{}, nameMap map[string]string) (map[string]interface{}, error) {
b, err := json.Marshal(obj)
if err != nil {
return nil, fmt.Errorf("Error converting struct to map, marshal failed:%v", err)
}
m, err := regexp.Compile(`"[a-z0-9A-Z_]+":`)
if err != nil {
return nil, fmt.Errorf("Error converting struct to map, compile regular express failed")
}
nb := m.ReplaceAllFunc(
b,
func(src []byte) []byte {
k := fmt.Sprintf("%s", src[1:len(src)-2])
v, ok := nameMap[k]
if !ok {
v = strings.ToLower(k)
}
return []byte(fmt.Sprintf("\"%s\":", v))
},
)
log.Printf("[DEBUG]convertStructToMap:: before change b =%s", b)
log.Printf("[DEBUG]convertStructToMap:: after change nb=%s", nb)
p := make(map[string]interface{})
err = json.Unmarshal(nb, &p)
if err != nil {
return nil, fmt.Errorf("Error converting struct to map, unmarshal failed:%v", err)
}
log.Printf("[DEBUG]convertStructToMap:: map= %#v\n", p)
return p, nil
}
func looksLikeJsonString(s interface{}) bool {
return regexp.MustCompile(`^\s*{`).MatchString(s.(string))
}