github.com/emcfarlane/larking@v0.0.0-20220605172417-1704b45ee6c3/starlib/starext/blobs.go (about) 1 package starext 2 3 import ( 4 "context" 5 "sync" 6 7 "gocloud.dev/blob" 8 ) 9 10 type Blobs struct { 11 mu sync.Mutex // protects bkts 12 bkts map[string]Bucket 13 } 14 15 type Bucket struct { 16 *blob.Bucket 17 } 18 19 func (b Bucket) Close() error { panic("close on pooled bucket") } 20 21 // Load bucket from blobs pool, close handled by blobs.Close. 22 func (b *Blobs) OpenBucket(ctx context.Context, urlstr string) (Bucket, error) { 23 b.mu.Lock() 24 defer b.mu.Unlock() 25 26 if bkt, ok := b.bkts[urlstr]; ok { 27 return bkt, nil 28 } 29 30 bkt, err := blob.OpenBucket(ctx, urlstr) 31 if err != nil { 32 return Bucket{}, err 33 } 34 35 if b.bkts == nil { 36 b.bkts = make(map[string]Bucket) 37 } 38 b.bkts[urlstr] = Bucket{bkt} 39 return Bucket{bkt}, nil 40 } 41 42 // Close open buckets. 43 func (b *Blobs) Close() error { 44 b.mu.Lock() 45 defer b.mu.Unlock() 46 47 var firstErr error 48 for _, bkt := range b.bkts { 49 if err := bkt.Bucket.Close(); err != nil { 50 if firstErr == nil { 51 firstErr = err 52 } 53 } 54 } 55 return firstErr 56 } 57 58 func (b *Blobs) NewReader(ctx context.Context, urlstr, key string, opts *blob.ReaderOptions) (*blob.Reader, error) { 59 bkt, err := b.OpenBucket(ctx, urlstr) 60 if err != nil { 61 return nil, err 62 } 63 return bkt.NewReader(ctx, key, opts) 64 } 65 66 func (b *Blobs) NewWriter(ctx context.Context, urlstr, key string, opts *blob.WriterOptions) (*blob.Writer, error) { 67 bkt, err := b.OpenBucket(ctx, urlstr) 68 if err != nil { 69 return nil, err 70 } 71 return bkt.NewWriter(ctx, key, opts) 72 }