-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathqueryparams.go
41 lines (35 loc) · 906 Bytes
/
queryparams.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
package simpleresty
import (
"github.com/davidji99/go-querystring/query"
"net/url"
"reflect"
)
// AddQueryParams takes a slice of opts and adds each field as escaped URL query parameters to a base URL string.
//
// Each element in opts must be a struct whose fields contain "url" tags.
//
// Based on: https://github.com/google/go-github/blob/master/github/github.go#L226
func AddQueryParams(baseURL string, opts ...interface{}) (string, error) {
// Handle if opts is nil
v := reflect.ValueOf(opts)
if v.Kind() == reflect.Slice && v.IsNil() {
return baseURL, nil
}
// Parse URL
u, parseErr := url.Parse(baseURL)
if parseErr != nil {
return "", parseErr
}
fulQS := url.Values{}
for _, opt := range opts {
qs, err := query.Values(opt)
if err != nil {
return baseURL, err
}
for k, v := range qs {
fulQS[k] = v
}
}
u.RawQuery = fulQS.Encode()
return u.String(), nil
}