kefu/lib/alioss.go

56 lines
1.6 KiB
Go
Raw Normal View History

2024-12-10 02:50:12 +00:00
package lib
import (
"errors"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"kefu/models"
)
type OssLib struct {
EndPoint string
BucketDomain string
Bucket *oss.Bucket
}
func NewOssLib() (*OssLib, error) {
endPoint := models.FindConfig("OSS_ENDPOINT")
accessKeyId := models.FindConfig("OSS_ACCESS_KEY_ID")
accessKeySecret := models.FindConfig("OSS_ACCESS_KEY_SECRET")
ossBucket := models.FindConfig("OSS_BUCKET")
ossBucketDomain := models.FindConfig("OSS_BUCKET_DOMAIN")
if endPoint == "" || accessKeyId == "" || accessKeySecret == "" || ossBucket == "" {
return nil, errors.New("endPoint,accessKeyId,accessKeySecret,ossBucket获取失败!")
}
// 创建OSSClient实例。
// yourEndpoint填写Bucket对应的Endpoint以华东1杭州为例填写为https://oss-cn-hangzhou.aliyuncs.com。其它Region请按实际情况填写。
// 阿里云账号AccessKey拥有所有API的访问权限风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维请登录RAM控制台创建RAM用户。
client, err := oss.New(endPoint, accessKeyId, accessKeySecret)
if err != nil {
return nil, err
}
// 填写存储空间名称例如examplebucket。
bucket, err := client.Bucket(ossBucket)
if err != nil {
return nil, err
}
ossLib := &OssLib{
Bucket: bucket,
BucketDomain: ossBucketDomain,
EndPoint: endPoint,
}
return ossLib, nil
}
func (this *OssLib) Upload(sourcePath, dstPath string) (string, error) {
err := this.Bucket.PutObjectFromFile(dstPath, sourcePath)
if err != nil {
return "", err
}
dstUrl := this.BucketDomain + "/" + dstPath
return dstUrl, nil
}