You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
1.8 KiB
Go

7 months ago
package storage
import (
"context"
"github.com/tencentyun/cos-go-sdk-v5"
"net/http"
"net/url"
"uploader/config"
)
type CosStorage struct {
Config *config.Cos
}
func NewCosStorage(config *config.Cos) *CosStorage {
return &CosStorage{Config: config}
}
func (s *CosStorage) getClient() (*cos.Client, error) {
u, _ := url.Parse(s.Config.BucketURL)
b := &cos.BaseURL{BucketURL: u}
client := cos.NewClient(b, &http.Client{
Transport: &cos.AuthorizationTransport{
// 通过环境变量获取密钥
// 环境变量 SECRETID 表示用户的 SecretId登录访问管理控制台查看密钥https://console.cloud.tencent.com/cam/capi
SecretID: s.Config.SecretID, // 用户的 SecretId建议使用子账号密钥授权遵循最小权限指引降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
// 环境变量 SECRETKEY 表示用户的 SecretKey登录访问管理控制台查看密钥https://console.cloud.tencent.com/cam/capi
SecretKey: s.Config.SecretKey, // 用户的 SecretKey建议使用子账号密钥授权遵循最小权限指引降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
},
})
return client, nil
}
func (s *CosStorage) Upload(filePath, destPath string) (string, error) {
client, err := s.getClient()
if err != nil {
return "", err
}
_, _, err = client.Object.Upload(
4 months ago
context.Background(), destPath, filePath, &cos.MultiUploadOptions{ThreadPoolSize: 5, PartSize: 30},
7 months ago
)
if err != nil {
return "", err
}
return s.Config.Domain + "/" + destPath, err
}
func (s *CosStorage) Delete(objectName string) error {
client, err := s.getClient()
if err != nil {
return err
}
_, err = client.Object.Delete(context.Background(), objectName)
return err
}