-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
131 lines (109 loc) · 2.2 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
package redmine
import (
"fmt"
"io"
"net/http"
"net/url"
"path"
)
var (
listLimit int
)
type Option func(*Options)
type Options struct {
debugMode bool
httpClient *http.Client
listLimit int
switchUser string
}
func OptionDebugMode(enabled bool) Option {
return func(args *Options) {
args.debugMode = enabled
}
}
func OptionHTTPClient(client *http.Client) Option {
return func(args *Options) {
args.httpClient = client
}
}
func OptionListLimit(limit int) Option {
return func(args *Options) {
args.listLimit = limit
}
}
func OptionSwitchUser(user string) Option {
return func(args *Options) {
args.switchUser = user
}
}
type Client struct {
baseURL url.URL
apiKey string
options *Options
}
func NewClient(baseURL, apiKey string, opts ...Option) (*Client, error) {
o := &Options{
debugMode: false,
httpClient: &http.Client{},
listLimit: 100,
switchUser: "",
}
for _, setter := range opts {
setter(o)
}
listLimit = o.listLimit
u, err := url.Parse(baseURL)
if err != nil {
return nil, fmt.Errorf("invalid baseURL: %s", err.Error())
}
c := &Client{
baseURL: *u,
apiKey: apiKey,
options: o,
}
if err := c.HealthCheck(); err != nil {
return nil, err
}
return c, nil
}
func (c *Client) getRequest(endpoint string, query url.Values) ([]byte, error) {
u := c.baseURL
u.Path = path.Join(u.Path, endpoint)
if query != nil {
u.RawQuery = query.Encode()
}
req, err := http.NewRequest(http.MethodGet, u.String(), nil)
if err != nil {
return nil, err
}
req.Header.Set("X-Redmine-API-Key", c.apiKey)
if u := c.options.switchUser; u != "" {
req.Header.Set("X-Redmine-Switch-User", u)
}
if c.options.debugMode {
fmt.Print(req.URL.String())
}
resp, err := c.options.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if c.options.debugMode {
fmt.Print(" --> ", resp.Status, "\n")
}
switch resp.StatusCode {
case http.StatusOK:
// OK
default:
return nil, fmt.Errorf("request failed: StatusCode=%d", resp.StatusCode)
}
return body, nil
}
func (c *Client) HealthCheck() error {
_, err := c.getRequest("/my/account.json", url.Values{})
return err
}