-
Notifications
You must be signed in to change notification settings - Fork 2
/
google_storage.go
71 lines (61 loc) · 1.64 KB
/
google_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
package yuri
///disclaimer::
///Do not use the this storage class
///I only created it with my use case in mind
import (
"context"
"fmt"
"io"
"os"
"time"
"cloud.google.com/go/storage"
"google.golang.org/api/option"
)
func InitGoogleStorage(path string) (*storage.Client, error) {
opt := option.WithCredentialsFile(path)
ctx := context.Background()
client, err := storage.NewClient(ctx, opt)
return client, err
}
type GoogleStorage struct {
Client *storage.Client
ProjectId string
}
func CreateBucket(Client *storage.Client, projectId, bucketName string) error {
ctx := context.Background()
bucket := Client.Bucket(bucketName)
ctx, cancel := context.WithTimeout(ctx, time.Second*20)
defer cancel()
if err := bucket.Create(ctx, projectId, nil); err != nil {
return err
}
return nil
}
func UploadFile(Client *storage.Client, bucket, objectName, filename string, isPublic bool) (*storage.Writer, error) {
ctx := context.Background()
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
ctx, cancel := context.WithTimeout(ctx, time.Second*50)
defer cancel()
handle := Client.Bucket(bucket).Object(objectName)
wc := handle.NewWriter(ctx)
///wc.MediaLink="cdn.codesahara.com/itachi"
if isPublic {
wc.ACL = []storage.ACLRule{{Entity: storage.AllUsers, Role: storage.RoleReader}}
}
contentType, err := GetFileContentTypeWithExtension(filename)
if err != nil {
return nil, err
}
wc.ContentType = contentType
if _, err = io.Copy(wc, f); err != nil {
return nil, fmt.Errorf("io.Copy: %v", err)
}
if err := wc.Close(); err != nil {
return nil, fmt.Errorf("Writer.Close: %v", err)
}
return wc, nil
}