You need to enable JavaScript to run this app.
导航

获取桶元数据(C++ SDK)

最近更新时间2024.02.04 18:30:56

首次发布时间2022.04.08 10:56:29

通过 HeadBucket 用于获取存储桶(Bucket)的信息, 同时可以根据返回的 TosError 判断 HTTP Code 判断桶是否存在。

注意事项

  • 获取桶元数据之前,您必须具有 tos:HeadBucket 权限。具体操作,请参见权限配置指南
  • 若桶不存在则该接口会返回 404,也常用于判断桶是否存在。

示例代码

以下代码用于获取桶 examplebucket 的元数据。

#include "TosClientV2.h"
using namespace VolcengineTos;

int main(void){
    // 初始化 TOS 账号信息
    // Your Region 填写 Bucket 所在 Region
    std::string region = "Your Region";
    std::string accessKey = std::getenv("TOS_ACCESS_KEY");
    std::string secretKey = std::getenv("TOS_SECRET_KEY");
    // 填写 Bucket 名称,例如 examplebucket
    std::string bucketName = "examplebucket";
    
    // 初始化网络等资源
    InitializeClient();
    // 创建交互的 client
    TosClientV2 client(region, accessKey, secretKey);
    
    // 获取桶元数据
    HeadBucketV2Input input(bucketName);
    auto output = client.headBucket(input);
    if (!output.isSuccess()) {
        // 桶不存在
        if(!output.error().isClientError() && output.error().getStatusCode() == 404) {
            std::cout << "Bucket not found." << std::endl;
        } else {
            std::cout << "HeadBucket failed." << output.error().String() << std::endl;
            // 释放网络等资源
            CloseClient();
            return -1;
        }
    }
    // 打印桶信息
    std::cout << "HeadBucket success, the bucket region is:" << output.result().getRegion()
              << " the storage class is:" << output.result().getStringFormatStorageClass()
              << " the azRedundancy is:" << output.result().getStringFormatAzRedundancy() << std::endl;
    // 释放网络等资源
    CloseClient();
    return 0;
}

相关文档

关于获取桶的元数据 API 文档,请参见 HeadBucket