-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
120 lines (94 loc) · 2.45 KB
/
client.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
package employmenthero
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
)
type Client struct {
ClientID string
Secret string
RedirectURI string
APIBase string
Client HTTPClient
Token *TokenResponse
}
type TokenResponse struct {
RefreshToken string `json:"refresh_token"`
Token string `json:"access_token"`
Type string `json:"token_type"`
ExpiresIn int `json:"expires_in"`
}
type ErrorResponse struct {
Response *http.Response
}
type HTTPClient interface {
Do(req *http.Request) (*http.Response, error)
}
// NewClient returns a new Client struct
func NewClient(clientID string, secret string, refreshToken string, APIBase string) (*Client, error) {
if clientID == "" || secret == "" || APIBase == "" || refreshToken == "" {
return nil, errors.New("Client ID, Secret and APIBase are required to create a Client")
}
return &Client{
Client: &http.Client{},
ClientID: clientID,
Secret: secret,
Token: &TokenResponse{RefreshToken: refreshToken},
APIBase: APIBase,
}, nil
}
func (c *Client) GetAccessToken(ctx context.Context) (*TokenResponse, error) {
data := url.Values{}
data.Set("client_id", c.ClientID)
data.Set("client_secret", c.Secret)
data.Set("refresh_token", c.Token.RefreshToken)
data.Set("grant_type", "refresh_token")
buf := bytes.NewBuffer([]byte(data.Encode()))
req, err := http.NewRequestWithContext(ctx, "POST", fmt.Sprintf("%s%s", c.APIBase, "/oauth2/token"), buf)
if err != nil {
return &TokenResponse{}, err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
response := &TokenResponse{}
err = c.Send(req, response)
if response.Token != "" {
c.Token = response
}
return response, err
}
func (c *Client) Send(req *http.Request, v interface{}) error {
if v == nil {
return nil
}
var (
err error
resp *http.Response
)
req.Header.Set("Accept", "application/json")
if req.Header.Get("Content-Type") == "" {
req.Header.Set("Content-Type", "application/json")
}
resp, err = c.Client.Do(req)
if err != nil {
return err
}
defer func(Body io.ReadCloser) error {
return Body.Close()
}(resp.Body)
if resp.StatusCode < 200 || resp.StatusCode > 299 {
data, err := io.ReadAll(resp.Body)
if err == nil && len(data) > 0 {
return fmt.Errorf(string(data))
}
}
if n, e := v.(io.Writer); e {
_, err := io.Copy(n, resp.Body)
return err
}
return json.NewDecoder(resp.Body).Decode(v)
}