对象存储服务 OBS-列举桶内多版本对象(Go SDK):代码示例
代码示例
本示例用于获取名为examplebucket桶下的版本对象列表,其中列举的是以test/ 开头的所有对象中的按照字典顺序的最多前100个对象,并且是从起始位置test/test2(该对象的版本号是G001117FCE89978B0000401205D5DC9A,如果没有匹配,则忽略该参数)开始列举。
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 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
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()) } input := &obs.ListVersionsInput{} // 指定存储桶名称 input.Bucket = "examplebucket" // 指定列举对象前缀,此处以“test/”前缀为例,满足指定前缀的对象会被列举。 input.Prefix = "test/" // 指定返回的最大对象数,此处以 100 为例,返回的对象列表将是按照字典顺序的最多前max-keys个对象,默认值为1000。 input.MaxKeys = 100 // 指定列举版本对象的起始位置,此处以“test/test2”为例 input.KeyMarker = "test/test2" // 与KeyMarker配合使用,如果KeyMarker没有对应的VersionIdMarker ,则该参数忽略 input.VersionIdMarker = "G001117FCE89978B0000401205D5DC9A" // 指定编码方式,此处以“url”为例,如果列举对象中存在特殊字符,则该参数必传 input.EncodingType = "url" // 列举桶内版本对象 output, err := obsClient.ListVersions(input) if err == nil { fmt.Printf("List version objects under the bucket(%s) successful!\n", input.Bucket) fmt.Printf("RequestId:%s\n", output.RequestId) for index, val := range output.Versions { fmt.Printf("Version[%d]-OwnerId:%s, ETag:%s, Key:%s, VersionId:%s, LastModified:%s, Size:%d\n", index, val.Owner.ID, val.ETag, val.Key, val.VersionId, val.LastModified, val.Size) } for index, val := range output.DeleteMarkers { fmt.Printf("DeleteMarker[%d]-OwnerId:%s, Key:%s, VersionId:%s, LastModified:%s\n", index, val.Owner.ID, val.Key, val.VersionId, val.LastModified) } return } fmt.Printf("List version objects under the bucket(%s) fail!\n", input.Bucket) 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) } } |