[golang] go obtains Tencent Cloud cos object storage and converts it to base64 string output

1. Preparation

1. We need to introduce cos go sdk

Need to introduce Tencent Cloud cos sdk
https://github.com/tencentyun/cos-go-sdk-v5

2. Coding

Configure yaml as follows:

Cos:
  SecretId: "xxx"
  SecretKey: "xxx"
  Domain: "https://你的.cos.ap-beijing.myqcloud.com"
  Prefix: "桶前缀"
  AppId: "xxx"

The go code is written as follows:

func  GetCosImg2Base64(string imgStr) (string, error) {
    
    
	u, _ := url.Parse(l.svcCtx.Config.Cos.Domain)
	b := &cos.BaseURL{
    
    BucketURL: u}
	client := cos.NewClient(b, &http.Client{
    
    
		Transport: &cos.AuthorizationTransport{
    
    
			// 通过环境变量获取密钥
			// 环境变量 SECRETID 表示用户的 SecretId,登录访问管理控制台查看密钥,https://console.cloud.tencent.com/cam/capi
			SecretID: l.svcCtx.Config.Cos.SecretId,
			// 用户的 SecretId,建议使用子账号密钥,授权遵循最小权限指引,降低使用风险。
			//子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
			// 环境变量 SECRETKEY 表示用户的 SecretKey,登录访问管理控制台查看密钥,https://console.cloud.tencent.com/cam/capi
			SecretKey: l.svcCtx.Config.Cos.SecretKey,
			// 用户的 SecretKey,建议使用子账号密钥,授权遵循最小权限指引,降低使用风险。
			//子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
		},
	})
	// 因为数据库存的都是带所有前缀的:/桶前缀/itrarace/6734/xxx.gif
	resp, err := client.Object.Get(context.Background(), imgStr, nil)
	if err != nil {
    
    
		//os.Exit(-1)
		l.Logger.Errorf(err.Error())
		return nil, xerr.NewErrCode(xerr.COS_DEL_SINGLE_ERROR)
	}
	defer resp.Body.Close()

	var buf bytes.Buffer
	_, err = io.Copy(&buf, resp.Body)
	if err != nil {
    
    
		l.Logger.Errorf(err.Error())
		return nil, xerr.NewErrCode(xerr.COS_DEL_SINGLE_ERROR)
	}

	// 将图片转为 base64
	//fmt.Println(resp.ContentLength)
	//imageContent := make([]byte, resp.ContentLength)
	 复制响应的 Body 到文件中
	//resp.Body.Read(imageContent)
	imageBase64 := base64.StdEncoding.EncodeToString(buf.Bytes())
	//fmt.Println(imageBase64)

	return imageBase64, nil
}

Guess you like

Origin blog.csdn.net/wanglei19891210/article/details/131390008