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

96 lines
2.0 KiB

package fileCos
import (
"bytes"
"context"
"epur-pay/pkg/logger"
"fmt"
"github.com/tencentyun/cos-go-sdk-v5"
"io"
"net/http"
"net/url"
"reflect"
)
/*
腾讯Cos
*/
type Cos struct {
AccessKeyId string
AccessKeySecret string
BucketName string
EndPoint string
Access string
ReadPrivate bool
Appid string
client *cos.Client
}
func New(accessKeyId, accessKeySecret, bucketName, endPoint string, access string, Appid string) (*Cos, error) {
var instance *Cos
instance = &Cos{
AccessKeyId: accessKeyId,
AccessKeySecret: accessKeySecret,
BucketName: bucketName,
EndPoint: endPoint,
Access: access,
Appid: Appid,
}
//cos.NewClient()
uu := fmt.Sprintf(
"https://%s-%s.%s", instance.BucketName, instance.Appid, instance.EndPoint)
logger.AccessLogger.Infoln("cos -> ", uu)
endPoint1, _ := url.Parse(uu)
client := cos.NewClient(
&cos.BaseURL{BucketURL: endPoint1}, &http.Client{
Transport: &cos.AuthorizationTransport{
SecretID: instance.AccessKeyId,
SecretKey: instance.AccessKeySecret,
},
})
instance.client = client
return instance, nil
}
func (this *Cos) url(fileName string) string {
return fmt.Sprintf("https://%s/%s", this.Access, fileName)
}
func (this *Cos) ReadUrl(filePath string) string {
return this.url(filePath)
}
func (this *Cos) Put(fileName string, contentType string, data interface{}) string {
var ossData io.Reader
typeOf := reflect.TypeOf(data).Kind()
//logger.AccessLogger.Infoln("类型:", typeOf)
switch typeOf {
case reflect.Slice:
ossData = bytes.NewBuffer(data.([]byte))
case reflect.Struct:
ossData = data.(io.Reader)
default:
panic("数据不合法!")
}
//oss.SetHeader("content-type", contentType)
_, err := this.client.Object.Put(context.Background(), fileName, ossData, nil)
if err != nil {
logger.AccessLogger.Error("上传失败!")
panic(err.Error())
}
return this.url(fileName)
}
func (this *Cos) Token(key string, contentType string) (map[string]interface{}, error) {
return nil, nil
}