-
Notifications
You must be signed in to change notification settings - Fork 3
/
marshal.go
222 lines (205 loc) · 5.13 KB
/
marshal.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
package uri
import (
"fmt"
"log"
"net/url"
"reflect"
"sort"
"strings"
"time"
)
const (
// sliceDelim used for slices
sliceDelim = ","
mapDelim = "|"
// supported struct tags
uriTag = "uri"
jsonTag = "json"
defaultTag = "default"
requiredTag = "required"
// supported tag values
scheme = "scheme"
host = "host"
path = "path"
userinfo = "userinfo"
password = "password"
username = "username"
filename = "filename"
authority = "authority" // userinfo@host
origin = "origin" // scheme://host/path - see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin
fragment = "fragment" // anything after hash #
)
// Marshal a struct into a string representation of a uri
// Note: Marshal panics if a struct or pointer to a struct is not provided
func Marshal(v interface{}) (s string) {
u := &url.URL{}
uVal := &url.Values{}
vStruct := reflect.ValueOf(v)
if vStruct.Kind() == reflect.Ptr {
if vStruct.IsNil() {
vStruct = reflect.New(vStruct.Type().Elem())
}
vStruct = vStruct.Elem()
}
parseStruct(u, uVal, vStruct)
// Note: url values are sorted by string value as they are encoded
u.RawQuery = uVal.Encode()
return u.String()
}
// MarshalUnescaped is the same as marshal but without url encoding the values
func MarshalUnescaped(v interface{}) string {
m := Marshal(v)
s, err := url.QueryUnescape(m)
if err != nil {
log.Println(err)
return m
}
return s
}
func parseStruct(u *url.URL, uVal *url.Values, vStruct reflect.Value) {
for i := 0; i < vStruct.NumField(); i++ {
field := vStruct.Field(i)
if !field.CanInterface() {
continue // skip unexported variables
}
// check for embedded struct and handle recursively
if field.Kind() == reflect.Struct {
ptr := reflect.New(field.Type())
if !implementsMarshaler(ptr) {
parseStruct(u, uVal, field)
continue
}
} else if field.Kind() == reflect.Ptr && field.Elem().Kind() == reflect.Struct {
if !implementsMarshaler(field) {
parseStruct(u, uVal, field.Elem())
continue
}
}
var name string
structTag := vStruct.Type().Field(i).Tag
tag := parseURITag(structTag)
fs := GetFieldString(field, structTag)
switch tag {
case scheme:
u.Scheme = fs
continue
case host:
u.Host = fs
continue
case path:
u.Path = fs
continue
case fragment:
u.Fragment = fs
continue
case userinfo:
u.User = url.User(fs)
continue
case username:
p, set := u.User.Password()
if set {
u.User = url.UserPassword(fs, p)
} else {
u.User = url.User(fs)
}
continue
case password:
u.User = url.UserPassword(u.User.Username(), fs)
continue
case origin: // scheme://host/path
l, err := url.Parse(fs)
if err == nil {
u.Host = l.Host
u.Scheme = l.Scheme
u.Path = l.Path
}
continue
case authority: //userinfo@host
l, err := url.Parse(fs)
if err == nil {
u.User = l.User
u.Host = l.Host
}
continue
case "-": // skip disabled fields
continue
case "":
name = vStruct.Type().Field(i).Name
default:
name = tag
}
def := vStruct.Type().Field(i).Tag.Get(defaultTag)
// skip default fields
if def == "" && isZero(field) {
continue
} else if fs == def {
continue
}
if field.Kind() == reflect.Slice {
for _, v := range strings.Split(fs, sliceDelim) {
uVal.Add(name, v)
}
} else {
uVal.Add(name, fs)
}
}
}
// GetFieldString returns a string representation of a Value
// booleans become true/false
// nil pointers return "nil"
// slices combine elements with a comma. []int{1,2,3} -> "1,2,3"
func GetFieldString(value reflect.Value, sTag reflect.StructTag) string {
format := sTag.Get("format")
if format != "" {
if value.Type() == reflect.TypeOf(time.Time{}) {
return value.Interface().(time.Time).Format(format)
}
if value.Type() == reflect.TypeOf(&time.Time{}) {
return value.Interface().(*time.Time).Format(format)
}
}
if format == "rune" && value.Kind() == reflect.Int32 {
return string(value.Interface().(rune))
}
switch value.Kind() {
case reflect.String:
return value.Interface().(string)
case reflect.Bool:
if value.Interface().(bool) == true {
return "true"
}
return "false"
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return fmt.Sprintf("%v", value.Interface())
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return fmt.Sprintf("%v", value.Interface())
case reflect.Float32, reflect.Float64:
return fmt.Sprintf("%v", value.Interface())
case reflect.Ptr:
if value.IsNil() {
return "nil"
}
return GetFieldString(value.Elem(), sTag)
case reflect.Slice:
var s string
for i := 0; i < value.Len(); i++ {
s += GetFieldString(value.Index(i), sTag) + sliceDelim
}
return strings.TrimRight(s, sliceDelim)
case reflect.Struct:
s, _ := tryMarshal(value)
return s
case reflect.Map:
iter := value.MapRange()
s := make([]string, 0)
for iter.Next() {
k := GetFieldString(iter.Key(), sTag)
v := GetFieldString(iter.Value(), sTag)
s = append(s, k+":"+v)
}
sort.Sort(sort.StringSlice(s)) // sorted for consistency
return strings.Join(s, mapDelim)
default:
return ""
}
}