-
-
Notifications
You must be signed in to change notification settings - Fork 178
/
client.go
259 lines (214 loc) · 6.33 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
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
package jira
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net"
"net/http"
"net/http/httputil"
"strings"
"time"
)
const (
// RFC3339 is jira datetime format.
RFC3339 = "2006-01-02T15:04:05-0700"
// InstallationTypeCloud represents Jira cloud server.
InstallationTypeCloud = "Cloud"
// InstallationTypeLocal represents on-premise Jira servers.
InstallationTypeLocal = "Local"
baseURLv3 = "/rest/api/3"
baseURLv2 = "/rest/api/2"
baseURLv1 = "/rest/agile/1.0"
apiVersion2 = "v2"
apiVersion3 = "v3"
)
var (
// ErrNoResult denotes no results.
ErrNoResult = fmt.Errorf("jira: no result")
// ErrEmptyResponse denotes empty response from the server.
ErrEmptyResponse = fmt.Errorf("jira: empty response from server")
)
// ErrUnexpectedResponse denotes response code other than the expected one.
type ErrUnexpectedResponse struct {
Body Errors
Status string
StatusCode int
}
func (e *ErrUnexpectedResponse) Error() string {
return e.Body.String()
}
// ErrMultipleFailed represents a grouped error, usually when
// multiple request fails when running them in a loop.
type ErrMultipleFailed struct {
Msg string
}
func (e *ErrMultipleFailed) Error() string {
return e.Msg
}
// Errors is a jira error type.
type Errors struct {
Errors map[string]string
ErrorMessages []string
WarningMessages []string
}
func (e Errors) String() string {
var out strings.Builder
if len(e.ErrorMessages) > 0 || len(e.Errors) > 0 {
out.WriteString("\nError:\n")
for _, v := range e.ErrorMessages {
out.WriteString(fmt.Sprintf(" - %s\n", v))
}
for k, v := range e.Errors {
out.WriteString(fmt.Sprintf(" - %s: %s\n", k, v))
}
}
if len(e.WarningMessages) > 0 {
out.WriteString("\nWarning:\n")
for _, v := range e.WarningMessages {
out.WriteString(fmt.Sprintf(" - %s\n", v))
}
}
return out.String()
}
// Header is a key, value pair for request headers.
type Header map[string]string
// Config is a jira config.
type Config struct {
Server string
Login string
APIToken string
Debug bool
}
// Client is a jira client.
type Client struct {
transport http.RoundTripper
server string
login string
token string
timeout time.Duration
debug bool
}
// ClientFunc decorates option for client.
type ClientFunc func(*Client)
// NewClient instantiates new jira client.
func NewClient(c Config, opts ...ClientFunc) *Client {
client := Client{
server: strings.TrimSuffix(c.Server, "/"),
login: c.Login,
token: c.APIToken,
debug: c.Debug,
}
client.transport = &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: client.timeout,
}).DialContext,
}
for _, opt := range opts {
opt(&client)
}
return &client
}
// WithTimeout is a functional opt to attach timeout to the client.
func WithTimeout(to time.Duration) ClientFunc {
return func(c *Client) {
c.timeout = to
}
}
// Get sends GET request to v3 version of the jira api.
func (c *Client) Get(ctx context.Context, path string, headers Header) (*http.Response, error) {
return c.request(ctx, http.MethodGet, c.server+baseURLv3+path, nil, headers)
}
// GetV2 sends GET request to v2 version of the jira api.
func (c *Client) GetV2(ctx context.Context, path string, headers Header) (*http.Response, error) {
return c.request(ctx, http.MethodGet, c.server+baseURLv2+path, nil, headers)
}
// GetV1 sends get request to v1 version of the jira api.
func (c *Client) GetV1(ctx context.Context, path string, headers Header) (*http.Response, error) {
return c.request(ctx, http.MethodGet, c.server+baseURLv1+path, nil, headers)
}
// Post sends POST request to v3 version of the jira api.
func (c *Client) Post(ctx context.Context, path string, body []byte, headers Header) (*http.Response, error) {
res, err := c.request(ctx, http.MethodPost, c.server+baseURLv3+path, body, headers)
if err != nil {
return res, err
}
return res, err
}
// PostV2 sends POST request to v2 version of the jira api.
func (c *Client) PostV2(ctx context.Context, path string, body []byte, headers Header) (*http.Response, error) {
res, err := c.request(ctx, http.MethodPost, c.server+baseURLv2+path, body, headers)
if err != nil {
return res, err
}
return res, err
}
// PostV1 sends POST request to v1 version of the jira api.
func (c *Client) PostV1(ctx context.Context, path string, body []byte, headers Header) (*http.Response, error) {
res, err := c.request(ctx, http.MethodPost, c.server+baseURLv1+path, body, headers)
if err != nil {
return res, err
}
return res, err
}
// Put sends PUT request to v3 version of the jira api.
func (c *Client) Put(ctx context.Context, path string, body []byte, headers Header) (*http.Response, error) {
res, err := c.request(ctx, http.MethodPut, c.server+baseURLv3+path, body, headers)
if err != nil {
return res, err
}
return res, err
}
// PutV2 sends PUT request to v2 version of the jira api.
func (c *Client) PutV2(ctx context.Context, path string, body []byte, headers Header) (*http.Response, error) {
res, err := c.request(ctx, http.MethodPut, c.server+baseURLv2+path, body, headers)
if err != nil {
return res, err
}
return res, err
}
func (c *Client) request(ctx context.Context, method, endpoint string, body []byte, headers Header) (*http.Response, error) {
var (
req *http.Request
res *http.Response
err error
)
req, err = http.NewRequest(method, endpoint, bytes.NewReader(body))
if err != nil {
return nil, err
}
defer func() {
if c.debug {
dump(req, res)
}
}()
for k, v := range headers {
req.Header.Set(k, v)
}
req.SetBasicAuth(c.login, c.token)
res, err = c.transport.RoundTrip(req.WithContext(ctx))
return res, err
}
func dump(req *http.Request, res *http.Response) {
reqDump, _ := httputil.DumpRequest(req, true)
respDump, _ := httputil.DumpResponse(res, false)
prettyPrintDump("Request Details", reqDump)
prettyPrintDump("Response Details", respDump)
}
func prettyPrintDump(heading string, data []byte) {
const separatorWidth = 60
fmt.Printf("\n\n%s", strings.ToUpper(heading))
fmt.Printf("\n%s\n\n", strings.Repeat("-", separatorWidth))
fmt.Print(string(data))
}
func formatUnexpectedResponse(res *http.Response) *ErrUnexpectedResponse {
var b Errors
// We don't care about decoding error here.
_ = json.NewDecoder(res.Body).Decode(&b)
return &ErrUnexpectedResponse{
Body: b,
Status: res.Status,
StatusCode: res.StatusCode,
}
}