forked from GoesToEleven/GolangTraining
/
storage.go
68 lines (58 loc) · 1.42 KB
/
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
package browser
import (
"io"
"net/http"
"strings"
"google.golang.org/appengine"
"google.golang.org/appengine/urlfetch"
"google.golang.org/cloud"
"google.golang.org/cloud/storage"
"golang.org/x/net/context"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
)
const delimiter = "/"
type file struct {
IsFolder bool
Filename string
URL string
}
func getCloudContext(aeCtx context.Context, credentials string) (context.Context, error) {
conf, err := google.JWTConfigFromJSON(
[]byte(credentials),
storage.ScopeFullControl,
)
if err != nil {
return nil, err
}
tokenSource := conf.TokenSource(aeCtx)
hc := &http.Client{
Transport: &oauth2.Transport{
Source: tokenSource,
Base: &urlfetch.Transport{Context: aeCtx},
},
}
return cloud.NewContext(appengine.AppID(aeCtx), hc), nil
}
func listFiles(cctx context.Context, bucket, path string) ([]string, []string, error) {
q := &storage.Query{
Delimiter: delimiter,
Prefix: path,
}
objs, err := storage.ListObjects(cctx, bucket, q)
if err != nil {
return nil, nil, err
}
subfolders := []string{}
for _, v := range objs.Prefixes {
subfolders = append(subfolders, strings.TrimPrefix(v, path))
}
files := []string{}
for _, v := range objs.Results {
files = append(files, v.Name)
}
return files, subfolders, nil
}
func getFile(cctx context.Context, bucket, path string) (io.ReadCloser, error) {
return storage.NewReader(cctx, bucket, path)
}