-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstorage.go
76 lines (62 loc) · 1.47 KB
/
storage.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
package imagegeneration
import (
"bufio"
"encoding/json"
"fmt"
"io"
"net/http"
"strconv"
)
type Bucket struct {
BucketID string
BaseURL string
APIKey string
}
type FileUploadOptions struct {
CacheControl string
ContentType string
Update bool
}
type FileResponse struct {
Key string `json:"key"`
}
func DefaultFileUploadOptions() FileUploadOptions {
return FileUploadOptions{
CacheControl: "3600",
ContentType: "text/plain;charset=UTF-8",
Update: false,
}
}
func (f *Bucket) Upload(path string, data io.Reader, opts FileUploadOptions) (string, error) {
body := bufio.NewReader(data)
_path := f.BucketID + "/" + path
client := &http.Client{}
var method string
if opts.Update {
method = http.MethodPut
} else {
method = http.MethodPost
}
reqURL := fmt.Sprintf("%s/storage/v1/object/%s", f.BaseURL, _path)
req, err := http.NewRequest(method, reqURL, body)
if err != nil {
return "", err
}
req.Header.Set("Authorization", "Bearer "+f.APIKey)
req.Header.Set("cache-control", opts.CacheControl)
req.Header.Set("content-type", opts.ContentType)
req.Header.Set("x-upsert", strconv.FormatBool(opts.Update))
res, err := client.Do(req)
if err != nil {
return "", err
}
resBody, err := io.ReadAll(res.Body)
if err != nil {
return "", err
}
var response FileResponse
if err = json.Unmarshal(resBody, &response); err != nil {
return "", err
}
return fmt.Sprintf("%s/storage/v1/object/public/%s", f.BaseURL, response.Key), nil
}