-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathclient.go
More file actions
262 lines (214 loc) · 6.88 KB
/
client.go
File metadata and controls
262 lines (214 loc) · 6.88 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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
package omise
import (
"bytes"
"context"
"encoding/json"
"fmt"
"go/build"
"io"
"net/http"
"strings"
"github.com/omise/omise-go/internal"
)
// Library version to include in user agent
var libraryVersion = "1.7.1"
// Client helps you configure and perform HTTP operations against Omise's REST API. It
// should be used with operation structures from the operations subpackage.
type Client struct {
*http.Client
debug bool
pkey string
skey string
// Overrides
Endpoints map[internal.Endpoint]string
// configuration
GoVersion string
customHeaders map[string]string
ctx context.Context
userAgent string
}
// NewClient creates and returns a Client with the given public key and secret key. Signs
// in to http://omise.co and visit https://dashboard.omise.co/test/dashboard to obtain
// your test (or live) keys.
func NewClient(pkey, skey string) (*Client, error) {
if err := validateKeys(pkey, skey); err != nil {
return nil, err
}
client := &Client{
Client: &http.Client{Transport: transport},
debug: false,
pkey: pkey,
skey: skey,
Endpoints: map[internal.Endpoint]string{},
}
if len(build.Default.ReleaseTags) > 0 {
client.GoVersion = build.Default.ReleaseTags[len(build.Default.ReleaseTags)-1]
}
return client, nil
}
// WithCustomHeaders lets us add headers to request. This should be called before calling Do() method
func (c *Client) WithCustomHeaders(headers map[string]string) {
if headers != nil {
c.customHeaders = headers
}
}
// WithContext By setting context, http request will use `NewRequestWithContext` which support to include tracing on same trace ID.
func (c *Client) WithContext(ctx context.Context) {
if ctx != nil {
c.ctx = ctx
}
}
// WithUserAgent feature allows us to append additional userAgent information to the original user agent.
func (c *Client) WithUserAgent(userAgent string) {
c.userAgent = userAgent
}
// If set to true then library will print the response of all the endpoints.
func (c *Client) SetDebug(debug bool) {
c.debug = debug
}
// Request creates a new *http.Request that should performs the supplied Operation. Most
// people should use the Do method instead.
func (c *Client) Request(operation internal.Operation) (req *http.Request, err error) {
req, err = c.buildJSONRequest(operation)
if err != nil {
return nil, err
}
err = c.setRequestHeaders(req, operation.Describe())
if err != nil {
return nil, err
}
return req, nil
}
func (c *Client) buildJSONRequest(operation internal.Operation) (*http.Request, error) {
desc := operation.Describe()
b, err := json.Marshal(operation)
if err != nil {
return nil, err
}
body := bytes.NewReader(b)
endpoint := string(desc.Endpoint)
if ep, ok := c.Endpoints[desc.Endpoint]; ok {
endpoint = ep
}
req, err := http.NewRequest(desc.Method, endpoint+desc.Path, body)
if c.ctx != nil {
req = req.WithContext(c.ctx)
}
return req, err
}
func (c *Client) setRequestHeaders(req *http.Request, desc *internal.Description) error {
return c.setRequestHeadersWithKeys(req, desc, c.pkey, c.skey)
}
func (c *Client) setRequestHeadersWithKeys(req *http.Request, desc *internal.Description, pkey, skey string) error {
ua := c.userAgent
ua += " OmiseGo/" + libraryVersion
if c.GoVersion != "" {
ua += " Go/" + c.GoVersion
}
if desc.ContentType != "" {
req.Header.Add("Content-Type", desc.ContentType)
}
req.Header.Add("User-Agent", strings.TrimSpace(ua))
req.Header.Add("Omise-Version", internal.Version)
// setting custom headers passed from the caller
for k, v := range c.customHeaders {
req.Header.Set(k, v)
}
switch desc.KeyKind() {
case "public":
req.SetBasicAuth(pkey, "")
case "secret":
req.SetBasicAuth(skey, "")
default:
return ErrInternal("unrecognized endpoint:" + desc.Endpoint)
}
return nil
}
func (c *Client) requestWithKeys(operation internal.Operation, pkey, skey string) (req *http.Request, err error) {
req, err = c.buildJSONRequest(operation)
if err != nil {
return nil, err
}
err = c.setRequestHeadersWithKeys(req, operation.Describe(), pkey, skey)
if err != nil {
return nil, err
}
return req, nil
}
// Do performs the supplied operation against Omise's REST API and unmarshal the response
// into the given result parameter. Results are usually basic objects or a list that
// corresponds to the operations being done.
//
// If the operation is successful, result should contains the response data. Otherwise a
// non-nil error should be returned. Error maybe of the omise-go.Error struct type, in
// which case you can further inspect the Code and Message field for more information.
func (c *Client) Do(result interface{}, operation internal.Operation) error {
req, err := c.Request(operation)
if err != nil {
return err
}
return c.doWithRequest(result, req)
}
// DoWithKeys performs the supplied operation using the provided pkey/skey pair without
// mutating the client. It is useful for multi-tenant scenarios where different
// credentials are needed per request while still reusing the underlying http.Client.
// Concurrency: DoWithKeys is intended to be called from multiple goroutines sharing
// the same Client instance. The Client's configuration (such as context, custom
// headers, user agent, and endpoint settings) must be treated as immutable once the
// Client is used concurrently. In particular, methods like WithCustomHeaders,
// WithContext, and other configuration-mutating helpers must not be called while the
// Client is in concurrent use, as doing so may cause data races and undefined
// behavior. Configure the Client fully before sharing it between goroutines or create
// separate Client instances per tenant as needed.
func (c *Client) DoWithKeys(result interface{}, pkey, skey string, operation internal.Operation) error {
if err := validateKeys(pkey, skey); err != nil {
return err
}
req, err := c.requestWithKeys(operation, pkey, skey)
if err != nil {
return err
}
return c.doWithRequest(result, req)
}
func validateKeys(pkey, skey string) error {
switch {
case pkey == "" && skey == "":
return ErrInvalidKey
case pkey != "" && !strings.HasPrefix(pkey, "pkey_"):
return ErrInvalidKey
case skey != "" && !strings.HasPrefix(skey, "skey_"):
return ErrInvalidKey
}
return nil
}
func (c *Client) doWithRequest(result interface{}, req *http.Request) error {
// response
resp, err := c.Client.Do(req)
if resp != nil {
defer resp.Body.Close()
}
if err != nil {
return err
}
buffer, err := io.ReadAll(resp.Body)
if err != nil {
return &ErrTransport{err, buffer}
}
switch {
case resp.StatusCode != 200:
err := &Error{StatusCode: resp.StatusCode}
if err := json.Unmarshal(buffer, err); err != nil {
return &ErrTransport{err, buffer}
}
return err
} // status == 200 && e == nil
if c.debug {
fmt.Println("resp:", resp.StatusCode, string(buffer))
}
if result != nil {
if err := json.Unmarshal(buffer, result); err != nil {
return &ErrTransport{err, buffer}
}
}
return nil
}