oss.go
2.2 KB
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package aliyun
import (
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"github.com/astaxie/beego"
"io"
)
/*
AK AccessKey 完全访问权限
STS (Security Token Service) 临时访问控制
*/
var (
Endpoint string = beego.AppConfig.String("end_point")
BucketName string = beego.AppConfig.String("bucket_name")
//BucketNameCdn string = beego.AppConfig.String("bucket_name_cdn")
//EndpointCdn string = beego.AppConfig.String("end_point_cdn")
)
type OSSClient struct {
client *oss.Client
Bucket *oss.Bucket
UpAddr UploadAddress
Auth UploadAuth
}
//新建oss-client对象
func NewStsOSSClient(uploadAddress, uploadAuth string) (o *OSSClient, err error) {
addr, e := ParseUploadAddress(uploadAddress)
if e != nil {
err = e
return
}
auth, e := ParseUploadAuth(uploadAuth)
if e != nil {
err = e
return
}
o, err = NewOSSClient(addr.Endpoint, auth.AccessKeyId, auth.AccessKeySecret, auth.SecurityToken)
if err != nil {
return
}
o.UpAddr = addr
o.Auth = auth
return
}
func NewOSSClient(ep, key, secret, token string) (o *OSSClient, err error) {
o = &OSSClient{}
o.client, err = oss.New(ep, key, secret, oss.SecurityToken(token))
if err != nil {
return
}
return
}
//简单上传 (通过文件地址)
func (o *OSSClient) PutObjectByUrl(bucketName string, fileName string, url string, options ...oss.Option) error {
r, err := GetFileFromUrl(url)
if err != nil {
return err
}
return o.PutObjectByBucket(bucketName, fileName, r, options...)
}
func (o *OSSClient) PutObjectByUrlDefault(url string, options ...oss.Option) error {
return o.PutObjectByUrl(o.UpAddr.Bucket, o.UpAddr.FileName, url, options...)
}
//简单上传
func (o *OSSClient) PutObjectByBucket(bucketName, objKey string, r io.Reader, options ...oss.Option) error {
bucket, err := o.client.Bucket(bucketName)
if err != nil {
return err
}
return bucket.PutObject(objKey, r, options...)
}
func (o *OSSClient) SetBucket(bucketName string) error {
bucket, err := o.client.Bucket(bucketName)
if err != nil {
return err
}
o.Bucket = bucket
return nil
}
func (o *OSSClient) PutObject(objKey string, r io.Reader, options ...oss.Option) error {
return o.Bucket.PutObject(objKey, r, options...)
}