Call IsBucketExist to check whether a named bucket exists and whether your credentials have permission to access it.
To determine whether a bucket exists, you must have theoss:GetBucketAclpermission. Check the returnederrorvalue to determine whether the call succeeded.
Prerequisites
Before you begin, make sure you have:
Configured access credentials as environment variables. See Configure access credentials
The
oss:GetBucketAclpermission granted to your RAM user. See Attach a custom policy to a RAM user
Method signature
func (c *Client) IsBucketExist(ctx context.Context, bucket string, optFns ...func(*Options)) (bool, error)Request parameters
| Parameter | Type | Description |
|---|---|---|
ctx | context.Context | Controls the lifetime of the request, such as deadlines and cancellations. |
bucket | string | The name of the bucket to check. |
optFns | ...func(*Options) | Optional operation-level settings. See Options. |
Response parameters
| Parameter | Type | Description |
|---|---|---|
exists | bool | The response to the operation. Valid only when err is nil. |
err | error | Non-nil if the request failed. |
Check whether a bucket exists
The following example shows the core call and how to handle the result:
// Check whether the bucket exists.
exists, err := client.IsBucketExist(context.TODO(), bucketName)
if err != nil {
// The check failed: network error, invalid credentials, or another unexpected error.
log.Fatalf("failed to check bucket existence: %v", err)
}
if exists {
log.Printf("bucket %q exists and is accessible", bucketName)
} else {
log.Printf("bucket %q does not exist or is not accessible", bucketName)
}For a complete, runnable program that accepts command-line arguments, see the full sample on GitHub.
Usage notes
The sample code uses
cn-hangzhouas the region ID (China (Hangzhou) region). By default, requests go through the public endpoint. To access OSS from another Alibaba Cloud service in the same region, configure the internal endpoint instead. See Regions and endpoints.Access credentials are read from environment variables at runtime.