/
util.go
71 lines (61 loc) · 1.77 KB
/
util.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
package vk
import (
"net/url"
"github.com/google/go-querystring/query"
"github.com/mailru/easyjson/jlexer"
)
// MergeURLValues merges mergeWith into base
//
// Can be useful when implementing API.Request
func MergeURLValues(base, mergeWith url.Values) {
for k, v := range mergeWith {
if old, ok := base[k]; ok {
base[k] = append(old, v...)
} else {
base[k] = v
}
}
}
// BuildRequestParams is a helper function which can be used when implementing API.Request
//
// params can be:
// - nil
// - url.Values
// - url tagged struct (https://godoc.org/github.com/google/go-querystring/query)
func BuildRequestParams(params interface{}) (url.Values, error) {
switch v := params.(type) {
case nil:
return make(url.Values), nil
case url.Values:
return v, nil
default:
return query.Values(params)
}
}
// BoolInt is bool type which conforms to easyjson.Unmarshaler interface
// and unmarshals from VK's favorite 1/0 int bools
type BoolInt bool
// UnmarshalJSON implements json.Unmarshaler interface
func (v *BoolInt) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
v.UnmarshalEasyJSON(&r)
return r.Error()
}
// UnmarshalEasyJSON implements easyjson.Unmarshaler interface
func (v *BoolInt) UnmarshalEasyJSON(in *jlexer.Lexer) {
*v = in.Int() != 0
}
// IntFrac is int type which conforms to easyjson.Unmarshaler interface
// and unmarshals as float to workaround VK bug with ints being sent
// as fractionals
type IntFrac int
// UnmarshalJSON implements json.Unmarshaler interface
func (v *IntFrac) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
v.UnmarshalEasyJSON(&r)
return r.Error()
}
// UnmarshalEasyJSON implements easyjson.Unmarshaler interface
func (v *IntFrac) UnmarshalEasyJSON(in *jlexer.Lexer) {
*v = IntFrac(int(in.Float32()))
}