Google Storage:如何检查存储桶是否存在

问题描述:

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

使用GoLang SDK进行Google云存储。...找不到检查存储桶是否存在的方法。 p>

  func(c * Client)Bucket(名称字符串)* BucketHandle 
  code>  pre> 
 
 

Bucket返回一个BucketHandle,即使bucket确实做了 不存在。 p>

那么,如何检查存储桶是否存在? 我不希望创建不存在的存储桶,因此无法采取尝试创建存储桶并处理错误的路线 p> div>

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.

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