-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
47 lines (40 loc) · 1.14 KB
/
main.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
package main
import (
"context"
"fmt"
"io"
"os"
"time"
"cloud.google.com/go/storage"
"google.golang.org/api/option"
)
func main() {
bucket := os.Getenv("BUCKET_NAME")
localObjectPath := os.Getenv("LOCAL_OBJECT_PATH")
remoteObjectPath := os.Getenv("REMOTE_OBJECT_PATH")
googleApplicationCredentials := os.Getenv("GOOGLE_APPLICATION_CREDENTIALS")
opts := option.WithCredentialsFile(googleApplicationCredentials)
ctx := context.Background()
client, err := storage.NewClient(ctx, opts)
if err != nil {
fmt.Fprintf(os.Stderr, "storage.NewClient: %v", err)
}
defer client.Close()
// Open local file.
f, err := os.Open(localObjectPath)
if err != nil {
fmt.Fprintf(os.Stderr, "os.Open: %v", err)
}
defer f.Close()
ctx, cancel := context.WithTimeout(ctx, time.Second*50)
defer cancel()
// Upload an object with storage.Writer.
wc := client.Bucket(bucket).Object(remoteObjectPath).NewWriter(ctx)
if _, err = io.Copy(wc, f); err != nil {
fmt.Fprintf(os.Stderr, "io.Copy: %v", err)
}
if err := wc.Close(); err != nil {
fmt.Fprintf(os.Stderr, "Writer.Close: %v", err)
}
fmt.Fprintf(os.Stdout, "Blob %v uploaded.\n", remoteObjectPath)
}