-
Notifications
You must be signed in to change notification settings - Fork 0
/
i9-gcs.go
71 lines (56 loc) · 1.38 KB
/
i9-gcs.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
/*
* Copyright (c) 2023.
* Created by Andy Pangaribuan <https://github.com/apangaribuan>.
* All Rights Reserved.
*/
package i9
import (
"bytes"
"context"
"io"
"os"
"path/filepath"
"time"
"cloud.google.com/go/storage"
"google.golang.org/api/option"
)
type srGCS struct {
ctx context.Context
handler *storage.BucketHandle
}
func newGcsInstance(bucketName string, credential []byte) (*srGCS, error) {
ctx := context.Background()
client, err := storage.NewClient(ctx, option.WithCredentialsJSON(credential))
if err != nil {
return nil, err
}
handler := client.Bucket(bucketName)
instance := &srGCS{
ctx: ctx,
handler: handler,
}
return instance, nil
}
func (slf *srGCS) Write(destination string, data []byte, timeout ...time.Duration) error {
ctx := context.Background()
if len(timeout) > 0 {
c, cancel := context.WithTimeout(ctx, timeout[0])
defer cancel()
ctx = c
}
writer := slf.handler.Object(destination).NewWriter(ctx)
defer writer.Close()
_, err := io.Copy(writer, bytes.NewReader(data))
return err
}
func (slf *srGCS) WriteFromFile(destination string, fromFilePath string, autoIncludeExtension bool, timeout ...time.Duration) error {
data, err := os.ReadFile(fromFilePath)
if err != nil {
return err
}
if autoIncludeExtension {
ext := filepath.Ext(fromFilePath)
destination += ext
}
return slf.Write(destination, data, timeout...)
}