-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvotesmart.go
134 lines (106 loc) · 2.23 KB
/
votesmart.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
package votesmart
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
)
const defaultBaseURL = "https://api.votesmart.org/"
func New(apiKey string, options ...Option) (Client, error) {
var opts clientOptions
for _, opt := range options {
opts = opt(opts)
}
if opts.baseURL == "" {
opts.baseURL = defaultBaseURL
}
if opts.client == nil {
opts.client = http.DefaultClient
}
u, err := url.Parse(opts.baseURL)
if err != nil {
return nil, err
}
return &client{
HTTP: opts.client,
BaseURL: u,
APIKey: apiKey,
}, nil
}
type Client interface {
Invoke(ctx context.Context, params *url.Values, dst Method) error
}
type Method interface {
Method() string
}
type clientOptions struct {
client *http.Client
baseURL string
}
type Option func(clientOptions) clientOptions
func WithClient(v *http.Client) Option {
return func(o clientOptions) clientOptions {
o.client = v
return o
}
}
func WithBaseURL(v string) Option {
return func(o clientOptions) clientOptions {
o.baseURL = v
return o
}
}
type Error struct {
ErrorMessage string `json:"errorMessage"`
}
func (e Error) Error() string {
return e.ErrorMessage
}
type client struct {
HTTP *http.Client
BaseURL *url.URL
APIKey string
}
func (c *client) Invoke(ctx context.Context, values *url.Values, dst Method) error {
requestValues := url.Values{}
if values != nil {
for k, v := range *values {
for _, vv := range v {
requestValues.Add(k, vv)
}
}
}
requestValues.Add("key", c.APIKey)
requestValues.Add("o", "JSON")
requestURL := *c.BaseURL
requestURL.Path = dst.Method()
requestURL.RawQuery = requestValues.Encode()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, requestURL.String(), nil)
if err != nil {
return err
}
res, err := c.HTTP.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode != 200 {
return fmt.Errorf("unexpected response status code %d", res.StatusCode)
}
b, err := io.ReadAll(res.Body)
if err != nil {
return err
}
var errorval struct {
Error Error `json:"error"`
}
if err := json.Unmarshal(b, &errorval); err != nil {
return err
}
if errorval.Error.ErrorMessage != "" {
return errorval.Error
}
return json.Unmarshal(b, dst)
}