初识GO SDK

Golang
380
0
0
2022-09-28

一、下载与安装

环境依赖

Golang:用于下载和安装 Go 编译运行环境,请前往 Golang 官网进行下载。

安装SDK

执行以下命令COS GO SDK

go get -u github.com/tencentyun/cos-go-sdk-v5
二、开始使用

在本文章中我们将为您介绍如何使用COS GO SDK完成一些基本操作,如初始化客户端、创建存储桶、查询存储桶列表、上传对象、查询对象列表、下载对象和删除对象。

1. 初始化

使用 COS 域名生成 COS GO 客户端 Client 结构。

func NewClient(uri *BaseURL, httpClient *http.Client) *Client

这是BaseURL结构体:

// BaseURL 访问各 API 所需的基础 URL
type BaseURL struct {
    // 访问 bucket, object 相关 API 的基础 URL(不包含 path 部分): https://examplebucket-1250000000.cos.<Region>.myqcloud.com
    BucketURL *url.URL
    // 访问 service API 的基础 URL(不包含 path 部分): https://cos.<Region>.myqcloud.com
    ServiceURL *url.URL
    // 访问 Batch API 的基础 URL (不包含 path 部分): https://<UIN>.cos-control.<Region>.myqcloud.com
    BatchURL *url.URL
    // 访问 CI 的基础 URL (不包含 path 部分): https://examplebucket-1250000000.ci.<Region>.myqcloud.com
    CIURL *url.URL
}

下面是请求实例这是直接去腾讯官网找到的:

  1. 使用永久秘钥
// 将 examplebucket-1250000000 和 COS_REGION 修改为用户真实的信息
// 存储桶名称,由bucketname-appid 组成,appid必须填入,可以在COS控制台查看存储桶名称。https://console.cloud.tencent.com/cos5/bucket
// COS_REGION 可以在控制台查看,https://console.cloud.tencent.com/cos5/bucket, 关于地域的详情见 https://cloud.tencent.com/document/product/436/6224
u, _ := url.Parse("https://examplebucket-1250000000.cos.COS_REGION.myqcloud.com")
// 用于Get Service 查询,默认全地域 service.cos.myqcloud.com
su, _ := url.Parse("https://cos.COS_REGION.myqcloud.com")
b := &cos.BaseURL{BucketURL: u, ServiceURL: su}
// 1.永久密钥
client := cos.NewClient(b, &http.Client{
    Transport: &cos.AuthorizationTransport{
        SecretID:  "SECRETID",  // 替换为用户的 SecretId,请登录访问管理控制台进行查看和管理,https://console.cloud.tencent.com/cam/capi
        SecretKey: "SECRETKEY", // 替换为用户的 SecretKey,请登录访问管理控制台进行查看和管理,https://console.cloud.tencent.com/cam/capi
    },
})
  1. 使用临时秘钥
// 将 examplebucket-1250000000 和 COS_REGION 修改为真实的信息
// 存储桶名称,由bucketname-appid 组成,appid必须填入,可以在COS控制台查看存储桶名称。https://console.cloud.tencent.com/cos5/bucket
// COS_REGION 可以在控制台查看,https://console.cloud.tencent.com/cos5/bucket, 关于地域的详情见 https://cloud.tencent.com/document/product/436/6224
u, _ := url.Parse("https://examplebucket-1250000000.cos.COS_REGION.myqcloud.com")
b := &cos.BaseURL{BucketURL: u}
// 2.临时密钥
client := cos.NewClient(b, &http.Client{
    Transport: &cos.AuthorizationTransport{
        // 如果使用临时密钥需要填入,临时密钥生成和使用指引参见https://cloud.tencent.com/document/product/436/14048
        SecretID:     "SECRETID",
        SecretKey:    "SECRETKEY",
        SessionToken: "SECRETTOKEN",
    },
})
if client != nil {
    // 调用 COS 请求
}
  1. 设置域名
  2. 通过修改 BaseURL,可以直接使用自定义域名或者全球加速域名访问 COS。
// 使用全球加速域名访问COS
u, _ := url.Parse("http://<BucketName-APPID>.cos.accelerate.myqcloud.com")
b := &cos.BaseURL{BucketURL: u}
// 2.临时密钥
client := cos.NewClient(b, &http.Client{
    Transport: &cos.AuthorizationTransport{
        // 如果使用临时密钥需要填入,临时密钥生成和使用指引参见https://cloud.tencent.com/document/product/436/14048
        SecretID:     "SECRETID",
        SecretKey:    "SECRETKEY",
        SessionToken: "SECRETTOKEN",
    },
})
2. 创建存储桶
package main

import (
    "context" 
    "net/http" 
    "net/url" 
    "github.com/tencentyun/cos-go-sdk-v5"
)

func main() {
    //创建存储桶,连接我们的腾讯云存储桶:https://yourname-1309975315.cos.ap-shanghai.myqcloud.com
    u, err := url.Parse("http://<BucketName-APPID>.cos.accelerate.myqcloud.com")
    if err != nil {
        panic(err)
    }
    //秘钥,该秘钥无效,需要更换自己的秘钥
    secID := "AKIDe8Ldfnjd0LQGrtgDUdfjkcnfdhfidf"
    secKey := "4rdffcKdfndlx3wax4vVoqbdfjihidfnkdff"
    b := &cos.BaseURL{BucketURL: u}
    c := cos.NewClient(b, &http.Client{
        Transport: &cos.AuthorizationTransport{
            SecretID:  secID,
            SecretKey: secKey,
        },
    })

    _, err = c.Bucket.Put(context.Background(), nil)
    if err != nil {
        panic(err)
    }

}                      
3. 查询存储列表
package main

import (
    "context" 
    "fmt" 
    "net/http"

    "github.com/tencentyun/cos-go-sdk-v5"
)

func main() {
    secID := "AKIDe8Ldfnjd0LQGrtgDUdfjkcnfdhfidf"
    secKey := "4rdffcKdfndlx3wax4vVoqbdfjihidfnkdff"

    c := cos.NewClient(nil, &http.Client{
        Transport: &cos.AuthorizationTransport{
            SecretID:  secID,
            SecretKey: secKey,
        },
    })

    s, _, err := c.Service.Get(context.Background())
    if err != nil {
        panic(err)
    }

    for _, b := range s.Buckets {
        fmt.Printf("列表: %#v\n", b)

    }

}

打印结果:

列表: cos.Bucket{Name:"*****-1309****", Region:"ap-shanghai", CreationDate:"2022-04-07T03:54:47Z"}

看到输出结果有:1、存储桶名 2、腾讯给的一串数字 3、服务地址 4、时间戳

4、上传对象
package main

import (
    "context" 
    "os" 
    "strings" 
    "net/http" 
    "net/url" 
    "github.com/tencentyun/cos-go-sdk-v5"
)

func main() {
    //秘钥,该秘钥无效,需要更换自己的秘钥
    secID := "AKIDe8Ldfnjd0LQGrtgDUdfjkcnfdhfidf"
    secKey := "4rdffcKdfndlx3wax4vVoqbdfjihidfnkdff"
    u, err := url.Parse("http://<BucketName-APPID>.cos.accelerate.myqcloud.com")
    if err != nil {
        panic(err)
    }
    b := &cos.BaseURL{BucketURL: u}
    c := cos.NewClient(b, &http.Client{
        Transport: &cos.AuthorizationTransport{
            SecretID:  secID,
            SecretKey: secKey,
        },
    })

    //1.通过字符串上传
    f := strings.NewReader("this is txt of test")

    name := "myCloudtest"
    _, err = c.Object.Put(context.Background(), name, f, nil)
    if err != nil {
        panic((err))
    }

    //2.通过本地文件上传对象
    path := "/Users/feng/test/img/10.png"
    name = "myCloudimg"

  _, err = c.Object.PutFromFile(context.Background(), name, path, nil)
  if err != nil {
      panic(err)
  }

    //3. 通过文件流上传
    fd, err := os.Open("/Users/feng/test/img/haha.png")
    if err != nil {
        panic(err)
    }
    defer fd.Close()
    name = "myCloudfileIO"

    _, err = c.Object.Put(context.Background(), name, fd, nil)
    if err != nil {
        panic(err)
    }

}
5. 获取预签名URL
package main

import (
    "context" 
    "fmt" 
    "net/http" 
    "net/url" 
    "time"

    "github.com/tencentyun/cos-go-sdk-v5"
)

func main() {

u, err := url.Parse("https://examplebucket-1250000000.cos.COS_REGION.myqcloud.com")
    if err != nil {
        panic(err)
    }
    //秘钥
    secID := "AKIDe8Ldfnjd0LQGrtgDUdfjkcnfdhfidf"
    secKey := "4rdffcKdfndlx3wax4vVoqbdfjihidfnkdff"

    b := &cos.BaseURL{BucketURL: u}

    client := cos.NewClient(b, &http.Client{
        Transport: &cos.AuthorizationTransport{
            SecretID:  secID,
            SecretKey: secKey,
        },
    })
    //存储桶文件名
    name := "cloud.png" 
    // 获取预签名URL
    presignedURL, err := client.Object.GetPresignedURL(context.Background(),
        http.MethodGet,
        name,
        secID,
        secKey,
        20*time.Second, nil)
    if err != nil {
        panic(err)
    }

    fmt.Println(presignedURL)
}

打印结果:

[*****MacBook-Pro:~/src/coolcar/server] feng% go run cmd/cos/main.go
https://myname-13*****8.cos.ap-shanghai.myqcloud.com/cloud.png?q-sign-algorithm=sha1&q-ak=AKIDe8LIyNWO0LQGrtgDUUEykU8XgY9drpMe&q-sign-time=1649332331%3B1649334651&q-key-time=1649332331%3B1649334651&q-header-list=host&q-url-param-list=&q-signature=e39e153454c6cffaf8750b0b0f8bffb00b590d356
[*****MacBook-Pro:~/src/coolcar/server] feng% 

接着我们访问该URL:

就可以访问到我们的腾讯云存储桶的name := "cloud.png"文件,有效时间只有20秒

6、查询对象存储列表
package main

import (
    "context" 
    "fmt" 
    "net/http" 
    "net/url" 
    "github.com/tencentyun/cos-go-sdk-v5"
)

func main() {
    secID := "AKIDe8Ldfnjd0LQGrtgDUdfjkcnfdhfidf"
    secKey := "4rdffcKdfndlx3wax4vVoqbdfjihidfnkdff"
    u, err := url.Parse("https://examplebucket-1250000000.cos.COS_REGION.myqcloud.com")
    if err != nil {
        panic(err)
    }
    b := &cos.BaseURL{BucketURL: u}
    c := cos.NewClient(b, &http.Client{
        Transport: &cos.AuthorizationTransport{
            SecretID:  secID,
            SecretKey: secKey,
        },
    })

    opt := &cos.BucketGetOptions{
        Prefix:  "myCloudimg",
        MaxKeys: 3,
    }
    v, _, err := c.Bucket.Get(context.Background(), opt)
    if err != nil {
        panic(err)
    }

    for _, c := range v.Contents {
        fmt.Printf("%s, %d\n", c.Key, c.Size)
    }

}
7. 下载对象
package main

import (
    "context" 
    "fmt" 
    "io/ioutil" 
    "net/http" 
    "net/url" 
    "github.com/tencentyun/cos-go-sdk-v5"
)

func main() {
    secID := "AKIDe8Ldfnjd0LQGrtgDUdfjkcnfdhfidf"
    secKey := "4rdffcKdfndlx3wax4vVoqbdfjihidfnkdff"
    u, err := url.Parse("https://examplebucket-1250000000.cos.COS_REGION.myqcloud.com")
    if err != nil {
        panic(err)
    }
    b := &cos.BaseURL{BucketURL: u}

    c := cos.NewClient(b, &http.Client{
        Transport: &cos.AuthorizationTransport{
            SecretID:  secID,
            SecretKey: secKey,
        },
    })


    name := "myCloudimg"
    localpath := "/Users/feng/Desktop/fromCloudimg.png"

  //1.通过响应体获取对象
    resp, err := c.Object.Get(context.Background(), name, nil)
    if err != nil {
        panic(err)
    }
    bs, _ := ioutil.ReadAll(resp.Body)
    resp.Body.Close()
    fmt.Printf("%s\n", string(bs))

    //2.获取对象到本地文件
    _, err = c.Object.GetToFile(context.Background(), name, localpath, nil)
    if err != nil {
        panic(err)
    }
8. 删除对象
package main

import (
    "context" 
    "net/http" 
    "net/url"

    "github.com/tencentyun/cos-go-sdk-v5"
)

func main() {
    secID := "AKIDe8Ldfnjd0LQGrtgDUdfjkcnfdhfidf"
    secKey := "4rdffcKdfndlx3wax4vVoqbdfjihidfnkdff"
    u, err := url.Parse("https://examplebucket-1250000000.cos.COS_REGION.myqcloud.com")
    if err != nil {
        panic(err)
    }
    b := &cos.BaseURL{BucketURL: u}
    c := cos.NewClient(b, &http.Client{
        Transport: &cos.AuthorizationTransport{
            SecretID:  secID,
            SecretKey: secKey,
        },
    })

    name := "myCloudfileIO" //删除指定对象
    _, err = c.Object.Delete(context.Background(), name, nil)
    if err != nil {
        panic(err)
    }

}