-
Notifications
You must be signed in to change notification settings - Fork 11
/
url_values.go
67 lines (60 loc) · 1.5 KB
/
url_values.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
65
66
67
// Copyright 2020 <chaishushan{AT}gmail.com>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package pbgo
import (
"encoding/json"
"fmt"
"net/url"
)
func BuildUrlValues(msg interface{}) (m url.Values, err error) {
defer func() {
if x := recover(); x != nil {
err = fmt.Errorf("pbgo.BuildUrlValues failed: %v", x)
}
}()
d, err := json.Marshal(msg)
if err != nil {
return nil, err
}
var mapx map[string]interface{}
if err := json.Unmarshal(d, &mapx); err != nil {
return nil, err
}
m = pkgUnpackMapXToMapString(mapx)
return m, nil
}
// X is oneof string/float64/[]interface/map[string]interface{}
func pkgUnpackMapXToMapString(mapx map[string]interface{}) map[string][]string {
var m = map[string][]string{}
for k, v := range mapx {
switch v := v.(type) {
case string:
m[k] = append(m[k], v)
case float64:
m[k] = append(m[k], fmt.Sprintf("%v", v))
case []interface{}:
for i := 0; i < len(v); i++ {
switch vi := v[i].(type) {
case string:
m[k] = append(m[k], vi)
case float64:
m[k] = append(m[k], fmt.Sprintf("%v", vi))
case map[string]interface{}:
for kk, vv := range pkgUnpackMapXToMapString(vi) {
m[k+"."+kk] = append(m[k+"."+kk], vv...)
}
default:
// unreachable
}
}
case map[string]interface{}:
for kk, vv := range pkgUnpackMapXToMapString(v) {
m[k+"."+kk] = append(m[k+"."+kk], vv...)
}
default:
// unreachable
}
}
return m
}