golang腾讯云cos拷贝与删除

安装golang版本的sdk

go get -u github.com/tencentyun/cos-go-sdk-v5

当前bucket是xxxx,区域是ap-beijing

据两个例子

拷贝

譬如想把 /temp/a.png 拷贝到 /app/a.png
接收的两个文件路径参数如下:

source : xxxx.cos.ap-beijing.myqcloud.com/temp/a.png
target : app/a.png

删除

譬如想把 /app/a.png删除:
接收的两个文件路径参数如下:

target : app/a.png

使用情况

使用的时候一般来说得到的都是一个完整的地址,根据完整的地址来进行拷贝和删除,写了两个简单的使用例子。

func CosCopyFile(source string) string {
 base := "https://xxxx.cos.ap-beijing.myqcloud.com/"
 u, _ := url.Parse(base)
 b := &cos.BaseURL{BucketURL: u}
 client := cos.NewClient(b, &http.Client{
  Transport: &cos.AuthorizationTransport{
   SecretID:  "id",
   SecretKey: "secret",
  },
 })

 var target string
 target = strings.Replace(source, base, "", -1)
 source = strings.Replace(source, "https://", "", -1)
 target = strings.Replace(target, "temp", "app", -1)
 // 移动对象
 fmt.Printf("source is %+v\n", source)
 fmt.Printf("target is %+v\n", target)
 _, _, err := client.Object.Copy(context.Background(), target, source, nil)
 if err == nil {
  return base + target
 }
 fmt.Printf("err is %+v\n", err)
 return ""
}

func CosDeleteFile(target string) {
 base := "https://xxxx.cos.ap-beijing.myqcloud.com/"
 u, _ := url.Parse("https://xxxx.cos.ap-beijing.myqcloud.com/")
 b := &cos.BaseURL{BucketURL: u}
 client := cos.NewClient(b, &http.Client{
  Transport: &cos.AuthorizationTransport{
   SecretID:  "id",
   SecretKey: "secret",
  },
 })
 target = strings.Replace(target, base, "", -1)

 fmt.Printf("delete file %+v", target)
 // 删除对象
 _, err := client.Object.Delete(context.Background(), target)
 if err != nil {
  fmt.Printf("delete error %+v", err)
 }
}

使用例子:

CosCopyFile("https://xxxx.cos.ap-beijing.myqcloud.com/temp/a.png")
CosDeleteFile("https://xxxx.cos.ap-beijing.myqcloud.com/app/a.png")

你可能感兴趣的:(golang,golang,腾讯云)