16 Commits

Author SHA1 Message Date
agin719
c88b73871d Merge pull request #87 from agin719/common-dev
ACL转换
2020-09-29 07:18:24 -05:00
jojoliang
b0a399e92d update travis.yml 2020-09-29 20:12:39 +08:00
jojoliang
5804e86747 update version 2020-09-28 16:14:06 +08:00
jojoliang
cb662cdad5 fix MultiUpload when filesize=0 2020-09-28 12:05:56 +08:00
jojoliang
0e9536d989 多版本删除 2020-09-27 20:33:52 +08:00
jojoliang
0206a7d026 ACL转换 2020-09-27 10:59:53 +08:00
agin719
d5130075f0 Merge pull request #86 from agin719/common-dev
fix bucket encryption & test
2020-09-16 21:50:47 -05:00
jojoliang
eb4e1ac4c9 fix bucket encryption & test 2020-09-17 10:31:44 +08:00
agin719
649bd027d2 Merge pull request #85 from agin719/common-dev
add bucket intelligenttiering
2020-09-14 21:54:45 -05:00
jojoliang
14683910e1 add bucket intelligenttiering 2020-09-14 21:56:24 +08:00
agin719
31af2decf4 Merge pull request #83 from agin719/common-dev
x-cos-copy-source urlencode修正
2020-08-31 08:52:47 -05:00
jojoliang
17c5ed144f x-cos-copy-source urlencode修正 2020-08-31 21:49:52 +08:00
agin719
e870e71637 Merge pull request #82 from agin719/common-dev
Common dev
2020-06-10 06:21:32 -05:00
jojoliang
f9f617878d add host to signature 2020-06-10 19:16:45 +08:00
agin719
7b799aff21 Merge pull request #80 from agin719/common-dev
add object tagging && bucket origin && add stsv3 demo
2020-06-04 02:29:57 -05:00
jojoliang
a0ab0eb0f8 add object tagging && bucket origin && add stsv3 demo 2020-06-04 15:00:35 +08:00
17 changed files with 718 additions and 30 deletions

View File

@@ -1,11 +1,5 @@
language: go
go:
- '1.7'
- '1.8'
- '1.9'
- 1.10.x
- 1.11.x
- 1.12.x
- master
sudo: false
before_install:

View File

@@ -125,6 +125,7 @@ func newAuthorization(secretID, secretKey string, req *http.Request, authTime *A
keyTime := authTime.keyString()
signKey := calSignKey(secretKey, keyTime)
req.Header.Set("Host", req.Host)
formatHeaders := *new(string)
signedHeaderList := *new([]string)
formatHeaders, signedHeaderList = genFormatHeaders(req.Header)

View File

@@ -6,7 +6,7 @@ import (
)
// BucketGetACLResult is same to the ACLXml
type BucketGetACLResult ACLXml
type BucketGetACLResult = ACLXml
// GetACL 使用API读取Bucket的ACL表只有所有者有权操作。
//
@@ -20,6 +20,9 @@ func (s *BucketService) GetACL(ctx context.Context) (*BucketGetACLResult, *Respo
result: &res,
}
resp, err := s.client.send(ctx, &sendOpt)
if err == nil {
decodeACL(resp, &res)
}
return &res, resp, err
}

View File

@@ -12,7 +12,7 @@ type BucketEncryptionConfiguration struct {
type BucketPutEncryptionOptions struct {
XMLName xml.Name `xml:"ServerSideEncryptionConfiguration"`
Rule *BucketEncryptionConfiguration `xml:"Rule>ApplySideEncryptionConfiguration"`
Rule *BucketEncryptionConfiguration `xml:"Rule>ApplyServerSideEncryptionByDefault"`
}
type BucketGetEncryptionResult BucketPutEncryptionOptions

View File

@@ -21,9 +21,9 @@ func TestBucketService_GetEncryption(t *testing.T) {
testFormValues(t, r, vs)
fmt.Fprint(w, `<ServerSideEncryptionConfiguration>
<Rule>
<ApplySideEncryptionConfiguration>
<ApplyServerSideEncryptionByDefault>
<SSEAlgorithm>AES256</SSEAlgorithm>
</ApplySideEncryptionConfiguration>
</ApplyServerSideEncryptionByDefault>
</Rule>
</ServerSideEncryptionConfiguration>`)

View File

@@ -0,0 +1,47 @@
package cos
import (
"context"
"encoding/xml"
"net/http"
)
type BucketIntelligentTieringTransition struct {
Days int `xml:"Days,omitempty"`
RequestFrequent int `xml:"RequestFrequent,omitempty"`
}
type BucketPutIntelligentTieringOptions struct {
XMLName xml.Name `xml:"IntelligentTieringConfiguration"`
Status string `xml:"Status,omitempty"`
Transition *BucketIntelligentTieringTransition `xml:"Transition,omitempty"`
}
type BucketGetIntelligentTieringResult BucketPutIntelligentTieringOptions
func (s *BucketService) PutIntelligentTiering(ctx context.Context, opt *BucketPutIntelligentTieringOptions) (*Response, error) {
if opt != nil && opt.Transition != nil {
opt.Transition.RequestFrequent = 1
}
sendOpt := sendOptions{
baseURL: s.client.BaseURL.BucketURL,
uri: "/?intelligenttiering",
method: http.MethodPut,
body: opt,
}
resp, err := s.client.send(ctx, &sendOpt)
return resp, err
}
func (s *BucketService) GetIntelligentTiering(ctx context.Context) (*BucketGetIntelligentTieringResult, *Response, error) {
var res BucketGetIntelligentTieringResult
sendOpt := sendOptions{
baseURL: s.client.BaseURL.BucketURL,
uri: "/?intelligenttiering",
method: http.MethodGet,
result: &res,
}
resp, err := s.client.send(ctx, &sendOpt)
return &res, resp, err
}

View File

@@ -0,0 +1,76 @@
package cos
import (
"context"
"encoding/xml"
"fmt"
"net/http"
"reflect"
"testing"
)
func TestBucketService_PutIntelligentTiering(t *testing.T) {
setup()
defer teardown()
opt := &BucketPutIntelligentTieringOptions{
Status: "Enabled",
Transition: &BucketIntelligentTieringTransition{
Days: 30,
},
}
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, http.MethodPut)
vs := values{
"intelligenttiering": "",
}
testFormValues(t, r, vs)
body := &BucketPutIntelligentTieringOptions{}
xml.NewDecoder(r.Body).Decode(body)
want := opt
want.XMLName = xml.Name{Local: "IntelligentTieringConfiguration"}
if !reflect.DeepEqual(want, body) {
t.Fatalf("Bucket.PutIntelligentTiering request\n body: %+v\n, want %+v\n", body, want)
}
})
_, err := client.Bucket.PutIntelligentTiering(context.Background(), opt)
if err != nil {
t.Fatalf("Bucket.PutIntelligentTiering failed, error: %v", err)
}
}
func TestBucketService_GetIntelligentTiering(t *testing.T) {
setup()
defer teardown()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, http.MethodGet)
vs := values{
"intelligenttiering": "",
}
testFormValues(t, r, vs)
fmt.Fprint(w, `<IntelligentTieringConfiguration>
<Status>Enabled</Status>
<Transition>
<Days>30</Days>
</Transition>
</IntelligentTieringConfiguration>`)
})
res, _, err := client.Bucket.GetIntelligentTiering(context.Background())
if err != nil {
t.Fatalf("Bucket.GetIntelligentTiering failed, error: %v", err)
}
want := &BucketGetIntelligentTieringResult{
XMLName: xml.Name{Local: "IntelligentTieringConfiguration"},
Status: "Enabled",
Transition: &BucketIntelligentTieringTransition{
Days: 30,
},
}
if !reflect.DeepEqual(res, want) {
t.Errorf("Bucket.GetIntelligentTiering returned\n%+v, want\n%+v", res, want)
}
}

90
bucket_origin.go Normal file
View File

@@ -0,0 +1,90 @@
package cos
import (
"context"
"encoding/xml"
"net/http"
)
type BucketPutOriginOptions struct {
XMLName xml.Name `xml:"OriginConfiguration"`
Rule []BucketOriginRule `xml:"OriginRule"`
}
type BucketOriginRule struct {
OriginType string `xml:"OriginType"`
OriginCondition *BucketOriginCondition `xml:"OriginCondition"`
OriginParameter *BucketOriginParameter `xml:"OriginParameter"`
OriginInfo *BucketOriginInfo `xml:"OriginInfo"`
}
type BucketOriginCondition struct {
HTTPStatusCode string `xml:"HTTPStatusCode,omitempty"`
Prefix string `xml:"Prefix,omitempty"`
}
type BucketOriginParameter struct {
Protocol string `xml:"Protocol,omitempty"`
FollowQueryString bool `xml:"FollowQueryString,omitempty"`
HttpHeader *BucketOriginHttpHeader `xml:"HttpHeader,omitempty"`
FollowRedirection bool `xml:"FollowRedirection,omitempty"`
HttpRedirectCode string `xml:"HttpRedirectCode,omitempty"`
CopyOriginData bool `xml:"CopyOriginData,omitempty"`
}
type BucketOriginHttpHeader struct {
// 目前还不支持 FollowAllHeaders
// FollowAllHeaders bool `xml:"FollowAllHeaders,omitempty"`
NewHttpHeaders []OriginHttpHeader `xml:"NewHttpHeaders>Header,omitempty"`
FollowHttpHeaders []OriginHttpHeader `xml:"FollowHttpHeaders>Header,omitempty"`
}
type OriginHttpHeader struct {
Key string `xml:"Key,omitempty"`
Value string `xml:"Value,omitempty"`
}
type BucketOriginInfo struct {
HostInfo string `xml:"HostInfo>HostName,omitempty"`
FileInfo *BucketOriginFileInfo `xml:"FileInfo,omitempty"`
}
type BucketOriginFileInfo struct {
PrefixDirective bool `xml:"PrefixDirective,omitempty"`
Prefix string `xml:"Prefix,omitempty"`
Suffix string `xml:"Suffix,omitempty"`
}
type BucketGetOriginResult BucketPutOriginOptions
func (s *BucketService) PutOrigin(ctx context.Context, opt *BucketPutOriginOptions) (*Response, error) {
sendOpt := &sendOptions{
baseURL: s.client.BaseURL.BucketURL,
uri: "/?origin",
method: http.MethodPut,
body: opt,
}
resp, err := s.client.send(ctx, sendOpt)
return resp, err
}
func (s *BucketService) GetOrigin(ctx context.Context) (*BucketGetOriginResult, *Response, error) {
var res BucketGetOriginResult
sendOpt := &sendOptions{
baseURL: s.client.BaseURL.BucketURL,
uri: "/?origin",
method: http.MethodGet,
result: &res,
}
resp, err := s.client.send(ctx, sendOpt)
return &res, resp, err
}
func (s *BucketService) DeleteOrigin(ctx context.Context) (*Response, error) {
sendOpt := &sendOptions{
baseURL: s.client.BaseURL.BucketURL,
uri: "/?origin",
method: http.MethodDelete,
}
resp, err := s.client.send(ctx, sendOpt)
return resp, err
}

55
cos.go
View File

@@ -11,6 +11,7 @@ import (
"net/http"
"net/url"
"reflect"
"strings"
"text/template"
"strconv"
@@ -21,7 +22,7 @@ import (
const (
// Version current go sdk version
Version = "0.7.6"
Version = "0.7.10"
userAgent = "cos-go-sdk-v5/" + Version
contentTypeXML = "application/xml"
defaultServiceBaseURL = "http://service.cos.myqcloud.com"
@@ -329,6 +330,8 @@ type ACLHeaderOptions struct {
XCosGrantRead string `header:"x-cos-grant-read,omitempty" url:"-" xml:"-"`
XCosGrantWrite string `header:"x-cos-grant-write,omitempty" url:"-" xml:"-"`
XCosGrantFullControl string `header:"x-cos-grant-full-control,omitempty" url:"-" xml:"-"`
XCosGrantReadACP string `header:"x-cos-grant-read-acp,omitempty" url:"-" xml:"-"`
XCosGrantWriteACP string `header:"x-cos-grant-write-acp,omitempty" url:"-" xml:"-"`
}
// ACLGrantee is the param of ACLGrant
@@ -353,3 +356,53 @@ type ACLXml struct {
Owner *Owner
AccessControlList []ACLGrant `xml:"AccessControlList>Grant,omitempty"`
}
func decodeACL(resp *Response, res *ACLXml) {
ItemMap := map[string]string{
"ACL": "x-cos-acl",
"READ": "x-cos-grant-read",
"WRITE": "x-cos-grant-write",
"READ_ACP": "x-cos-grant-read-acp",
"WRITE_ACP": "x-cos-grant-write-acp",
"FULL_CONTROL": "x-cos-grant-full-control",
}
publicACL := make(map[string]int)
resACL := make(map[string][]string)
for _, item := range res.AccessControlList {
if item.Grantee == nil {
continue
}
if item.Grantee.ID == "qcs::cam::anyone:anyone" || item.Grantee.URI == "http://cam.qcloud.com/groups/global/AllUsers" {
publicACL[item.Permission] = 1
} else if item.Grantee.ID != res.Owner.ID {
resACL[item.Permission] = append(resACL[item.Permission], "id=\""+item.Grantee.ID+"\"")
}
}
if publicACL["FULL_CONTROL"] == 1 || (publicACL["READ"] == 1 && publicACL["WRITE"] == 1) {
resACL["ACL"] = []string{"public-read-write"}
} else if publicACL["READ"] == 1 {
resACL["ACL"] = []string{"public-read"}
} else {
resACL["ACL"] = []string{"private"}
}
for item, header := range ItemMap {
if len(resp.Header.Get(header)) > 0 || len(resACL[item]) == 0 {
continue
}
resp.Header.Set(header, uniqueGrantID(resACL[item]))
}
}
func uniqueGrantID(grantIDs []string) string {
res := []string{}
filter := make(map[string]int)
for _, id := range grantIDs {
if filter[id] != 0 {
continue
}
filter[id] = 1
res = append(res, id)
}
return strings.Join(res, ",")
}

View File

@@ -61,9 +61,9 @@ const (
kRepRegion = "ap-chengdu"
// Batch测试需要的源存储桶和目标存储桶目前只在成都、重庆地域公测
kBatchBucket = "testcd-1259654469"
kTargetBatchBucket = "cosgosdkreptest-1259654469" //复用了存储桶
kBatchRegion = "ap-chengdu"
kBatchBucket = "cosgosdktest-1259654469"
kTargetBatchBucket = "cosgosdktest-1259654469" //复用了存储桶
kBatchRegion = "ap-guangzhou"
)
func (s *CosTestSuite) SetupSuite() {
@@ -812,7 +812,7 @@ func (s *CosTestSuite) TestBatch() {
assert.Equal(s.T(), res3.Priority, 3, "priority not right")
// 等待状态变成Suspended
for i := 0; i < 10; i = i + 1 {
for i := 0; i < 50; i = i + 1 {
res, _, err := client.Batch.DescribeJob(context.Background(), jobid, headers)
assert.Nil(s.T(), err, "describe job Failed")
assert.Equal(s.T(), res2.Job.ConfirmationRequired, "true", "ConfirmationRequired not right")

View File

@@ -0,0 +1,64 @@
package main
import (
"context"
"fmt"
"net/http"
"net/url"
"os"
"github.com/tencentyun/cos-go-sdk-v5"
"github.com/tencentyun/cos-go-sdk-v5/debug"
)
func log_status(err error) {
if err == nil {
return
}
if cos.IsNotFoundError(err) {
// WARN
fmt.Println("Resource is not existed")
} else if e, ok := cos.IsCOSError(err); ok {
fmt.Printf("Code: %v\n", e.Code)
fmt.Printf("Message: %v\n", e.Message)
fmt.Printf("Resource: %v\n", e.Resource)
fmt.Printf("RequestId: %v\n", e.RequestID)
// ERROR
} else {
fmt.Println(err)
// ERROR
}
}
func main() {
u, _ := url.Parse("https://test-1259654469.cos.ap-guangzhou.myqcloud.com")
b := &cos.BaseURL{
BucketURL: u,
}
c := cos.NewClient(b, &http.Client{
Transport: &cos.AuthorizationTransport{
SecretID: os.Getenv("COS_SECRETID"),
SecretKey: os.Getenv("COS_SECRETKEY"),
Transport: &debug.DebugRequestTransport{
RequestHeader: true,
RequestBody: false,
ResponseHeader: true,
ResponseBody: false,
},
},
})
opt := &cos.BucketPutIntelligentTieringOptions {
Status: "Enabled",
Transition: &cos.BucketIntelligentTieringTransition {
Days: 30,
},
}
_, err := c.Bucket.PutIntelligentTiering(context.Background(), opt)
log_status(err)
res, _, err := c.Bucket.GetIntelligentTiering(context.Background())
log_status(err)
fmt.Printf("%+v\n", res)
fmt.Printf("%+v\n", res.Status)
fmt.Printf("%+v\n", res.Transition.Days)
}

92
example/bucket/origin.go Normal file
View File

@@ -0,0 +1,92 @@
package main
import (
"context"
"fmt"
"net/http"
"net/url"
"os"
"github.com/tencentyun/cos-go-sdk-v5"
"github.com/tencentyun/cos-go-sdk-v5/debug"
)
func log_status(err error) {
if err == nil {
return
}
if cos.IsNotFoundError(err) {
// WARN
fmt.Println("Resource is not existed")
} else if e, ok := cos.IsCOSError(err); ok {
fmt.Printf("Code: %v\n", e.Code)
fmt.Printf("Message: %v\n", e.Message)
fmt.Printf("Resource: %v\n", e.Resource)
fmt.Printf("RequestId: %v\n", e.RequestID)
// ERROR
} else {
fmt.Println(err)
// ERROR
}
}
func main() {
u, _ := url.Parse("https://test-1259654469.cos.ap-guangzhou.myqcloud.com")
b := &cos.BaseURL{
BucketURL: u,
}
c := cos.NewClient(b, &http.Client{
Transport: &cos.AuthorizationTransport{
SecretID: os.Getenv("COS_SECRETID"),
SecretKey: os.Getenv("COS_SECRETKEY"),
Transport: &debug.DebugRequestTransport{
RequestHeader: true,
RequestBody: true,
ResponseHeader: true,
ResponseBody: true,
},
},
})
opt := &cos.BucketPutOriginOptions{
Rule: []cos.BucketOriginRule{
{
OriginType: "Proxy",
OriginCondition: &cos.BucketOriginCondition{
HTTPStatusCode: "404",
Prefix: "",
},
OriginParameter: &cos.BucketOriginParameter{
Protocol: "FOLLOW",
FollowQueryString: true,
HttpHeader: &cos.BucketOriginHttpHeader{
NewHttpHeaders: []cos.OriginHttpHeader{
{
Key: "x-cos-ContentType",
Value: "csv",
},
},
FollowHttpHeaders: []cos.OriginHttpHeader{
{
Key: "Content-Type",
},
},
},
FollowRedirection: true,
},
OriginInfo: &cos.BucketOriginInfo{
HostInfo: "examplebucket-1250000000.cos.ap-shanghai.myqcloud.com",
},
},
},
}
_, err := c.Bucket.PutOrigin(context.Background(), opt)
log_status(err)
res, _, err := c.Bucket.GetOrigin(context.Background())
log_status(err)
fmt.Printf("%+v\n", res)
fmt.Printf("%+v\n", res.Rule)
_, err = c.Bucket.DeleteOrigin(context.Background())
log_status(err)
}

75
example/object/tagging.go Normal file
View File

@@ -0,0 +1,75 @@
package main
import (
"context"
"fmt"
"net/url"
"os"
"net/http"
"github.com/tencentyun/cos-go-sdk-v5"
"github.com/tencentyun/cos-go-sdk-v5/debug"
)
func log_status(err error) {
if err == nil {
return
}
if cos.IsNotFoundError(err) {
// WARN
fmt.Println("WARN: Resource is not existed")
} else if e, ok := cos.IsCOSError(err); ok {
fmt.Printf("ERROR: Code: %v\n", e.Code)
fmt.Printf("ERROR: Message: %v\n", e.Message)
fmt.Printf("ERROR: Resource: %v\n", e.Resource)
fmt.Printf("ERROR: RequestId: %v\n", e.RequestID)
// ERROR
} else {
fmt.Printf("ERROR: %v\n", err)
// ERROR
}
}
func main() {
u, _ := url.Parse("https://test-1259654469.cos.ap-guangzhou.myqcloud.com")
b := &cos.BaseURL{
BucketURL: u,
}
c := cos.NewClient(b, &http.Client{
Transport: &cos.AuthorizationTransport{
SecretID: os.Getenv("COS_SECRETID"),
SecretKey: os.Getenv("COS_SECRETKEY"),
Transport: &debug.DebugRequestTransport{
RequestHeader: true,
RequestBody: true,
ResponseHeader: true,
ResponseBody: true,
},
},
})
name := "test"
opt := &cos.ObjectPutTaggingOptions{
TagSet: []cos.ObjectTaggingTag{
{
Key: "test_k2",
Value: "test_v2",
},
{
Key: "test_k3",
Value: "test_v3",
},
},
}
_, err := c.Object.PutTagging(context.Background(), name, opt)
log_status(err)
res, _, err := c.Object.GetTagging(context.Background(), name)
log_status(err)
fmt.Printf("%v\n", res.TagSet)
_, err = c.Object.DeleteTagging(context.Background(), name)
log_status(err)
}

96
example/sts/sts_v3.go Normal file
View File

@@ -0,0 +1,96 @@
package main
import (
"context"
"fmt"
"github.com/tencentyun/cos-go-sdk-v5"
"github.com/tencentyun/cos-go-sdk-v5/debug"
"github.com/tencentyun/qcloud-cos-sts-sdk/go"
"net/http"
"net/url"
"os"
"strings"
"time"
)
func main() {
appid := "1259654469"
bucket := "test-1259654469"
c := sts.NewClient(
os.Getenv("COS_SECRETID"),
os.Getenv("COS_SECRETKEY"),
nil,
)
opt := &sts.CredentialOptions{
DurationSeconds: int64(time.Hour.Seconds()),
Region: "ap-guangzhou",
Policy: &sts.CredentialPolicy{
Statement: []sts.CredentialPolicyStatement{
{
Action: []string{
"name/cos:PostObject",
"name/cos:PutObject",
"name/cos:GetObject",
},
Effect: "allow",
Resource: []string{
//这里改成允许的路径前缀,可以根据自己网站的用户登录态判断允许上传的具体路径,例子: a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
"qcs::cos:ap-guangzhou:uid/" + appid + ":" + bucket + "/exampleobject",
},
},
},
},
}
res, err := c.GetCredential(opt)
if err != nil {
panic(err)
}
fmt.Printf("%+v\n", res.Credentials)
//获取临时ak、sk、token
tAk := res.Credentials.TmpSecretID
tSk := res.Credentials.TmpSecretKey
token := res.Credentials.SessionToken
u, _ := url.Parse("https://" + bucket + ".cos.ap-guangzhou.myqcloud.com")
b := &cos.BaseURL{BucketURL: u}
client := cos.NewClient(b, &http.Client{
Transport: &cos.AuthorizationTransport{
// 使用临时密钥
SecretID: tAk,
SecretKey: tSk,
SessionToken: token,
Transport: &debug.DebugRequestTransport{
RequestHeader: true,
RequestBody: true,
ResponseHeader: true,
ResponseBody: true,
},
},
})
name := "exampleobject"
f := strings.NewReader("test")
_, err = client.Object.Put(context.Background(), name, f, nil)
if err != nil {
panic(err)
}
name = "exampleobject"
f = strings.NewReader("test xxx")
optc := &cos.ObjectPutOptions{
ObjectPutHeaderOptions: &cos.ObjectPutHeaderOptions{
ContentType: "text/html",
},
ACLHeaderOptions: &cos.ACLHeaderOptions{
//XCosACL: "public-read",
XCosACL: "private",
},
}
_, err = client.Object.Put(context.Background(), name, f, optc)
if err != nil {
panic(err)
}
}

104
object.go
View File

@@ -10,6 +10,7 @@ import (
"net/url"
"os"
"sort"
"strings"
"time"
)
@@ -236,11 +237,15 @@ type ObjectCopyResult struct {
//
// https://cloud.tencent.com/document/product/436/10881
func (s *ObjectService) Copy(ctx context.Context, name, sourceURL string, opt *ObjectCopyOptions, id ...string) (*ObjectCopyResult, *Response, error) {
surl := strings.SplitN(sourceURL, "/", 2)
if len(surl) < 2 {
return nil, nil, errors.New(fmt.Sprintf("x-cos-copy-source format error: %s", sourceURL))
}
var u string
if len(id) == 1 {
u = fmt.Sprintf("%s?versionId=%s", encodeURIComponent(sourceURL), id[0])
u = fmt.Sprintf("%s/%s?versionId=%s", surl[0], encodeURIComponent(surl[1]), id[0])
} else if len(id) == 0 {
u = encodeURIComponent(sourceURL)
u = fmt.Sprintf("%s/%s", surl[0], encodeURIComponent(surl[1]))
} else {
return nil, nil, errors.New("wrong params")
}
@@ -279,7 +284,9 @@ type ObjectDeleteOptions struct {
XCosSSECustomerKeyMD5 string `header:"x-cos-server-side-encryption-customer-key-MD5,omitempty" url:"-" xml:"-"`
//兼容其他自定义头部
XOptionHeader *http.Header `header:"-,omitempty" url:"-" xml:"-"`
VersionId string `header:"-" url:"VersionId,omitempty" xml:"-"`
}
// Delete Object请求可以将一个文件Object删除。
//
// https://www.qcloud.com/document/product/436/7743
@@ -298,6 +305,7 @@ func (s *ObjectService) Delete(ctx context.Context, name string, opt ...*ObjectD
uri: "/" + encodeURIComponent(name),
method: http.MethodDelete,
optHeader: optHeader,
optQuery: optHeader,
}
resp, err := s.client.send(ctx, &sendOpt)
return resp, err
@@ -434,9 +442,10 @@ type ObjectDeleteMultiResult struct {
XMLName xml.Name `xml:"DeleteResult"`
DeletedObjects []Object `xml:"Deleted,omitempty"`
Errors []struct {
Key string
Code string
Message string
Key string `xml:",omitempty"`
Code string `xml:",omitempty"`
Message string `xml:",omitempty"`
VersionId string `xml:",omitempty"`
} `xml:"Error,omitempty"`
}
@@ -466,6 +475,7 @@ type Object struct {
LastModified string `xml:",omitempty"`
StorageClass string `xml:",omitempty"`
Owner *Owner `xml:",omitempty"`
VersionId string `xml:",omitempty"`
}
// MultiUploadOptions is the option of the multiupload,
@@ -610,6 +620,24 @@ func (s *ObjectService) Upload(ctx context.Context, name string, filepath string
if err != nil {
return nil, nil, err
}
if partNum == 0 {
var opt0 *ObjectPutOptions
if opt.OptIni != nil {
opt0 = &ObjectPutOptions{
opt.OptIni.ACLHeaderOptions,
opt.OptIni.ObjectPutHeaderOptions,
}
}
rsp, err := s.PutFromFile(ctx, name, filepath, opt0)
if err != nil {
return nil, rsp, err
}
result := &CompleteMultipartUploadResult{
Key: name,
ETag: rsp.Header.Get("ETag"),
}
return result, rsp, nil
}
// 2.Init
optini := opt.OptIni
@@ -675,3 +703,69 @@ func (s *ObjectService) Upload(ctx context.Context, name string, filepath string
return v, resp, err
}
type ObjectPutTaggingOptions struct {
XMLName xml.Name `xml:"Tagging"`
TagSet []ObjectTaggingTag `xml:"TagSet>Tag,omitempty"`
}
type ObjectTaggingTag BucketTaggingTag
type ObjectGetTaggingResult ObjectPutTaggingOptions
func (s *ObjectService) PutTagging(ctx context.Context, name string, opt *ObjectPutTaggingOptions, id ...string) (*Response, error) {
var u string
if len(id) == 1 {
u = fmt.Sprintf("/%s?tagging&versionId=%s", encodeURIComponent(name), id[0])
} else if len(id) == 0 {
u = fmt.Sprintf("/%s?tagging", encodeURIComponent(name))
} else {
return nil, errors.New("wrong params")
}
sendOpt := &sendOptions{
baseURL: s.client.BaseURL.BucketURL,
uri: u,
method: http.MethodPut,
body: opt,
}
resp, err := s.client.send(ctx, sendOpt)
return resp, err
}
func (s *ObjectService) GetTagging(ctx context.Context, name string, id ...string) (*ObjectGetTaggingResult, *Response, error) {
var u string
if len(id) == 1 {
u = fmt.Sprintf("/%s?tagging&versionId=%s", encodeURIComponent(name), id[0])
} else if len(id) == 0 {
u = fmt.Sprintf("/%s?tagging", encodeURIComponent(name))
} else {
return nil, nil, errors.New("wrong params")
}
var res ObjectGetTaggingResult
sendOpt := &sendOptions{
baseURL: s.client.BaseURL.BucketURL,
uri: u,
method: http.MethodGet,
result: &res,
}
resp, err := s.client.send(ctx, sendOpt)
return &res, resp, err
}
func (s *ObjectService) DeleteTagging(ctx context.Context, name string, id ...string) (*Response, error) {
var u string
if len(id) == 1 {
u = fmt.Sprintf("/%s?tagging&versionId=%s", encodeURIComponent(name), id[0])
} else if len(id) == 0 {
u = fmt.Sprintf("/%s?tagging", encodeURIComponent(name))
} else {
return nil, errors.New("wrong params")
}
sendOpt := &sendOptions{
baseURL: s.client.BaseURL.BucketURL,
uri: u,
method: http.MethodDelete,
}
resp, err := s.client.send(ctx, sendOpt)
return resp, err
}

View File

@@ -6,7 +6,7 @@ import (
)
// ObjectGetACLResult is the result of GetObjectACL
type ObjectGetACLResult ACLXml
type ObjectGetACLResult = ACLXml
// GetACL Get Object ACL接口实现使用API读取Object的ACL表只有所有者有权操作。
//
@@ -20,6 +20,9 @@ func (s *ObjectService) GetACL(ctx context.Context, name string) (*ObjectGetACLR
result: &res,
}
resp, err := s.client.send(ctx, &sendOpt)
if err == nil {
decodeACL(resp, &res)
}
return &res, resp, err
}