链接复制成功!
判断桶是否存在(Go SDK)
功能介绍
判断指定桶名的桶是否存在,返回的结果中HTTP状态码为200表明桶存在,否则返回404表明桶不存在。
接口约束
- 您必须是桶拥有者或拥有判断桶是否存在的权限,才能判断桶是否存在。建议使用IAM或桶策略进行授权,如果使用IAM则需授予obs:bucket:HeadBucket权限,如果使用桶策略则需授予HeadBucket权限。相关授权方式介绍可参见OBS权限控制概述,配置方式详见使用IAM自定义策略、自定义创建桶策略。
- OBS支持的Region与Endpoint的对应关系,详细信息请参见地区与终端节点。
方法定义
func (obsClient ObsClient) HeadBucket(bucketName string, extensions...extensionOptions) (output *BaseModel, err error)
请求参数说明
参数名称 |
参数类型 |
是否必选 |
描述 |
---|---|---|---|
bucketName |
string |
是 |
参数解释: 桶名。 约束限制:
默认取值: 无 |
extensions |
否 |
参数解释: 桶相关扩展信息。通过调用拓展配置项为对应请求配置额外的拓展请求头,详情参考extensionOptions |
返回结果说明
参数名称 |
参数类型 |
描述 |
---|---|---|
StatusCode |
int |
参数解释: HTTP状态码。 取值范围: 状态码是一组从2xx(成功)到4xx或5xx(错误)的数字代码,状态码表示了请求响应的状态。完整的状态码列表请参见状态码。 默认取值: 无 |
RequestId |
string |
参数解释: OBS服务端返回的请求ID。 默认取值: 无 |
ResponseHeaders |
map[string][]string |
参数解释: HTTP响应头信息。 默认取值: 无 |
代码示例
本示例用于判断examplebucket桶是否存在。
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 |
package main
import (
"fmt"
"os"
obs "github.com/huaweicloud/huaweicloud-sdk-go-obs/obs"
)
func main() {
//推荐通过环境变量获取AKSK,这里也可以使用其他外部引入方式传入,如果使用硬编码可能会存在泄露风险。
//您可以登录访问管理控制台获取访问密钥AK/SK,获取方式请参见https://support.huaweicloud.com/usermanual-ca/ca_01_0003.html。
ak := os.Getenv("AccessKeyID")
sk := os.Getenv("SecretAccessKey")
// 【可选】如果使用临时AK/SK和SecurityToken访问OBS,同样建议您尽量避免使用硬编码,以降低信息泄露风险。您可以通过环境变量获取访问密钥AK/SK,也可以使用其他外部引入方式传入。
securityToken := os.Getenv("SecurityToken")
// endpoint填写Bucket对应的Endpoint, 这里以华北-北京四为例,其他地区请按实际情况填写。
endPoint := "https://obs.cn-north-4.myhuaweicloud.com"
// 创建obsClient实例
// 如果使用临时AKSK和SecurityToken访问OBS,需要在创建实例时通过obs.WithSecurityToken方法指定securityToken值。
obsClient, err := obs.New(ak, sk, endPoint, obs.WithSecurityToken(securityToken))
if err != nil {
fmt.Printf("Create obsClient error, errMsg: %s", err.Error())
}
// 指定存储桶名称
bucketname := "examplebucket"
// 判断桶是否存在
output, err := obsClient.HeadBucket(bucketname)
if err == nil {
fmt.Printf("Head bucket(%s) successful!\n", bucketname)
fmt.Printf("RequestId:%s\n", output.RequestId)
return
}
fmt.Printf("Head bucket(%s) fail!\n", bucketname)
if obsError, ok := err.(obs.ObsError); ok {
fmt.Println("An ObsError was found, which means your request sent to OBS was rejected with an error response.")
fmt.Println(obsError.Error())
} else {
fmt.Println("An Exception was found, which means the client encountered an internal problem when attempting to communicate with OBS, for example, the client was unable to access the network.")
fmt.Println(err)
}
}
|
相关链接
- 判断桶是否存在和获取桶元数据是同一个REST API,关于判断桶是否存在的API说明,请参见获取桶元数据。
- 创建桶过程中返回的错误码含义、问题原因及处理措施可参考OBS错误码。
- 桶和对象相关常见问题请参见桶和对象相关常见问题。
父主题: 桶相关接口(Go SDK)