-
Notifications
You must be signed in to change notification settings - Fork 0
/
storage.go
98 lines (70 loc) · 1.7 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package main
import (
"bytes"
"context"
"github.com/patrickmn/go-cache"
"io/ioutil"
"log"
"net/url"
"time"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
)
var minioClient *minio.Client
var ctx context.Context
var c *cache.Cache
func storageInit(endpoint string, accessKey string, secretKey string) {
var err error
ctx = context.Background()
c = cache.New(time.Hour, 15*time.Minute)
minioClient, err = minio.New(endpoint, &minio.Options{
Creds: credentials.NewStaticV4(accessKey, secretKey, ""),
Secure: false,
})
if err != nil {
log.Fatalln(err)
}
log.Println("Minio client created.")
}
func cleanStorageCache() {
c.DeleteExpired()
}
func uploadImage(name string, data []byte) bool {
reader := bytes.NewReader(data)
_, err := minioClient.PutObject(ctx, "photos", name, reader, int64(len(data)), minio.PutObjectOptions{})
if err != nil {
return false
}
return true
}
func fetchImage(name string) ([]byte, error) {
result, err := minioClient.GetObject(ctx, "photos", name, minio.GetObjectOptions{})
defer result.Close()
if err != nil {
return nil, err
}
data, err := ioutil.ReadAll(result)
if err != nil {
return nil, err
}
return data, nil
}
func fetchImageUrl(name string) (*url.URL, error) {
cached, found := c.Get(name)
if found {
return cached.(*url.URL), nil
}
result, err := minioClient.PresignedGetObject(ctx, "photos", name, time.Second * 60 * 60, nil)
if err != nil {
return nil, err
}
c.Set(name, result, cache.DefaultExpiration)
return result, nil
}
func deleteImage(name string) error {
err := minioClient.RemoveObject(ctx, "photos", name, minio.RemoveObjectOptions{})
if err != nil {
return err
}
return nil
}