7
votes

Using GoLang SDK for google cloud storage.... Cannot find a method to check if a bucket exists.

func (c *Client) Bucket(name string) *BucketHandle

Bucket returns a BucketHandle even if bucket does not exist.

So, how can I check if the bucket exists? I do not want to create the bucket if it does not exist, so cannot take the route of trying to create a bucket and handle errors

2

2 Answers

6
votes

This can be done by using the Attrs function :

bucket := client.Bucket(bucketName)
exists,err := bucket.Attrs(ctx)
if err != nil {
    log.Fatalf("Message: %v",err)
}
fmt.Println(exists)

Since err, prints Message: storage: bucket doesn't exist.

In case you consider that having a function that directly mentions if a bucket exists or not would be useful, I suggest filling a feature request to the Cloud Storage engineering team to consider having it on further releases.

0
votes

you can func (c *Client) Buckets(ctx context.Context, projectID string) *BucketIterator to iterate over the existing buckets and check if it exists.