-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
gcs.go
67 lines (56 loc) · 1.8 KB
/
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
package provider
import (
"context"
"io"
"net/http"
"cloud.google.com/go/storage"
"github.com/pkg/errors"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"google.golang.org/api/option"
)
// NewGCSTransport returns the transport used by GCS.
func NewGCSTransport(ctx context.Context) (http.RoundTripper, error) {
ts, err := google.DefaultTokenSource(ctx, storage.ScopeReadOnly)
if err != nil {
return nil, errors.Wrap(err, "cannot create token source")
}
return oauth2.NewClient(ctx, ts).Transport, nil
}
// NewGCS will create the GCS Provider.
func NewGCS(ctx context.Context, bucket string, transport http.RoundTripper) (*GCS, error) {
// Create the options for the client.
opts := []option.ClientOption{
option.WithHTTPClient(&http.Client{
Transport: transport,
}),
}
// Creates a storage client for the requests made by this server.
client, err := storage.NewClient(ctx, opts...)
if err != nil {
return nil, errors.Wrap(err, "cannot create storage client")
}
return &GCS{
bucket: client.Bucket(bucket),
}, nil
}
// GCS provides a way to access files from Google Cloud Storage. Credentials
// used are loaded from the `GOOGLE_APPLICATION_CREDENTIALS` environment
// variable.
type GCS struct {
bucket *storage.BucketHandle
}
// Provide provides a file by making a request to Google Cloud Storage with the
// specified key and then returning the response body when the request was
// complete.
func (gcs *GCS) Provide(ctx context.Context, filename string) (io.ReadCloser, error) {
// Get the object handlea and return a reader based on the object handle.
r, err := gcs.bucket.Object(filename).NewReader(ctx)
if err != nil {
if errors.Is(err, storage.ErrObjectNotExist) {
return nil, ErrNotFound
}
return nil, errors.Wrap(err, "cannot get file from provider")
}
return r, nil
}