-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdirectdecisions.go
More file actions
181 lines (153 loc) · 4.57 KB
/
directdecisions.go
File metadata and controls
181 lines (153 loc) · 4.57 KB
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
// Copyright (c) 2022, Direct Decisions Go client AUTHORS.
// All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package directdecisions
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"net/url"
"strings"
"sync"
)
const (
version = "0.1.0"
userAgent = "directdecisions-go/" + version
contentType = "application/json; charset=utf-8"
defaultBaseURL = "https://api.directdecisions.com/"
)
// Client manages communication with the Direct Decisions API.
type Client struct {
httpClient *http.Client // HTTP client must handle authentication implicitly.
service service // Reuse a single struct instead of allocating one for each service on the heap.
// rate contains the current rate limit for the client as determined
// by the most recent API call.
rate Rate
rateMu sync.RWMutex
// Services that API provides.
Votings *VotingsService
}
// ClientOptions holds optional parameters for the Client.
type ClientOptions struct {
HTTPClient *http.Client
BaseURL *url.URL
}
// NewClient constructs a new Client that uses API key authentication.
func NewClient(key string, o *ClientOptions) (c *Client) {
if o == nil {
o = new(ClientOptions)
}
authFunc := func(r *http.Request) {}
if key != "" {
authFunc = func(r *http.Request) {
r.Header.Set("Authorization", "Bearer "+key)
}
}
return newClient(httpClientWithTransport(o.HTTPClient, o.BaseURL, authFunc))
}
// newClient constructs a new *Client with the provided http Client, which
// should handle authentication implicitly, and sets all API services.
func newClient(httpClient *http.Client) (c *Client) {
c = &Client{httpClient: httpClient}
c.service.client = c
c.Votings = (*VotingsService)(&c.service)
return c
}
func httpClientWithTransport(c *http.Client, baseURL *url.URL, authFunc func(r *http.Request)) *http.Client {
if c == nil {
c = new(http.Client)
}
transport := c.Transport
if transport == nil {
transport = http.DefaultTransport
}
if baseURL == nil {
baseURL, _ = url.Parse(defaultBaseURL)
}
if !strings.HasSuffix(baseURL.Path, "/") {
baseURL.Path += "/"
}
c.Transport = roundTripperFunc(func(r *http.Request) (resp *http.Response, err error) {
r.Header.Set("User-Agent", userAgent)
authFunc(r)
u, err := baseURL.Parse(r.URL.String())
if err != nil {
return nil, err
}
r.URL = u
return transport.RoundTrip(r)
})
return c
}
// request handles the HTTP request response cycle. It JSON encodes the request
// body, creates an HTTP request with provided method on a path with required
// headers, sets current request rate information to the Client and decodes
// request body if the v argument is not nil and content type is
// application/json.
func (c *Client) request(ctx context.Context, method, path string, body, v interface{}) (err error) {
var bodyBuffer io.ReadWriter
if body != nil {
bodyBuffer = new(bytes.Buffer)
if err = encodeJSON(bodyBuffer, body); err != nil {
return err
}
}
req, err := http.NewRequest(method, path, bodyBuffer)
if err != nil {
return err
}
req = req.WithContext(ctx)
if body != nil {
req.Header.Set("Content-Type", contentType)
}
req.Header.Set("Accept", contentType)
r, err := c.httpClient.Do(req)
if err != nil {
return err
}
defer drain(r.Body)
c.setRate(r)
if err := responseErrorHandler(r); err != nil {
return err
}
if v != nil && strings.Contains(r.Header.Get("Content-Type"), "application/json") {
return json.NewDecoder(r.Body).Decode(&v)
}
return nil
}
// encodeJSON writes a JSON-encoded v object to the provided writer with
// SetEscapeHTML set to false.
func encodeJSON(w io.Writer, v interface{}) (err error) {
enc := json.NewEncoder(w)
enc.SetEscapeHTML(false)
return enc.Encode(v)
}
// drain discards all of the remaining data from the reader and closes it,
// asynchronously.
func drain(r io.ReadCloser) {
go func() {
// Panicking here does not put data in
// an inconsistent state.
defer func() {
_ = recover()
}()
_, _ = io.Copy(io.Discard, r)
r.Close()
}()
}
// service is the base type for all API service providing the Client instance
// for them to use.
type service struct {
client *Client
}
// roundTripperFunc type is an adapter to allow the use of ordinary functions as
// http.RoundTripper interfaces. If f is a function with the appropriate
// signature, roundTripperFunc(f) is a http.RoundTripper that calls f.
type roundTripperFunc func(*http.Request) (*http.Response, error)
// RoundTrip calls f(r).
func (f roundTripperFunc) RoundTrip(r *http.Request) (*http.Response, error) {
return f(r)
}