/
tencent_cos.go
56 lines (51 loc) · 1.57 KB
/
tencent_cos.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package file
import (
"bytes"
"fmt"
FileConstant "github.com/herman-hang/herman/application/constants/admin/file"
"github.com/herman-hang/herman/kernel/app"
"github.com/tencentyun/cos-go-sdk-v5"
"golang.org/x/net/context"
"io/ioutil"
"net/http"
"net/url"
)
// TencentCOS 腾讯云COS结构体
type TencentCOS struct {
client *cos.Client
bucket string
}
// NewTencentCOS 实例化一个腾讯云COS对象
// @param string path 文件存储目录
// @return *TencentCOS error 返回腾讯云COS对象和一个错误信息
func NewTencentCOS(region string, appId string, secretId string, secretKey string, bucket string) (*TencentCOS, error) {
u, _ := url.Parse(fmt.Sprintf("https://%s-%s.cos.%s.myqcloud.com", bucket, appId, region))
c := cos.NewClient(&cos.BaseURL{BucketURL: u}, &http.Client{
Transport: &cos.AuthorizationTransport{
SecretID: secretId,
SecretKey: secretKey,
},
})
return &TencentCOS{client: c, bucket: bucket}, nil
}
// Upload 文件上传
// @param string key 文件key
// @param content 文件流
// @return void
func (t *TencentCOS) Upload(key string, content []byte) error {
_, err := t.client.Object.Put(context.Background(), key, bytes.NewReader(content), nil)
if err != nil {
app.Log.Error(FileConstant.UploadFail)
}
return nil
}
// Download 文件下载
// @param string key 文件key
// @return []byte, error 文件流和错误信息
func (t *TencentCOS) Download(key string) ([]byte, error) {
res, err := t.client.Object.Get(context.Background(), key, nil)
if err != nil {
panic(FileConstant.DownloadFail)
}
return ioutil.ReadAll(res.Body)
}