-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
168 lines (147 loc) · 3.76 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
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
package goreydenx
import (
"errors"
"io"
"net/http"
"net/url"
"strings"
"time"
"github.com/bytedance/sonic"
"github.com/golang-module/carbon"
)
type JSONMarshal func(v interface{}) ([]byte, error)
type JSONUnmarshal func(data []byte, v interface{}) error
type Token struct {
AccessToken string `json:"access_token"`
ExpiresIn string `json:"expires_in"`
TokenType string `json:"token_type,omitempty"`
}
func (t *Token) IsValid() bool {
if t.AccessToken == "" || t.ExpiresIn == "" {
return false
}
now := carbon.Now(carbon.UTC)
return carbon.Parse(t.ExpiresIn, carbon.UTC).Compare(">=", now)
}
type Client struct {
*http.Client
JSONEncoder JSONMarshal
JSONDecoder JSONUnmarshal
Token *Token
BaseUrl string
userName string
password string
}
func (c *Client) isAuthenticated() bool {
if c.Token == nil {
return false
}
return c.Token.IsValid()
}
func (c *Client) Auth() *Client {
if c.isAuthenticated() {
return c
}
if c.Token == nil {
form := url.Values{}
form.Add("username", c.userName)
form.Add("password", c.password)
req, _ := http.NewRequest(http.MethodPost, c.BaseUrl+"/token/", strings.NewReader(form.Encode()))
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
resp, err := c.Do(req)
if err == nil && resp.StatusCode == 200 {
body, err := io.ReadAll(resp.Body)
if err == nil {
t := Token{}
err := c.JSONDecoder(body, &t)
if err == nil {
c.Token = &t
}
}
}
} else {
if !c.Token.IsValid() {
token, _ := c.RefreshToken()
c.Token = token
}
}
return c
}
func (c *Client) RefreshToken() (*Token, error) {
resp, err := request(c, http.MethodPatch, "/token/refresh/", nil)
if err == nil {
token := Token{}
if decodeError := c.JSONDecoder(resp, &token); decodeError != nil {
return nil, decodeError
}
return &token, nil
}
return nil, err
}
func request(client *Client, method string, path string, payload io.Reader) ([]byte, error) {
if !client.isAuthenticated() {
return nil, errors.New("unauthorized")
}
req, _ := http.NewRequest(method, client.BaseUrl+path, payload)
req.Header.Set("Accept", "application/json")
if client.Token != nil && client.Token.IsValid() && path != "/token/" {
req.Header.Set("Authorization", "Bearer "+client.Token.AccessToken)
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
switch resp.StatusCode {
case http.StatusBadRequest:
return nil, errors.New("bad request")
case http.StatusTooManyRequests:
return nil, errors.New("too many requests")
case http.StatusNotFound:
return nil, errors.New("not found")
case http.StatusUnauthorized:
return nil, errors.New("unauthorized")
case http.StatusOK:
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return body, err
default:
return nil, errors.New("unknown error")
}
}
func (c *Client) Get(path string) ([]byte, error) {
return request(c, http.MethodGet, path, nil)
}
func (c *Client) Post(path string, payload io.Reader) ([]byte, error) {
return request(c, http.MethodPost, path, payload)
}
func (c *Client) Patch(path string, payload io.Reader) ([]byte, error) {
return request(c, http.MethodPatch, path, payload)
}
// NewClient Make Client instance
func NewClient(userName string, password string) *Client {
return &Client{
Client: &http.Client{
Timeout: time.Second * 5,
},
JSONEncoder: sonic.Marshal,
JSONDecoder: sonic.Unmarshal,
BaseUrl: BaseUrl,
userName: userName,
password: password,
}
}
// NewClientWithToken Make Client instance
func NewClientWithToken(token *Token) *Client {
return &Client{
Client: &http.Client{
Timeout: time.Second * 5,
},
JSONEncoder: sonic.Marshal,
JSONDecoder: sonic.Unmarshal,
BaseUrl: BaseUrl,
Token: token,
}
}