-
Notifications
You must be signed in to change notification settings - Fork 2
/
client.go
220 lines (172 loc) · 5.13 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
package bunnystorage
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"path/filepath"
"strings"
"git.sr.ht/~jamesponddotco/xstd-go/xerrors"
"git.sr.ht/~jamesponddotco/xstd-go/xnet/xhttp"
"git.sr.ht/~jamesponddotco/xstd-go/xstrings"
)
const (
// ErrConfigRequired is returned when a Client is created without a Config.
ErrConfigRequired xerrors.Error = "config is required"
)
type (
// Client is the LanguageTool API client.
Client struct {
// httpc is the underlying HTTP client used by the API client.
httpc *http.Client
// cfg specifies the configuration used by the API client.
cfg *Config
}
)
// NewClient returns a new bunny.net Edge Storage API client.
func NewClient(cfg *Config) (*Client, error) {
if cfg == nil {
return nil, ErrConfigRequired
}
cfg.init()
if err := cfg.validate(); err != nil {
return nil, err
}
retryPolicy := &xhttp.RetryPolicy{
IsRetryable: xhttp.DefaultIsRetryable,
MaxRetries: cfg.MaxRetries,
MinRetryDelay: xhttp.DefaultMinRetryDelay,
MaxRetryDelay: xhttp.DefaultMaxRetryDelay,
}
return &Client{
httpc: xhttp.NewRetryingClient(cfg.Timeout, retryPolicy, cfg.Logger),
cfg: cfg,
}, nil
}
// List lists the files in the storage zone.
func (c *Client) List(ctx context.Context, path string) ([]*Object, *Response, error) {
path = strings.TrimPrefix(path, "/")
uri := xstrings.JoinWithSeparator("/", c.cfg.Endpoint.String(), c.cfg.StorageZone, path+"/")
headers := map[string]string{
"Accept": "application/json",
"AccessKey": c.cfg.AccessKey(OperationRead),
}
req, err := c.request(ctx, http.MethodGet, uri, headers, http.NoBody)
if err != nil {
return nil, nil, fmt.Errorf("%w", err)
}
resp, err := c.do(ctx, req)
if err != nil {
return nil, nil, fmt.Errorf("%w", err)
}
var files []*Object
if err := json.Unmarshal(resp.Body, &files); err != nil {
return nil, nil, fmt.Errorf("%w", err)
}
return files, resp, nil
}
// Download downloads a file from the storage zone.
func (c *Client) Download(ctx context.Context, path, filename string) ([]byte, *Response, error) {
path = strings.TrimPrefix(path, "/")
filename = filepath.Base(filename)
uri := xstrings.JoinWithSeparator("/", c.cfg.Endpoint.String(), c.cfg.StorageZone, path, filename)
headers := map[string]string{
"Accept": "*/*",
"AccessKey": c.cfg.AccessKey(OperationRead),
}
req, err := c.request(ctx, http.MethodGet, uri, headers, http.NoBody)
if err != nil {
return nil, nil, fmt.Errorf("%w", err)
}
resp, err := c.do(ctx, req)
if err != nil {
return nil, nil, fmt.Errorf("%w", err)
}
return resp.Body, resp, nil
}
// Upload uploads a file to the storage zone.
func (c *Client) Upload(ctx context.Context, path, filename, checksum string, body io.Reader) (*Response, error) {
path = strings.TrimPrefix(path, "/")
uri := xstrings.JoinWithSeparator("/", c.cfg.Endpoint.String(), c.cfg.StorageZone, path, filename)
headers := map[string]string{
"AccessKey": c.cfg.AccessKey(OperationWrite),
}
if checksum != "" {
headers["Checksum"] = strings.ToUpper(checksum)
}
req, err := c.request(ctx, http.MethodPut, uri, headers, body)
if err != nil {
return nil, fmt.Errorf("%w", err)
}
resp, err := c.do(ctx, req)
if err != nil {
return nil, fmt.Errorf("%w", err)
}
return resp, nil
}
// Delete deletes a file from the storage zone.
func (c *Client) Delete(ctx context.Context, path, filename string) (*Response, error) {
path = strings.TrimPrefix(path, "/")
filename = filepath.Base(filename)
uri := xstrings.JoinWithSeparator("/", c.cfg.Endpoint.String(), c.cfg.StorageZone, path, filename)
headers := map[string]string{
"AccessKey": c.cfg.AccessKey(OperationWrite),
}
req, err := c.request(ctx, http.MethodDelete, uri, headers, http.NoBody)
if err != nil {
return nil, fmt.Errorf("%w", err)
}
resp, err := c.do(ctx, req)
if err != nil {
return nil, fmt.Errorf("%w", err)
}
return resp, nil
}
// do performs an HTTP request using the underlying HTTP client.
func (c *Client) do(_ context.Context, req *http.Request) (*Response, error) {
ret, err := c.httpc.Do(req)
if err != nil {
return nil, fmt.Errorf("%w", err)
}
defer func() {
if err = xhttp.DrainResponseBody(ret); err != nil {
log.Fatal(err)
}
}()
var buffer *bytes.Buffer
if ret.ContentLength > 0 {
buffer = bytes.NewBuffer(make([]byte, 0, ret.ContentLength))
} else {
buffer = bytes.NewBuffer(make([]byte, 0))
}
_, err = io.Copy(buffer, ret.Body)
if err != nil {
return nil, fmt.Errorf("%w", err)
}
response := &Response{
Header: ret.Header.Clone(),
Body: buffer.Bytes(),
Status: ret.StatusCode,
}
return response, nil
}
// request is a convenience function for creating an HTTP request.
func (c *Client) request(ctx context.Context, method, uri string, headers map[string]string, body io.Reader) (*http.Request, error) {
if headers == nil {
headers = map[string]string{}
}
if _, ok := headers["User-Agent"]; !ok {
headers["User-Agent"] = c.cfg.UserAgent
}
req, err := http.NewRequestWithContext(ctx, method, uri, body)
if err != nil {
return nil, fmt.Errorf("%w", err)
}
for k, v := range headers {
req.Header.Set(k, v)
}
return req, nil
}