-
Notifications
You must be signed in to change notification settings - Fork 1
/
uploader.go
73 lines (60 loc) · 1.79 KB
/
uploader.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
package uploader
import (
"bytes"
"fmt"
"io"
"log"
gcs "cloud.google.com/go/storage"
opt "google.golang.org/api/option"
"github.com/minodisk/resizer/options"
"github.com/minodisk/resizer/storage"
"github.com/pkg/errors"
"golang.org/x/net/context"
)
const (
scope = gcs.ScopeFullControl
sixMonths = 60 * 60 * 24 * 30 * 6
)
type Uploader struct {
context context.Context
bucket *gcs.BucketHandle
bucketName string
}
// New はアップローダーを作成する。
func New(o *options.Options) (*Uploader, error) {
ctx := context.Background()
client, err := gcs.NewClient(ctx, opt.WithScopes(gcs.ScopeFullControl), opt.WithServiceAccountFile(o.ServiceAccount.Path))
if err != nil {
return nil, errors.Wrap(err, "can't create client for GCS")
}
return &Uploader{
context: ctx,
bucket: client.Bucket(o.Bucket),
bucketName: o.Bucket,
}, nil
}
func (u *Uploader) Upload(buf *bytes.Buffer, f storage.Image) (string, error) {
object := u.bucket.Object(f.Filename)
w := object.NewWriter(u.context)
written, err := io.Copy(w, buf)
if err != nil {
return "", errors.Wrap(err, "can't copy buffer to GCS object writer")
}
if err := w.Close(); err != nil {
return "", errors.Wrap(err, "can't close object writer")
}
log.Printf("Write %d bytes object '%s' in bucket '%s'\n", written, f.Filename, u.bucketName)
attrs, err := object.Update(u.context, gcs.ObjectAttrsToUpdate{
ContentType: f.ContentType,
CacheControl: fmt.Sprintf("max-age=%d", sixMonths),
})
if err != nil {
return "", errors.Wrap(err, "can't update object attributes")
}
log.Printf("Attributes: %+v\n", *attrs)
url := u.CreateURL(f.Filename)
return url, nil
}
func (u *Uploader) CreateURL(path string) string {
return fmt.Sprintf("https://%s.storage.googleapis.com/%s", u.bucketName, path)
}