-
Notifications
You must be signed in to change notification settings - Fork 155
/
blob.go
82 lines (73 loc) · 2.56 KB
/
blob.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
//
// Copyright 2024 The GUAC Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package blob
import (
"bytes"
"context"
"fmt"
"gocloud.dev/blob"
_ "gocloud.dev/blob/azureblob"
_ "gocloud.dev/blob/fileblob"
_ "gocloud.dev/blob/gcsblob"
_ "gocloud.dev/blob/memblob"
_ "gocloud.dev/blob/s3blob"
)
type BlobStore struct {
bucket *blob.Bucket
}
// NewBlobStore initializes the blob store based on the url.
// utilizing gocloud (https://gocloud.dev/howto/blob/) various blob stores
// such as S3, google cloud bucket, azure blob store can be used.
// Authentication is setup via environment variables. Please refer to for
// full documentation https://gocloud.dev/howto/blob/
func NewBlobStore(ctx context.Context, url string) (*BlobStore, error) {
bucket, err := blob.OpenBucket(ctx, url)
if err != nil {
return nil, fmt.Errorf("failed to open bucket with error: %w", err)
}
return &BlobStore{
bucket: bucket,
}, nil
}
// Write uses the key and value to write the data to the initialized blob store (via the authentication provided)
func (b *BlobStore) Write(ctx context.Context, key string, value []byte) error {
w, err := b.bucket.NewWriter(ctx, key, nil)
if err != nil {
return fmt.Errorf("failed to write to bucket with error: %w", err)
}
_, writeErr := w.Write(value)
// Always check the return value of Close when writing.
closeErr := w.Close()
if writeErr != nil {
return fmt.Errorf("failed to write the value with error: %w", writeErr)
}
if closeErr != nil {
return fmt.Errorf("failed to close the bucket writer with error: %w", closeErr)
}
return nil
}
// Read uses the key read the data from the initialized blob store (via the authentication provided)
func (b *BlobStore) Read(ctx context.Context, key string) ([]byte, error) {
r, err := b.bucket.NewReader(ctx, key, nil)
if err != nil {
return nil, fmt.Errorf("failed to read to bucket with error: %w", err)
}
defer r.Close()
buf := new(bytes.Buffer)
if _, err := buf.ReadFrom(r); err != nil {
return nil, fmt.Errorf("failed to read bytes with error: %w", err)
}
return buf.Bytes(), nil
}