-
Notifications
You must be signed in to change notification settings - Fork 92
/
object.go
1980 lines (1837 loc) · 60.3 KB
/
object.go
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package cos
import (
"bytes"
"context"
"crypto/md5"
"encoding/hex"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"hash/crc64"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"sort"
"strconv"
"strings"
"time"
)
// ObjectService 相关 API
type ObjectService service
// ObjectGetOptions is the option of GetObject
type ObjectGetOptions struct {
ResponseContentType string `url:"response-content-type,omitempty" header:"-"`
ResponseContentLanguage string `url:"response-content-language,omitempty" header:"-"`
ResponseExpires string `url:"response-expires,omitempty" header:"-"`
ResponseCacheControl string `url:"response-cache-control,omitempty" header:"-"`
ResponseContentDisposition string `url:"response-content-disposition,omitempty" header:"-"`
ResponseContentEncoding string `url:"response-content-encoding,omitempty" header:"-"`
Range string `url:"-" header:"Range,omitempty"`
IfModifiedSince string `url:"-" header:"If-Modified-Since,omitempty"`
// SSE-C
XCosSSECustomerAglo string `header:"x-cos-server-side-encryption-customer-algorithm,omitempty" url:"-" xml:"-"`
XCosSSECustomerKey string `header:"x-cos-server-side-encryption-customer-key,omitempty" url:"-" xml:"-"`
XCosSSECustomerKeyMD5 string `header:"x-cos-server-side-encryption-customer-key-MD5,omitempty" url:"-" xml:"-"`
//兼容其他自定义头部
XOptionHeader *http.Header `header:"-,omitempty" url:"-" xml:"-"`
XCosTrafficLimit int `header:"x-cos-traffic-limit,omitempty" url:"-" xml:"-"`
// 下载进度, ProgressCompleteEvent不能表示对应API调用成功,API是否调用成功的判断标准为返回err==nil
Listener ProgressListener `header:"-" url:"-" xml:"-"`
}
// presignedURLTestingOptions is the opt of presigned url
type presignedURLTestingOptions struct {
authTime *AuthTime
}
// Get Object 请求可以将一个文件(Object)下载至本地。
// 该操作需要对目标 Object 具有读权限或目标 Object 对所有人都开放了读权限(公有读)。
//
// https://www.qcloud.com/document/product/436/7753
func (s *ObjectService) Get(ctx context.Context, name string, opt *ObjectGetOptions, id ...string) (*Response, error) {
if s.client.Conf.ObjectKeySimplifyCheck && !CheckObjectKeySimplify("/"+name) {
return nil, ObjectKeySimplifyCheckErr
}
var u string
if len(id) == 1 {
u = fmt.Sprintf("/%s?versionId=%s", encodeURIComponent(name), id[0])
} else if len(id) == 0 {
u = "/" + encodeURIComponent(name)
} else {
return nil, errors.New("wrong params")
}
sendOpt := sendOptions{
baseURL: s.client.BaseURL.BucketURL,
uri: u,
method: http.MethodGet,
optQuery: opt,
optHeader: opt,
disableCloseBody: true,
}
resp, err := s.client.doRetry(ctx, &sendOpt)
if opt != nil && opt.Listener != nil {
if err == nil && resp != nil {
if totalBytes, e := strconv.ParseInt(resp.Header.Get("Content-Length"), 10, 64); e == nil {
resp.Body = TeeReader(resp.Body, nil, totalBytes, opt.Listener)
}
}
}
return resp, err
}
// GetToFile download the object to local file
func (s *ObjectService) GetToFile(ctx context.Context, name, localpath string, opt *ObjectGetOptions, id ...string) (*Response, error) {
resp, err := s.Get(ctx, name, opt, id...)
if err != nil {
return resp, err
}
defer resp.Body.Close()
// If file exist, overwrite it
fd, err := os.OpenFile(localpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0660)
if err != nil {
return resp, err
}
_, err = io.Copy(fd, resp.Body)
fd.Close()
if err != nil {
return resp, err
}
return resp, nil
}
func (s *ObjectService) GetObjectURL(name string) *url.URL {
uri, _ := url.Parse("/" + encodeURIComponent(name, []byte{'/'}))
return s.client.BaseURL.BucketURL.ResolveReference(uri)
}
type PresignedURLOptions struct {
Query *url.Values `xml:"-" url:"-" header:"-"`
Header *http.Header `header:"-,omitempty" url:"-" xml:"-"`
SignMerged bool `xml:"-" url:"-" header:"-"`
AuthTime *AuthTime `xml:"-" url:"-" header:"-"`
EncodeDelimiter bool `xml:"-" url:"-" header:"-"`
}
// GetPresignedURL get the object presigned to down or upload file by url
// 预签名函数,signHost: 默认签入Header Host, 您也可以选择不签入Header Host,但可能导致请求失败或安全漏洞
func (s *ObjectService) GetPresignedURL(ctx context.Context, httpMethod, name, ak, sk string, expired time.Duration, opt interface{}, signHost ...bool) (*url.URL, error) {
if name == "" {
return nil, fmt.Errorf("object key is empty.")
}
// 兼容 name 以 / 开头的情况
if strings.HasPrefix(name, "/") {
name = encodeURIComponent("/") + encodeURIComponent(name[1:], []byte{'/'})
} else {
name = encodeURIComponent(name, []byte{'/'})
}
sendOpt := sendOptions{
baseURL: s.client.BaseURL.BucketURL,
uri: "/" + name,
method: httpMethod,
optQuery: opt,
optHeader: opt,
}
var authTime *AuthTime
if opt != nil {
if popt, ok := opt.(*presignedURLTestingOptions); ok {
authTime = popt.authTime
}
if popt, ok := opt.(*PresignedURLOptions); ok {
if popt.Query != nil {
qs := popt.Query.Encode()
if qs != "" {
sendOpt.uri = fmt.Sprintf("%s?%s", sendOpt.uri, qs)
}
}
if popt.AuthTime != nil {
authTime = popt.AuthTime
}
}
}
req, err := s.client.newRequest(ctx, sendOpt.baseURL, sendOpt.uri, sendOpt.method, sendOpt.body, sendOpt.optQuery, sendOpt.optHeader, false)
if err != nil {
return nil, err
}
if authTime == nil {
authTime = NewAuthTime(expired)
}
signedHost := true
if len(signHost) > 0 {
signedHost = signHost[0]
}
authorization := newAuthorization(ak, sk, req, authTime, signedHost)
if opt != nil {
if opt, ok := opt.(*PresignedURLOptions); ok {
if opt.SignMerged {
sign := encodeURIComponent(authorization)
if req.URL.RawQuery == "" {
req.URL.RawQuery = fmt.Sprintf("sign=%s", sign)
} else {
req.URL.RawQuery = fmt.Sprintf("%s&sign=%s", req.URL.RawQuery, sign)
}
return req.URL, nil
}
}
}
sign := encodeURIComponent(authorization, []byte{'&', '='})
if req.URL.RawQuery == "" {
req.URL.RawQuery = fmt.Sprintf("%s", sign)
} else {
req.URL.RawQuery = fmt.Sprintf("%s&%s", req.URL.RawQuery, sign)
}
return req.URL, nil
}
func (s *ObjectService) GetPresignedURL2(ctx context.Context, httpMethod, name string, expired time.Duration, opt interface{}, signHost ...bool) (*url.URL, error) {
if name == "" {
return nil, fmt.Errorf("object key is empty.")
}
// 兼容 name 以 / 开头的情况
if strings.HasPrefix(name, "/") {
name = encodeURIComponent("/") + encodeURIComponent(name[1:], []byte{'/'})
} else {
name = encodeURIComponent(name, []byte{'/'})
}
cred := s.client.GetCredential()
if cred == nil {
return nil, fmt.Errorf("GetCredential failed")
}
sendOpt := sendOptions{
baseURL: s.client.BaseURL.BucketURL,
uri: "/" + name,
method: httpMethod,
optQuery: opt,
optHeader: opt,
}
var authTime *AuthTime
mark := "?"
if opt != nil {
if popt, ok := opt.(*presignedURLTestingOptions); ok {
authTime = popt.authTime
}
if popt, ok := opt.(*PresignedURLOptions); ok {
if popt.Query != nil {
qs := popt.Query.Encode()
if qs != "" {
sendOpt.uri = fmt.Sprintf("%s?%s", sendOpt.uri, qs)
mark = "&"
}
}
if popt.AuthTime != nil {
authTime = popt.AuthTime
}
}
}
if cred.SessionToken != "" {
sendOpt.uri = fmt.Sprintf("%s%s%s", sendOpt.uri, mark, url.Values{"x-cos-security-token": []string{cred.SessionToken}}.Encode())
}
req, err := s.client.newRequest(ctx, sendOpt.baseURL, sendOpt.uri, sendOpt.method, sendOpt.body, sendOpt.optQuery, sendOpt.optHeader, false)
if err != nil {
return nil, err
}
if authTime == nil {
authTime = NewAuthTime(expired)
}
signedHost := true
if len(signHost) > 0 {
signedHost = signHost[0]
}
authorization := newAuthorization(cred.SecretID, cred.SecretKey, req, authTime, signedHost)
if opt != nil {
if opt, ok := opt.(*PresignedURLOptions); ok {
if opt.SignMerged {
sign := encodeURIComponent(authorization)
if req.URL.RawQuery == "" {
req.URL.RawQuery = fmt.Sprintf("sign=%s", sign)
} else {
req.URL.RawQuery = fmt.Sprintf("%s&sign=%s", req.URL.RawQuery, sign)
}
return req.URL, nil
}
}
}
sign := encodeURIComponent(authorization, []byte{'&', '='})
if req.URL.RawQuery == "" {
req.URL.RawQuery = fmt.Sprintf("%s", sign)
} else {
req.URL.RawQuery = fmt.Sprintf("%s&%s", req.URL.RawQuery, sign)
}
return req.URL, nil
}
func (s *ObjectService) GetPresignedURL3(ctx context.Context, httpMethod, name string, expired time.Duration, opt interface{}, signHost ...bool) (*url.URL, error) {
if name == "" {
return nil, fmt.Errorf("object key is empty.")
}
var encodeDelimiter bool
if opt != nil {
if popt, ok := opt.(*PresignedURLOptions); ok {
encodeDelimiter = popt.EncodeDelimiter
}
}
if encodeDelimiter {
name = encodeURIComponent(name)
} else {
name = encodeURIComponent(name, []byte("/"))
}
cred := s.client.GetCredential()
if cred == nil {
return nil, fmt.Errorf("GetCredential failed")
}
sendOpt := sendOptions{
baseURL: s.client.BaseURL.BucketURL,
uri: "/" + name,
method: httpMethod,
optQuery: opt,
optHeader: opt,
}
var authTime *AuthTime
mark := "?"
if opt != nil {
if popt, ok := opt.(*presignedURLTestingOptions); ok {
authTime = popt.authTime
}
if popt, ok := opt.(*PresignedURLOptions); ok {
if popt.Query != nil {
qs := popt.Query.Encode()
if qs != "" {
sendOpt.uri = fmt.Sprintf("%s?%s", sendOpt.uri, qs)
mark = "&"
}
}
if popt.AuthTime != nil {
authTime = popt.AuthTime
}
}
}
if cred.SessionToken != "" {
sendOpt.uri = fmt.Sprintf("%s%s%s", sendOpt.uri, mark, url.Values{"x-cos-security-token": []string{cred.SessionToken}}.Encode())
}
req, err := s.client.newRequest(ctx, sendOpt.baseURL, sendOpt.uri, sendOpt.method, sendOpt.body, sendOpt.optQuery, sendOpt.optHeader, false)
if err != nil {
return nil, err
}
if authTime == nil {
authTime = NewAuthTime(expired)
}
signedHost := true
if len(signHost) > 0 {
signedHost = signHost[0]
}
authorization := newAuthorization(cred.SecretID, cred.SecretKey, req, authTime, signedHost)
if opt != nil {
if opt, ok := opt.(*PresignedURLOptions); ok {
if opt.SignMerged {
sign := encodeURIComponent(authorization)
if req.URL.RawQuery == "" {
req.URL.RawQuery = fmt.Sprintf("sign=%s", sign)
} else {
req.URL.RawQuery = fmt.Sprintf("%s&sign=%s", req.URL.RawQuery, sign)
}
return req.URL, nil
}
}
}
sign := encodeURIComponent(authorization, []byte{'&', '='})
if req.URL.RawQuery == "" {
req.URL.RawQuery = fmt.Sprintf("%s", sign)
} else {
req.URL.RawQuery = fmt.Sprintf("%s&%s", req.URL.RawQuery, sign)
}
return req.URL, nil
}
func (s *ObjectService) GetSignature(ctx context.Context, httpMethod, name, ak, sk string, expired time.Duration, opt *PresignedURLOptions, signHost ...bool) string {
// 兼容 name 以 / 开头的情况
name = encodeURIComponent(name)
sendOpt := sendOptions{
baseURL: s.client.BaseURL.BucketURL,
uri: "/" + name,
method: httpMethod,
optQuery: opt,
optHeader: opt,
}
if opt != nil && opt.Query != nil {
qs := opt.Query.Encode()
if qs != "" {
sendOpt.uri = fmt.Sprintf("%s?%s", sendOpt.uri, qs)
}
}
req, err := s.client.newRequest(ctx, sendOpt.baseURL, sendOpt.uri, sendOpt.method, sendOpt.body, sendOpt.optQuery, sendOpt.optHeader, false)
if err != nil {
return ""
}
authTime := NewAuthTime(expired)
signedHost := true
if len(signHost) > 0 {
signedHost = signHost[0]
}
authorization := newAuthorization(ak, sk, req, authTime, signedHost)
return authorization
}
// ObjectPutHeaderOptions the options of header of the put object
type ObjectPutHeaderOptions struct {
CacheControl string `header:"Cache-Control,omitempty" url:"-"`
ContentDisposition string `header:"Content-Disposition,omitempty" url:"-"`
ContentEncoding string `header:"Content-Encoding,omitempty" url:"-"`
ContentType string `header:"Content-Type,omitempty" url:"-"`
ContentMD5 string `header:"Content-MD5,omitempty" url:"-"`
ContentLength int64 `header:"Content-Length,omitempty" url:"-"`
ContentLanguage string `header:"Content-Language,omitempty" url:"-"`
Expect string `header:"Expect,omitempty" url:"-"`
Expires string `header:"Expires,omitempty" url:"-"`
XCosContentSHA1 string `header:"x-cos-content-sha1,omitempty" url:"-"`
// 自定义的 x-cos-meta-* header
XCosMetaXXX *http.Header `header:"x-cos-meta-*,omitempty" url:"-"`
XCosStorageClass string `header:"x-cos-storage-class,omitempty" url:"-"`
// 可选值: Normal, Appendable
//XCosObjectType string `header:"x-cos-object-type,omitempty" url:"-"`
// Enable Server Side Encryption, Only supported: AES256
XCosServerSideEncryption string `header:"x-cos-server-side-encryption,omitempty" url:"-" xml:"-"`
// SSE-C
XCosSSECustomerAglo string `header:"x-cos-server-side-encryption-customer-algorithm,omitempty" url:"-" xml:"-"`
XCosSSECustomerKey string `header:"x-cos-server-side-encryption-customer-key,omitempty" url:"-" xml:"-"`
XCosSSECustomerKeyMD5 string `header:"x-cos-server-side-encryption-customer-key-MD5,omitempty" url:"-" xml:"-"`
//兼容其他自定义头部
XOptionHeader *http.Header `header:"-,omitempty" url:"-" xml:"-"`
XCosTrafficLimit int `header:"x-cos-traffic-limit,omitempty" url:"-" xml:"-"`
// 上传进度, ProgressCompleteEvent不能表示对应API调用成功,API是否调用成功的判断标准为返回err==nil
Listener ProgressListener `header:"-" url:"-" xml:"-"`
}
// ObjectPutOptions the options of put object
type ObjectPutOptions struct {
*ACLHeaderOptions `header:",omitempty" url:"-" xml:"-"`
*ObjectPutHeaderOptions `header:",omitempty" url:"-" xml:"-"`
// PutFromFile 使用
innerSwitchURL *url.URL `header:"-" url:"-" xml:"-"`
}
// Put Object请求可以将一个文件(Oject)上传至指定Bucket。
//
// https://www.qcloud.com/document/product/436/7749
func (s *ObjectService) Put(ctx context.Context, name string, r io.Reader, uopt *ObjectPutOptions) (*Response, error) {
if r == nil {
return nil, fmt.Errorf("reader is nil")
}
if err := CheckReaderLen(r); err != nil {
return nil, err
}
opt := CloneObjectPutOptions(uopt)
totalBytes, err := GetReaderLen(r)
if err != nil && opt != nil && opt.Listener != nil {
if opt.ContentLength == 0 {
return nil, err
}
totalBytes = opt.ContentLength
}
if err == nil {
// 非bytes.Buffer/bytes.Reader/strings.Reader/os.File 由用户指定ContentLength, 或使用 Chunk 上传
if opt != nil && opt.ContentLength == 0 && IsLenReader(r) {
opt.ContentLength = totalBytes
}
}
// 如果是io.Seeker,则重试
count := 1
var position int64
if seeker, ok := r.(io.Seeker); ok {
// 记录原始位置
position, err = seeker.Seek(0, io.SeekCurrent)
if err == nil && s.client.Conf.RetryOpt.Count > 0 {
count = s.client.Conf.RetryOpt.Count
}
}
var resp *Response
var retrieable bool
sUrl := s.client.BaseURL.BucketURL
if opt.innerSwitchURL != nil {
sUrl = opt.innerSwitchURL
}
retryErr := &RetryError{}
for nr := 0; nr < count; nr++ {
reader := TeeReader(r, nil, totalBytes, nil)
if s.client.Conf.EnableCRC {
reader.writer = crc64.New(crc64.MakeTable(crc64.ECMA))
}
if opt != nil && opt.Listener != nil {
reader.listener = opt.Listener
}
sendOpt := sendOptions{
baseURL: sUrl,
uri: "/" + encodeURIComponent(name),
method: http.MethodPut,
body: reader,
optHeader: opt,
}
// 把上一次错误记录下来
if err != nil {
retryErr.Add(err)
}
resp, err = s.client.send(ctx, &sendOpt)
sUrl, retrieable = s.client.CheckRetrieable(sUrl, resp, err, nr >= count-2)
if retrieable && nr+1 < count {
if seeker, ok := r.(io.Seeker); ok {
_, e := seeker.Seek(position, io.SeekStart)
if e != nil {
break
}
continue
}
}
break
}
if err != nil {
if _, ok := err.(*ErrorResponse); !ok {
retryErr.Add(err)
err = retryErr
}
}
return resp, err
}
// PutFromFile put object from local file
func (s *ObjectService) PutFromFile(ctx context.Context, name string, filePath string, uopt *ObjectPutOptions) (resp *Response, err error) {
opt := CloneObjectPutOptions(uopt)
nr := 0
for nr < 3 {
fd, e := os.Open(filePath)
if e != nil {
err = e
return
}
resp, err = s.Put(ctx, name, fd, opt)
if err != nil {
nr++
fd.Close()
if s.client.Conf.RetryOpt.AutoSwitchHost {
// 收不到报文 或者 不存在RequestId
if resp == nil || resp.Header.Get("X-Cos-Request-Id") == "" {
opt.innerSwitchURL = toSwitchHost(s.client.BaseURL.BucketURL)
}
}
continue
}
fd.Close()
break
}
return
}
// ObjectCopyHeaderOptions is the head option of the Copy
type ObjectCopyHeaderOptions struct {
// When use replace directive to update meta infos
CacheControl string `header:"Cache-Control,omitempty" url:"-"`
ContentDisposition string `header:"Content-Disposition,omitempty" url:"-"`
ContentEncoding string `header:"Content-Encoding,omitempty" url:"-"`
ContentLanguage string `header:"Content-Language,omitempty" url:"-"`
ContentType string `header:"Content-Type,omitempty" url:"-"`
Expires string `header:"Expires,omitempty" url:"-"`
Expect string `header:"Expect,omitempty" url:"-"`
XCosMetadataDirective string `header:"x-cos-metadata-directive,omitempty" url:"-" xml:"-"`
XCosCopySourceIfModifiedSince string `header:"x-cos-copy-source-If-Modified-Since,omitempty" url:"-" xml:"-"`
XCosCopySourceIfUnmodifiedSince string `header:"x-cos-copy-source-If-Unmodified-Since,omitempty" url:"-" xml:"-"`
XCosCopySourceIfMatch string `header:"x-cos-copy-source-If-Match,omitempty" url:"-" xml:"-"`
XCosCopySourceIfNoneMatch string `header:"x-cos-copy-source-If-None-Match,omitempty" url:"-" xml:"-"`
XCosStorageClass string `header:"x-cos-storage-class,omitempty" url:"-" xml:"-"`
// 自定义的 x-cos-meta-* header
XCosMetaXXX *http.Header `header:"x-cos-meta-*,omitempty" url:"-"`
XCosCopySource string `header:"x-cos-copy-source" url:"-" xml:"-"`
XCosServerSideEncryption string `header:"x-cos-server-side-encryption,omitempty" url:"-" xml:"-"`
// SSE-C
XCosSSECustomerAglo string `header:"x-cos-server-side-encryption-customer-algorithm,omitempty" url:"-" xml:"-"`
XCosSSECustomerKey string `header:"x-cos-server-side-encryption-customer-key,omitempty" url:"-" xml:"-"`
XCosSSECustomerKeyMD5 string `header:"x-cos-server-side-encryption-customer-key-MD5,omitempty" url:"-" xml:"-"`
XCosCopySourceSSECustomerAglo string `header:"x-cos-copy-source-server-side-encryption-customer-algorithm,omitempty" url:"-" xml:"-"`
XCosCopySourceSSECustomerKey string `header:"x-cos-copy-source-server-side-encryption-customer-key,omitempty" url:"-" xml:"-"`
XCosCopySourceSSECustomerKeyMD5 string `header:"x-cos-copy-source-server-side-encryption-customer-key-MD5,omitempty" url:"-" xml:"-"`
//兼容其他自定义头部
XOptionHeader *http.Header `header:"-,omitempty" url:"-" xml:"-"`
}
// ObjectCopyOptions is the option of Copy, choose header or body
type ObjectCopyOptions struct {
*ObjectCopyHeaderOptions `header:",omitempty" url:"-" xml:"-"`
*ACLHeaderOptions `header:",omitempty" url:"-" xml:"-"`
}
// ObjectCopyResult is the result of Copy
type ObjectCopyResult struct {
XMLName xml.Name `xml:"CopyObjectResult"`
ETag string `xml:"ETag,omitempty"`
LastModified string `xml:"LastModified,omitempty"`
CRC64 string `xml:"CRC64,omitempty"`
VersionId string `xml:"VersionId,omitempty"`
}
// Copy 调用 PutObjectCopy 请求实现将一个文件从源路径复制到目标路径。建议文件大小 1M 到 5G,
// 超过 5G 的文件请使用分块上传 Upload - Copy。在拷贝的过程中,文件元属性和 ACL 可以被修改。
//
// 用户可以通过该接口实现文件移动,文件重命名,修改文件属性和创建副本。
//
// 注意:在跨帐号复制的时候,需要先设置被复制文件的权限为公有读,或者对目标帐号赋权,同帐号则不需要。
//
// 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) {
if strings.HasPrefix(sourceURL, "http://") || strings.HasPrefix(sourceURL, "https://") {
return nil, nil, errors.New("sourceURL format is invalid.")
}
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/%s?versionId=%s", surl[0], encodeURIComponent(surl[1]), id[0])
} else if len(id) == 0 {
keyAndVer := strings.SplitN(surl[1], "?", 2)
if len(keyAndVer) < 2 {
u = fmt.Sprintf("%s/%s", surl[0], encodeURIComponent(surl[1], []byte{'/'}))
} else {
u = fmt.Sprintf("%v/%v?%v", surl[0], encodeURIComponent(keyAndVer[0], []byte{'/'}), encodeURIComponent(keyAndVer[1], []byte{'='}))
}
} else {
return nil, nil, errors.New("wrong params")
}
var res ObjectCopyResult
copyOpt := &ObjectCopyOptions{
&ObjectCopyHeaderOptions{},
&ACLHeaderOptions{},
}
if opt != nil {
if opt.ObjectCopyHeaderOptions != nil {
*copyOpt.ObjectCopyHeaderOptions = *opt.ObjectCopyHeaderOptions
}
if opt.ACLHeaderOptions != nil {
*copyOpt.ACLHeaderOptions = *opt.ACLHeaderOptions
}
}
copyOpt.XCosCopySource = u
var bs bytes.Buffer
sendOpt := sendOptions{
baseURL: s.client.BaseURL.BucketURL,
uri: "/" + encodeURIComponent(name),
method: http.MethodPut,
body: nil,
optHeader: copyOpt,
result: &bs,
}
resp, err := s.client.doRetry(ctx, &sendOpt)
if err == nil { // 请求正常
err = xml.Unmarshal(bs.Bytes(), &res) // body 正常返回
// If the error occurs during the copy operation, the error response is embedded in the 200 OK response. This means that a 200 OK response can contain either a success or an error.
if resp != nil && resp.StatusCode == 200 {
if err != nil {
resErr := &ErrorResponse{Response: resp.Response}
xml.Unmarshal(bs.Bytes(), resErr)
return &res, resp, resErr
}
}
}
return &res, resp, err
}
type ObjectDeleteOptions struct {
// SSE-C
XCosSSECustomerAglo string `header:"x-cos-server-side-encryption-customer-algorithm,omitempty" url:"-" xml:"-"`
XCosSSECustomerKey string `header:"x-cos-server-side-encryption-customer-key,omitempty" url:"-" xml:"-"`
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
func (s *ObjectService) Delete(ctx context.Context, name string, opt ...*ObjectDeleteOptions) (*Response, error) {
var optHeader *ObjectDeleteOptions
if len(name) == 0 || name == "/" {
return nil, errors.New("empty object name")
}
// When use "" string might call the delete bucket interface
if s.client.Conf.ObjectKeySimplifyCheck && !CheckObjectKeySimplify("/"+name) {
return nil, ObjectKeySimplifyCheckErr
}
if len(opt) > 0 {
optHeader = opt[0]
}
sendOpt := sendOptions{
baseURL: s.client.BaseURL.BucketURL,
uri: "/" + encodeURIComponent(name),
method: http.MethodDelete,
optHeader: optHeader,
optQuery: optHeader,
}
resp, err := s.client.doRetry(ctx, &sendOpt)
return resp, err
}
// ObjectHeadOptions is the option of HeadObject
type ObjectHeadOptions struct {
IfModifiedSince string `url:"-" header:"If-Modified-Since,omitempty"`
// SSE-C
XCosSSECustomerAglo string `header:"x-cos-server-side-encryption-customer-algorithm,omitempty" url:"-" xml:"-"`
XCosSSECustomerKey string `header:"x-cos-server-side-encryption-customer-key,omitempty" url:"-" xml:"-"`
XCosSSECustomerKeyMD5 string `header:"x-cos-server-side-encryption-customer-key-MD5,omitempty" url:"-" xml:"-"`
XOptionHeader *http.Header `header:"-,omitempty" url:"-" xml:"-"`
}
// Head Object请求可以取回对应Object的元数据,Head的权限与Get的权限一致
//
// https://www.qcloud.com/document/product/436/7745
func (s *ObjectService) Head(ctx context.Context, name string, opt *ObjectHeadOptions, id ...string) (*Response, error) {
var u string
if len(id) == 1 {
u = fmt.Sprintf("/%s?versionId=%s", encodeURIComponent(name), id[0])
} else if len(id) == 0 {
u = "/" + encodeURIComponent(name)
} else {
return nil, errors.New("wrong params")
}
sendOpt := sendOptions{
baseURL: s.client.BaseURL.BucketURL,
uri: u,
method: http.MethodHead,
optHeader: opt,
}
resp, err := s.client.doRetry(ctx, &sendOpt)
if resp != nil && resp.Header["X-Cos-Object-Type"] != nil && resp.Header["X-Cos-Object-Type"][0] == "appendable" {
resp.Header.Add("x-cos-next-append-position", resp.Header.Get("Content-Length"))
}
return resp, err
}
func (s *ObjectService) IsExist(ctx context.Context, name string, id ...string) (bool, error) {
_, err := s.Head(ctx, name, nil, id...)
if err == nil {
return true, nil
}
if IsNotFoundError(err) {
return false, nil
}
return false, err
}
// ObjectOptionsOptions is the option of object options
type ObjectOptionsOptions struct {
Origin string `url:"-" header:"Origin"`
AccessControlRequestMethod string `url:"-" header:"Access-Control-Request-Method"`
AccessControlRequestHeaders string `url:"-" header:"Access-Control-Request-Headers,omitempty"`
}
// Options Object请求实现跨域访问的预请求。即发出一个 OPTIONS 请求给服务器以确认是否可以进行跨域操作。
//
// 当CORS配置不存在时,请求返回403 Forbidden。
//
// https://www.qcloud.com/document/product/436/8288
func (s *ObjectService) Options(ctx context.Context, name string, opt *ObjectOptionsOptions) (*Response, error) {
sendOpt := sendOptions{
baseURL: s.client.BaseURL.BucketURL,
uri: "/" + encodeURIComponent(name),
method: http.MethodOptions,
optHeader: opt,
}
resp, err := s.client.send(ctx, &sendOpt)
return resp, err
}
// CASJobParameters support three way: Standard(in 35 hours), Expedited(quick way, in 15 mins), Bulk(in 5-12 hours_
type CASJobParameters struct {
Tier string `xml:"Tier" header:"-" url:"-"`
}
// ObjectRestoreOptions is the option of object restore
type ObjectRestoreOptions struct {
XMLName xml.Name `xml:"RestoreRequest" header:"-" url:"-"`
Days int `xml:"Days,omitempty" header:"-" url:"-"`
Tier *CASJobParameters `xml:"CASJobParameters" header:"-" url:"-"`
XOptionHeader *http.Header `xml:"-" header:",omitempty" url:"-"`
}
// PutRestore API can recover an object of type archived by COS archive.
//
// https://cloud.tencent.com/document/product/436/12633
func (s *ObjectService) PostRestore(ctx context.Context, name string, opt *ObjectRestoreOptions, id ...string) (*Response, error) {
var u string
if len(id) == 1 {
u = fmt.Sprintf("/%s?restore&versionId=%s", encodeURIComponent(name), id[0])
} else if len(id) == 0 {
u = fmt.Sprintf("/%s?restore", encodeURIComponent(name))
} else {
return nil, errors.New("wrong params")
}
sendOpt := sendOptions{
baseURL: s.client.BaseURL.BucketURL,
uri: u,
method: http.MethodPost,
body: opt,
optHeader: opt,
}
resp, err := s.client.doRetry(ctx, &sendOpt)
return resp, err
}
// Append请求可以将一个文件(Object)以分块追加的方式上传至 Bucket 中。使用Append Upload的文件必须事前被设定为Appendable。
// 当Appendable的文件被执行Put Object的操作以后,文件被覆盖,属性改变为Normal。
//
// 文件属性可以在Head Object操作中被查询到,当您发起Head Object请求时,会返回自定义Header『x-cos-object-type』,该Header只有两个枚举值:Normal或者Appendable。
//
// 追加上传建议文件大小1M - 5G。如果position的值和当前Object的长度不致,COS会返回409错误。
// 如果Append一个Normal的Object,COS会返回409 ObjectNotAppendable。
//
// Appendable的文件不可以被复制,不参与版本管理,不参与生命周期管理,不可跨区域复制。
//
// 当 r 不是 bytes.Buffer/bytes.Reader/strings.Reader 时,必须指定 opt.ObjectPutHeaderOptions.ContentLength
//
// https://www.qcloud.com/document/product/436/7741
func (s *ObjectService) Append(ctx context.Context, name string, position int, r io.Reader, opt *ObjectPutOptions) (int, *Response, error) {
res := position
if r == nil {
return res, nil, fmt.Errorf("reader is nil")
}
if err := CheckReaderLen(r); err != nil {
return res, nil, err
}
opt = CloneObjectPutOptions(opt)
totalBytes, err := GetReaderLen(r)
if err != nil && opt != nil && opt.Listener != nil {
if opt.ContentLength == 0 {
return res, nil, err
}
totalBytes = opt.ContentLength
}
if err == nil {
// 非bytes.Buffer/bytes.Reader/strings.Reader/os.File 由用户指定ContentLength, 或使用 Chunk 上传
if opt != nil && opt.ContentLength == 0 && IsLenReader(r) {
opt.ContentLength = totalBytes
}
}
reader := TeeReader(r, nil, totalBytes, nil)
if s.client.Conf.EnableCRC {
reader.writer = md5.New() // MD5校验
reader.disableCheckSum = true
}
if opt != nil && opt.Listener != nil {
reader.listener = opt.Listener
}
u := fmt.Sprintf("/%s?append&position=%d", encodeURIComponent(name), position)
sendOpt := sendOptions{
baseURL: s.client.BaseURL.BucketURL,
uri: u,
method: http.MethodPost,
optHeader: opt,
body: reader,
}
resp, err := s.client.send(ctx, &sendOpt)
if err == nil {
// 数据校验
if s.client.Conf.EnableCRC && reader.writer != nil {
wanted := hex.EncodeToString(reader.Sum())
if wanted != resp.Header.Get("x-cos-content-sha1") {
return res, resp, fmt.Errorf("append verification failed, want:%v, return:%v, header:%+v", wanted, resp.Header.Get("x-cos-content-sha1"), resp.Header)
}
}
np, err := strconv.ParseInt(resp.Header.Get("x-cos-next-append-position"), 10, 64)
return int(np), resp, err
}
return res, resp, err
}
// ObjectDeleteMultiOptions is the option of DeleteMulti
type ObjectDeleteMultiOptions struct {
XMLName xml.Name `xml:"Delete" header:"-"`
Quiet bool `xml:"Quiet" header:"-"`
Objects []Object `xml:"Object" header:"-"`
//XCosSha1 string `xml:"-" header:"x-cos-sha1"`
}
// ObjectDeleteMultiResult is the result of DeleteMulti
type ObjectDeleteMultiResult struct {
XMLName xml.Name `xml:"DeleteResult"`
DeletedObjects []Object `xml:"Deleted,omitempty"`
Errors []struct {
Key string `xml:",omitempty"`
Code string `xml:",omitempty"`
Message string `xml:",omitempty"`
VersionId string `xml:",omitempty"`
} `xml:"Error,omitempty"`
}
// DeleteMulti 请求实现批量删除文件,最大支持单次删除1000个文件。
// 对于返回结果,COS提供Verbose和Quiet两种结果模式。Verbose模式将返回每个Object的删除结果;
// Quiet模式只返回报错的Object信息。
// https://www.qcloud.com/document/product/436/8289
func (s *ObjectService) DeleteMulti(ctx context.Context, opt *ObjectDeleteMultiOptions) (*ObjectDeleteMultiResult, *Response, error) {
var res ObjectDeleteMultiResult
sendOpt := sendOptions{
baseURL: s.client.BaseURL.BucketURL,
uri: "/?delete",
method: http.MethodPost,
body: opt,
result: &res,
}
resp, err := s.client.doRetry(ctx, &sendOpt)
return &res, resp, err
}
// Object is the meta info of the object
type Object struct {
Key string `xml:",omitempty"`
ETag string `xml:",omitempty"`
Size int64 `xml:",omitempty"`
PartNumber int `xml:",omitempty"`
LastModified string `xml:",omitempty"`
StorageClass string `xml:",omitempty"`
Owner *Owner `xml:",omitempty"`
VersionId string `xml:",omitempty"`
StorageTier string `xml:",omitempty"`
RestoreStatus string `xml:",omitempty"`
}
// MultiUploadOptions is the option of the multiupload,
// ThreadPoolSize default is one
type MultiUploadOptions struct {
OptIni *InitiateMultipartUploadOptions
PartSize int64
ThreadPoolSize int
CheckPoint bool
DisableChecksum bool
}
type MultiDownloadOptions struct {
Opt *ObjectGetOptions
PartSize int64
ThreadPoolSize int
CheckPoint bool
CheckPointFile string
DisableChecksum bool
}
type MultiDownloadCPInfo struct {
Size int64 `json:"contentLength,omitempty"`
ETag string `json:"eTag,omitempty"`
CRC64 string `json:"crc64ecma,omitempty"`
LastModified string `json:"lastModified,omitempty"`
DownloadedBlocks []DownloadedBlock `json:"downloadedBlocks,omitempty"`
}
type DownloadedBlock struct {
From int64 `json:"from,omitempty"`
To int64 `json:"to,omitempty"`
}
type Chunk struct {
Number int
OffSet int64
Size int64
Done bool
ETag string
}
// jobs
type Jobs struct {
Name string
UploadId string
FilePath string
RetryTimes int
VersionId []string
Chunk Chunk
Data io.Reader
Opt *ObjectUploadPartOptions
DownOpt *ObjectGetOptions
}
type Results struct {
PartNumber int
Resp *Response
err error
}
func LimitReadCloser(r io.Reader, n int64) io.Reader {
var lc LimitedReadCloser
lc.R = r
lc.N = n
return &lc
}
type LimitedReadCloser struct {
io.LimitedReader
}