-
Notifications
You must be signed in to change notification settings - Fork 0
/
storing.go
72 lines (61 loc) · 1.38 KB
/
storing.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
package main
import (
"context"
"fmt"
"io"
"os"
"time"
"cloud.google.com/go/storage"
"google.golang.org/api/option"
)
type Store interface {
SetBucket(b string) Store
SetTimeout(t int) Store
SetCredentials(c []byte) Store
Upload(dst, src string) error
}
type Storing struct {
bucket string
timeout time.Duration
credentials []byte
}
func (s *Storing) SetBucket(b string) Store {
s.bucket = b
return s
}
func (s *Storing) SetTimeout(t int) Store {
s.timeout = time.Duration(t) * time.Second
return s
}
func (s *Storing) SetCredentials(c []byte) Store {
s.credentials = c
return s
}
func (s *Storing) Upload(dst, src string) error {
// Create clinet
ctx := context.Background()
client, err := storage.NewClient(ctx, option.WithCredentialsJSON(s.credentials))
if err != nil {
return fmt.Errorf("storage.NewClient: %v", err)
}
defer client.Close()
// Open local file
f, err := os.Open(src)
if err != nil {
return fmt.Errorf("os.Open: %v", err)
}
defer f.Close()
// Create writer and Upload
o := client.Bucket(s.bucket).Object(dst)
o = o.If(storage.Conditions{DoesNotExist: true})
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
wc := o.NewWriter(ctx)
if _, err = io.Copy(wc, f); err != nil {
return fmt.Errorf("io.Copy: %v", err)
}
if err := wc.Close(); err != nil {
return fmt.Errorf("Writer.Close: %v", err)
}
return nil
}