-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbasicauth.go
80 lines (65 loc) · 1.73 KB
/
basicauth.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
package vivawallet
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
// New creates a new viva client for the basic auth apis
func NewBasicAuth(merchantID string, apiKey string, demo bool) *BasicAuthClient {
return &BasicAuthClient{
Config: Config{
Demo: demo,
MerchantID: merchantID,
APIKey: apiKey,
},
Client: httpClient,
}
}
func (c BasicAuthClient) Get(uri string, v interface{}) error {
req := newRequest("GET", uri, nil)
body, reqErr := c.performReq(req)
if reqErr != nil {
return reqErr
}
return json.Unmarshal(body, v)
}
func (c BasicAuthClient) Post(uri string, reader *bytes.Reader, v interface{}) error {
req := newRequest("POST", uri, reader)
body, reqErr := c.performReq(req)
if reqErr != nil {
return reqErr
}
return json.Unmarshal(body, v)
}
func (c BasicAuthClient) Patch(uri string, reader *bytes.Reader) error {
req := newRequest("PATCH", uri, reader)
_, reqErr := c.performReq(req)
if reqErr != nil {
return reqErr
}
return nil
}
func (c BasicAuthClient) Delete(uri string, reader *bytes.Reader, v interface{}) error {
req := newRequest("DELETE", uri, reader)
body, reqErr := c.performReq(req)
if reqErr != nil {
return reqErr
}
return json.Unmarshal(body, v)
}
func (c BasicAuthClient) performReq(req *http.Request) ([]byte, error) {
req.Header.Add("Content-Type", "application/json")
req.SetBasicAuth(c.Config.MerchantID, c.Config.APIKey)
resp, httpErr := c.Client.Do(req)
if httpErr != nil {
return nil, fmt.Errorf("failed to perform request %s", httpErr)
}
defer resp.Body.Close()
body, bodyErr := io.ReadAll(resp.Body)
if resp.StatusCode != 200 {
return nil, fmt.Errorf("failed to perform request with status %d", resp.StatusCode)
}
return body, bodyErr
}