-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
97 lines (79 loc) · 1.86 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
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
package minox
import (
"net/http"
"net/url"
"reflect"
"strconv"
null "gopkg.in/guregu/null.v3"
"github.com/gorilla/schema"
)
type SchemaMarshaler interface {
MarshalSchema() string
}
type ToURLValues interface {
ToURLValues() (url.Values, error)
}
func AddQueryParamsToRequest(requestParams interface{}, req *http.Request, skipEmpty bool) error {
var err error
params := url.Values{}
to, ok := requestParams.(ToURLValues)
if ok == true {
params, err = to.ToURLValues()
if err != nil {
return err
}
} else {
encoder := newSchemaEncoder()
err := encoder.Encode(requestParams, params)
if err != nil {
return err
}
}
query := req.URL.Query()
for k, vals := range params {
for _, v := range vals {
if skipEmpty && v == "" {
continue
}
if skipEmpty && v == "0" {
continue
}
query.Add(k, v)
}
}
req.URL.RawQuery = query.Encode()
return nil
}
func newSchemaEncoder() *schema.Encoder {
encoder := schema.NewEncoder()
// // register custom encoders
// encodeSchemaMarshaler := func(v reflect.Value) string {
// marshaler, ok := v.Interface().(SchemaMarshaler)
// if ok == true {
// return marshaler.MarshalSchema()
// }
// stringer, ok := v.Interface().(fmt.Stringer)
// if ok == true {
// return stringer.String()
// }
// return ""
// }
encodeNullFloat := func(v reflect.Value) string {
nullFloat, _ := v.Interface().(null.Float)
if nullFloat.IsZero() {
return ""
}
return strconv.FormatFloat(nullFloat.Float64, 'f', 6, 64)
}
encodeNullBool := func(v reflect.Value) string {
nullBool, _ := v.Interface().(null.Bool)
if nullBool.IsZero() {
return ""
}
return strconv.FormatBool(nullBool.Bool)
}
// encoder.RegisterEncoder(Date{}, encodeSchemaMarshaler)
encoder.RegisterEncoder(null.Float{}, encodeNullFloat)
encoder.RegisterEncoder(null.Bool{}, encodeNullBool)
return encoder
}