-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathclient.go
227 lines (189 loc) · 5.19 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
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
package tapd
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/url"
"strings"
"github.com/google/go-querystring/query"
)
const (
defaultBaseURL = "https://api.tapd.cn/"
defaultUserAgent = "go-tapd"
)
var defaultHTTPClient = NewRetryableHTTPClient()
type Client struct {
// baseURL for API requests.
baseURL *url.URL
// username, password for basic authentication.
username, password string
// userAgent used for HTTP requests
userAgent string
// httpClient is the HTTP client used to communicate with the API.
httpClient *http.Client
// services used for talking to different parts of the Tapd API.
StoryService *StoryService
BugService *BugService
IterationService *IterationService
TaskService *TaskService
CommentService *CommentService
ReportService *ReportService
AttachmentService *AttachmentService
TimesheetService *TimesheetService
WorkspaceService *WorkspaceService
LabelService *LabelService
MeasureService *MeasureService
UserService *UserService
WorkflowService *WorkflowService
SettingService *SettingService
}
// NewClient returns a new Tapd API client.
// Alias for NewBasicAuthClient.
func NewClient(username, password string, opts ...ClientOption) (*Client, error) {
return NewBasicAuthClient(username, password, opts...)
}
// NewBasicAuthClient returns a new Tapd API client with basic authentication.
func NewBasicAuthClient(username, password string, opts ...ClientOption) (*Client, error) {
return newClient(append(opts,
WithBasicAuth(username, password))...)
}
// newClient returns a new Tapd API client.
func newClient(opts ...ClientOption) (*Client, error) {
c := &Client{
userAgent: defaultUserAgent,
httpClient: defaultHTTPClient,
}
for _, opt := range opts {
if err := opt(c); err != nil {
return nil, err
}
}
// setup
if err := c.setup(); err != nil {
return nil, err
}
// services
c.StoryService = &StoryService{client: c}
c.BugService = &BugService{client: c}
c.IterationService = &IterationService{client: c}
c.TaskService = &TaskService{client: c}
c.CommentService = &CommentService{client: c}
c.ReportService = &ReportService{client: c}
c.AttachmentService = &AttachmentService{client: c}
c.TimesheetService = &TimesheetService{client: c}
c.WorkspaceService = &WorkspaceService{client: c}
c.LabelService = &LabelService{client: c}
c.MeasureService = &MeasureService{client: c}
c.UserService = &UserService{client: c}
c.WorkflowService = &WorkflowService{client: c}
c.SettingService = &SettingService{client: c}
return c, nil
}
// setup sets up the client for API requests.
func (c *Client) setup() error {
if c.baseURL == nil {
if err := c.setBaseURL(defaultBaseURL); err != nil {
return err
}
}
return nil
}
// setBaseURL sets the base URL for API requests to a custom endpoint.
func (c *Client) setBaseURL(urlStr string) error {
if !strings.HasSuffix(urlStr, "/") {
urlStr += "/"
}
baseURL, err := url.Parse(urlStr)
if err != nil {
return err
}
c.baseURL = baseURL
return nil
}
func (c *Client) NewRequest(ctx context.Context, method, path string, data any, opts []RequestOption) (*http.Request, error) { //nolint:lll
u := *c.baseURL
unescaped, err := url.PathUnescape(path)
if err != nil {
return nil, err
}
// Set the encoded path data
u.RawPath = c.baseURL.Path + path
u.Path = c.baseURL.Path + unescaped
// Create a request specific headers map.
reqHeaders := make(http.Header)
reqHeaders.Set("Accept", "application/json")
if c.userAgent != "" {
reqHeaders.Set("User-Agent", c.userAgent)
}
var body io.Reader
switch {
case method == http.MethodPatch || method == http.MethodPost || method == http.MethodPut:
reqHeaders.Set("Content-Type", "application/json")
if data != nil {
b, err := json.Marshal(data)
if err != nil {
return nil, err
}
body = io.NopCloser(bytes.NewReader(b))
}
case data != nil:
q, err := query.Values(data)
if err != nil {
return nil, err
}
u.RawQuery = q.Encode()
}
req, err := http.NewRequestWithContext(ctx, method, u.String(), body)
if err != nil {
return nil, err
}
// basic auth
if c.username != "" && c.password != "" {
req.SetBasicAuth(c.username, c.password)
}
// Set the request specific headers.
for k, v := range reqHeaders {
req.Header[k] = v
}
// Apply request options
for _, opt := range opts {
if err := opt(req); err != nil {
return nil, err
}
}
return req, nil
}
func (c *Client) Do(req *http.Request, v any) (*Response, error) {
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close() // nolint:errcheck
defer io.Copy(io.Discard, resp.Body) // nolint:errcheck
// decode response body
var rawBody RawBody
if err := json.NewDecoder(resp.Body).Decode(&rawBody); err != nil {
return nil, err
}
// debug mode
// body, _ := json.Marshal(rawBody)
// fmt.Println(string(body))
// spew.Dump(rawBody)
// check status
if rawBody.Status != 1 {
return nil, &ErrorResponse{
response: resp,
rawBody: &rawBody,
err: errors.New(rawBody.Info),
}
}
if v != nil {
if err := json.Unmarshal(rawBody.Data, v); err != nil {
return nil, err
}
}
return newResponse(resp), err
}