|
|
|
|
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(
|
|
|
|
|
context.Background(), destPath, filePath, &cos.MultiUploadOptions{ThreadPoolSize: 5, PartSize: 30},
|
|
|
|
|
)
|
|
|
|
|
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
|
|
|
|
|
}
|