-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgs.go
109 lines (102 loc) · 2.48 KB
/
gs.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package bqwt
import (
"cloud.google.com/go/storage"
"context"
"io"
"io/ioutil"
"net/url"
"os"
)
//DownloadGSContent returns google storage content
func DownloadGSContent(ctx context.Context, URL string) ([]byte, error) {
parsedURL, err := url.Parse(URL)
if err != nil {
return nil, err
}
if parsedURL.Scheme == "file" {
content, err := ioutil.ReadFile(parsedURL.Path)
if err != nil {
return nil, reclassifyNotFoundIfMatched(err, URL)
}
return content, err
}
client, err := storage.NewClient(ctx)
if err != nil {
return nil, err
}
bucket := client.Bucket(parsedURL.Host)
objectPath := string(parsedURL.Path[1:])
rc, err := bucket.Object(objectPath).NewReader(ctx)
if err != nil {
return nil, reclassifyNotFoundIfMatched(err, URL)
}
defer rc.Close()
data, err := ioutil.ReadAll(rc)
if err != nil {
return nil, err
}
return data, nil
}
//UploadGSContent uploads content to gs
func UploadGSContent(ctx context.Context, URL string, reader io.Reader) error {
parsedURL, err := url.Parse(URL)
if err != nil {
return err
}
if parsedURL.Scheme == "file" {
data, err := ioutil.ReadAll(reader)
if err != nil {
return err
}
return ioutil.WriteFile(parsedURL.Path, data, 0777)
}
client, err := storage.NewClient(ctx)
if err != nil {
return err
}
bucket := client.Bucket(parsedURL.Host)
objectPath := string(parsedURL.Path[1:])
writer := bucket.Object(objectPath).NewWriter(ctx)
if _, err := io.Copy(writer, reader); err != nil {
return err
}
return writer.Close()
}
//ExistsGSObject returns true if gs object exists
func ExistsGSObject(ctx context.Context, URL string) bool {
parsedURL, err := url.Parse(URL)
if err != nil {
return false
}
if parsedURL.Scheme == "file" {
_, err := os.Stat(parsedURL.Path)
return err == nil
}
client, err := storage.NewClient(ctx)
if err != nil {
return false
}
bucket := client.Bucket(parsedURL.Host)
objectPath := string(parsedURL.Path[1:])
_, err = bucket.Object(objectPath).Attrs(ctx)
err = reclassifyNotFoundIfMatched(err, URL)
return !IsNotFoundError(err)
}
//DeleteGSObject delete gs object
func DeleteGSObject(ctx context.Context, URL string) error {
parsedURL, err := url.Parse(URL)
if err != nil {
return err
}
if parsedURL.Scheme == "file" {
err = os.Remove(parsedURL.Path)
return err
}
client, err := storage.NewClient(ctx)
if err != nil {
return err
}
bucket := client.Bucket(parsedURL.Host)
objectPath := string(parsedURL.Path[1:])
return bucket.Object(objectPath).Delete(ctx)
}