-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
223 lines (187 loc) · 6.03 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
package bunnystorage
import (
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"net/url"
"time"
"github.com/minio/sha256-simd"
"github.com/go-resty/resty/v2"
"github.com/sirupsen/logrus"
"github.com/valyala/fasthttp"
)
type Client struct {
*fasthttp.Client
logger resty.Logger
password string
baseUrl url.URL
}
// Initialize a new bunnystorage-go client with default settings. Endpoint format is https://<region endpoint>/<Storage Zone Name> e.g. https://la.storage.bunnycdn.com/mystoragezone/
func NewClient(endpoint url.URL, password string) Client {
return Client{
&fasthttp.Client{
ReadTimeout: time.Second * 30,
WriteTimeout: time.Second * 30,
},
logrus.New(),
password,
endpoint,
}
}
// Add a custom logger. The logger has to implement the resty.Logger interface
func (c *Client) WithLogger(l resty.Logger) *Client {
c.logger = l
return c
}
func (c *Client) prepareRequest(path string) *fasthttp.Request {
req := fasthttp.AcquireRequest()
reqUrl := c.baseUrl.JoinPath(path)
req.Header.Add("AccessKey", c.password)
req.SetRequestURI(reqUrl.String())
return req
}
// Uploads a file to the relative path. generateChecksum controls if a checksum gets generated and attached to the upload request. Returns an error.
func (c *Client) Upload(path string, content []byte, generateChecksum bool) error {
req := c.prepareRequest(path)
defer fasthttp.ReleaseRequest(req)
req.Header.Add("Content-Type", "application/octet-stream")
req.Header.SetMethod(fasthttp.MethodPut)
req.SetBody(content)
resp := fasthttp.AcquireResponse()
defer fasthttp.ReleaseResponse(resp)
if generateChecksum {
checksum := sha256.New()
_, err := checksum.Write(content)
if err != nil {
return err
}
hex_checksum := hex.EncodeToString(checksum.Sum(nil))
req.Header.Add("Checksum", hex_checksum)
}
err := c.Do(req, resp)
c.logger.Debugf("Put Request Response: %v", resp)
if err != nil {
c.logger.Errorf("Put Request Failed: %v", err)
return err
}
if isHTTPError(resp.StatusCode()) {
return errors.New(string(resp.Header.StatusMessage()))
}
return nil
}
// Downloads a file from a path.
func (c *Client) Download(path string) ([]byte, error) {
req := c.prepareRequest(path)
defer fasthttp.ReleaseRequest(req)
req.Header.SetMethod(fasthttp.MethodGet)
resp := fasthttp.AcquireResponse()
defer fasthttp.ReleaseResponse(resp)
err := c.Do(req, resp)
c.logger.Debugf("Get Request Response: %v", resp)
if err != nil {
c.logger.Errorf("Get Request Failed: %v", err)
return nil, err
}
if isHTTPError(resp.StatusCode()) {
return nil, errors.New(string(resp.Header.StatusMessage()))
}
respBody := make([]byte, len(resp.Body()))
copy(respBody, resp.Body())
return respBody, nil
}
// Downloads a byte range of a file. Uses the semantics for HTTP range requests. If you want to avoid passing buffers directly for performance, use DownloadPartialWithReaderCloser
//
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Range_requests
func (c *Client) DownloadPartial(path string, rangeStart int64, rangeEnd int64) ([]byte, error) {
req := c.prepareRequest(path)
defer fasthttp.ReleaseRequest(req)
req.Header.SetMethod(fasthttp.MethodGet)
req.Header.Add("Range", fmt.Sprintf("bytes=%d-%d", rangeStart, rangeEnd))
resp := fasthttp.AcquireResponse()
defer fasthttp.ReleaseResponse(resp)
err := c.Do(req, resp)
c.logger.Debugf("Get Request Response: %v", resp)
if err != nil {
c.logger.Errorf("Get Request Failed: %v", err)
return nil, err
}
if isHTTPError(resp.StatusCode()) {
return nil, errors.New(string(resp.Header.StatusMessage()))
}
respBody := make([]byte, len(resp.Body()))
copy(respBody, resp.Body())
return respBody, nil
}
// Delete a file or a directory. If the path to delete is a directory, set the isPath flag to true
func (c *Client) Delete(path string, isPath bool) error {
if isPath {
path += "/" // The trailing slash is required to delete a directory
}
req := c.prepareRequest(path)
defer fasthttp.ReleaseRequest(req)
req.Header.SetMethod(fasthttp.MethodDelete)
resp := fasthttp.AcquireResponse()
defer fasthttp.ReleaseResponse(resp)
err := c.Do(req, resp)
c.logger.Debugf("Delete Request Response: %v", resp)
if err != nil {
c.logger.Errorf("Delete Request Failed: %v", err)
return err
}
if isHTTPError(resp.StatusCode()) {
return errors.New(string(resp.Header.StatusMessage()))
}
return nil
}
// Lists files from a directory.
func (c *Client) List(path string) ([]Object, error) {
req := c.prepareRequest(path + "/") // The trailing slash is neccessary, since without it the API will treat the requested directory as a file and returns an empty list
defer fasthttp.ReleaseRequest(req)
req.Header.SetMethod(fasthttp.MethodGet)
req.Header.Add("Accept", "application/json")
resp := fasthttp.AcquireResponse()
defer fasthttp.ReleaseResponse(resp)
err := c.Do(req, resp)
c.logger.Debugf("List Request Response: %v", resp)
if err != nil {
c.logger.Errorf("List Request Failed: %v", err)
return nil, err
}
if isHTTPError(resp.StatusCode()) {
return nil, errors.New(string(resp.Header.StatusMessage()))
}
objectList := make([]Object, 0)
err = json.Unmarshal(resp.Body(), &objectList)
if err != nil {
return nil, err
}
return objectList, nil
}
// Describes an Object. EXPERIMENTAL. The official Java SDK uses it, but the DESCRIBE HTTP method used is not officially documented.
func (c *Client) Describe(path string) (Object, error) {
object := Object{}
req := c.prepareRequest(path)
defer fasthttp.ReleaseRequest(req)
req.Header.SetMethod("DESCRIBE")
req.Header.Add("Accept", "application/json")
resp := fasthttp.AcquireResponse()
defer fasthttp.ReleaseResponse(resp)
err := c.Do(req, resp)
c.logger.Debugf("Describe Request Response: %v", resp)
if err != nil {
c.logger.Errorf("Describe Request Failed: %v", err)
return object, err
}
if isHTTPError(resp.StatusCode()) {
return object, errors.New(string(resp.Header.StatusMessage()))
}
err = json.Unmarshal(resp.Body(), &object)
if err != nil {
return object, err
}
return object, nil
}
func isHTTPError(c int) bool {
return c > 399
}