58 lines
1.7 KiB
Go
58 lines
1.7 KiB
Go
|
package dfs
|
|||
|
|
|||
|
import (
|
|||
|
"bytes"
|
|||
|
"context"
|
|||
|
"fmt"
|
|||
|
"github.com/tencentyun/cos-go-sdk-v5"
|
|||
|
"io"
|
|||
|
"net/http"
|
|||
|
"net/url"
|
|||
|
"time"
|
|||
|
)
|
|||
|
|
|||
|
type cosClient struct {
|
|||
|
client *cos.Client
|
|||
|
}
|
|||
|
|
|||
|
func newCos(secretId, secretKey, bucket string, region string) IDfs {
|
|||
|
c := new(cosClient)
|
|||
|
//u, _ := url.Parse(fmt.Sprintf("https://ttsj-1359624709.cos.ap-chengdu.myqcloud.com", bucket, region))
|
|||
|
u, _ := url.Parse(fmt.Sprintf("https://%v.cos.%v.myqcloud.com", bucket, region))
|
|||
|
b := &cos.BaseURL{BucketURL: u}
|
|||
|
client := cos.NewClient(b, &http.Client{
|
|||
|
Transport: &cos.AuthorizationTransport{
|
|||
|
SecretID: secretId, // 用户的 SecretId,建议使用子账号密钥,授权遵循最小权限指引,降低使用风险。子账号密钥获取可参考 https://cloud.tencent.com/document/product/598/37140
|
|||
|
SecretKey: secretKey, // 用户的 SecretKey,建议使用子账号密钥,授权遵循最小权限指引,降低使用风险。子账号密钥获取可参考 https://cloud.tencent.com/document/product/598/37140
|
|||
|
},
|
|||
|
})
|
|||
|
c.client = client
|
|||
|
|
|||
|
return c
|
|||
|
}
|
|||
|
|
|||
|
func (c *cosClient) GetObj(path string) ([]byte, error) {
|
|||
|
ctx, cf := context.WithTimeout(context.Background(), time.Second*10)
|
|||
|
defer cf()
|
|||
|
rsp, err := c.client.Object.Get(ctx, path, nil)
|
|||
|
if err != nil {
|
|||
|
return nil, fmt.Errorf("get cos object %v error:%v", path, err)
|
|||
|
}
|
|||
|
rspBin, err := io.ReadAll(rsp.Body)
|
|||
|
if err != nil {
|
|||
|
return nil, fmt.Errorf("read response obj %v error:%v", path, err)
|
|||
|
}
|
|||
|
return rspBin, nil
|
|||
|
}
|
|||
|
|
|||
|
func (c *cosClient) PutObj(path string, content []byte) error {
|
|||
|
ctx, cf := context.WithTimeout(context.Background(), time.Second*10)
|
|||
|
defer cf()
|
|||
|
buffer := bytes.NewBuffer(content)
|
|||
|
_, err := c.client.Object.Put(ctx, path, buffer, nil)
|
|||
|
return err
|
|||
|
}
|
|||
|
|
|||
|
func (c *cosClient) Close() {
|
|||
|
}
|