-
Notifications
You must be signed in to change notification settings - Fork 12
/
gcs.go
71 lines (63 loc) · 1.7 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
68
69
70
71
package gcs
import (
"context"
"fmt"
"io"
"net/http"
"path"
"strings"
"cloud.google.com/go/storage"
"github.com/pkg/errors"
"google.golang.org/api/option"
)
type GCS struct {
client *storage.Client
bkt *storage.BucketHandle
}
func New(bucketName, serviceAccountFile string) (*GCS, error) {
ctx := context.Background()
o := []option.ClientOption{
option.WithServiceAccountFile(serviceAccountFile),
option.WithScopes(storage.ScopeReadOnly),
}
client, err := storage.NewClient(ctx, o...)
if err != nil {
return nil, errors.Wrap(err, "creating google cloud storage client")
}
bkt := client.Bucket(bucketName)
_, err = bkt.Attrs(ctx)
if err != nil && err == storage.ErrBucketNotExist {
return nil, fmt.Errorf("gcs bucket %s does not exist", bucketName)
} else if err != nil {
return nil, errors.Wrap(err, "getting bucket attributes")
}
return &GCS{client: client, bkt: bkt}, nil
}
func (g *GCS) HealthzHandler() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if err := g.Healthz(); err != nil {
http.Error(w, "health check failed", http.StatusInternalServerError)
return
}
}
}
func (g *GCS) Healthz() error {
_, err := g.bkt.Attrs(context.Background())
return err
}
func (g *GCS) FileHandler(w http.ResponseWriter, r *http.Request) {
upath := strings.TrimPrefix(r.URL.Path, "/")
o := g.bkt.Object(path.Clean(upath))
ctx := context.Background()
f, err := o.NewReader(ctx)
if err == storage.ErrObjectNotExist {
errString := fmt.Sprintf("file %s not found: %s", upath, err)
http.Error(w, errString, http.StatusNotFound)
return
} else if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer f.Close()
io.Copy(w, f)
}