56 lines
1.6 KiB
Go
56 lines
1.6 KiB
Go
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
|
||
}
|