forked from huaweicloud/terraform-provider-huaweicloud
/
utils.go
45 lines (41 loc) · 1.23 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
package huaweicloud
import (
"encoding/json"
"fmt"
"log"
"regexp"
"strings"
)
// 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
}