/
cos.go
1253 lines (1101 loc) · 32.9 KB
/
cos.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 (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"math/rand"
"os"
"strings"
"time"
"github.com/forhappy/cos-go-sdk/auth"
"github.com/forhappy/cos-go-sdk/http"
"github.com/forhappy/cos-go-sdk/utils"
)
const ENDPOINT = "http://web.file.myqcloud.com/files/v1/"
const EXPIRES = 60 * 5
const requestCanceled = "request canceled while waiting for connection"
const requestOnClosedConnection = "use of closed network connection"
// 腾讯云 COS API 客户端
type Client struct {
AppId string // 项目 ID
SecretId string // 项目 Secret ID
SecretKey string // 项目 Secret Key
Timeout time.Duration // 客户端超时时长
}
// 目录搜索模式, 细分为:
// Both : 列举目录和文件
// DirectoryOnly: 仅列举目录
// FileOnly : 仅列举文件
type ListPattern int
const (
Both ListPattern = iota // 列举目录和文件
DirectoryOnly // 仅列举目录
FileOnly // 仅列举文件
)
// 字符串化目录搜索模式, 可能的返回值为: eListBoth, eListDirOnly, eListFileOnly
func (p ListPattern) String() string {
switch p {
case Both:
return "eListBoth"
case DirectoryOnly:
return "eListDirOnly"
case FileOnly:
return "eListFileOnly"
default:
return "eListBoth"
}
}
// 目录搜索排序方式, 细分为:
// Asc: 正序
// Desc: 反序
type ListOrder int
const (
Asc ListOrder = iota // 正序
Desc // 反序
)
func (l ListOrder) Int() int {
switch l {
case Asc:
return 0
case Desc:
return 1
default:
return 0
}
}
// 构造 COS API 客户端
// appId: 项目 ID
// secretId: 项目的 Secret ID
// secretKey: 项目的 Secret Key
func NewClient(appId, secretId, secretKey string) *Client {
rand.Seed(time.Now().Unix())
return &Client{
AppId: appId,
SecretId: secretId,
SecretKey: secretKey,
Timeout: -1,
}
}
// 设置客户端 HTTP 请求超时时长
func (c *Client) SetTimeout(timeout time.Duration) {
c.Timeout = timeout
}
// 判断客户端是否超时
func (c Client) IsTimeout(err error) bool {
return strings.HasSuffix(err.Error(), requestCanceled) ||
strings.HasSuffix(err.Error(), requestOnClosedConnection)
}
// COS API 请求参数封装
type Request struct {
Op string `json:"op" url:"op"`
}
// COS API 返回结果封装
type Response struct {
Code int `json:"code"`
Message string `json:"message"`
}
// 目录创建操作的请求参数封装
type CreateFolderRequest struct {
Request
BizAttr string `json:"biz_attr"`
}
// 目录创建操作的返回结果封装
type CreateFolderResponse struct {
Response
Data struct {
Ctime string `json:"ctime"`
ResourcePath string `json:"resource_path"`
} `json:"data"`
}
// 目录更新操作的请求参数封装
type UpdateFolderRequest struct {
Request
BizAttr string `json:"biz_attr"`
}
// 目录更新操作的返回结果封装
type UpdateFolderResponse struct {
Response
}
// 目录查询操作的请求参数封装
type StatFolderRequest struct {
Request
}
// 目录查询操作的返回结果封装
type StatFolderResponse struct {
Response
Data struct {
Name string `json:"name"`
BizAttr string `json:"biz_attr"`
Ctime string `json:"ctime"`
Mtime string `json:"mtime"`
} `json:"data"`
}
// 目录删除操作的请求参数封装
type DeleteFolderRequest struct {
Request
}
// 目录删除操作的返回结果封装
type DeleteFolderResponse struct {
Response
}
// 目录列举及搜索操作的请求参数封装
type ListFolderRequest struct {
Op string `json:"op" url:"op"`
Pattern string `json:"pattern" url:"pattern"`
Context string `json:"context" url:"context"`
Num int `json:"num" url:"num"`
Order int `json:"order" url:"order"`
}
// 目录列举及搜索操作的返回结果封装
type ListFolderResponse struct {
Response
Data struct {
Context string `json:"context"`
HasMore bool `json:"has_more"`
DirCount int `json:"dircount"`
FileCount int `json:"filecount"`
Infos []struct {
Name string `json:"name"`
BizAttr string `json:"biz_attr"`
FileSize int64 `json:"filesize"`
FileLen int64 `json:"filelen"`
Sha string `json:"sha"`
Ctime string `json:"ctime"`
Mtime string `json:"mtime"`
AccessUrl string `json:"access_url"`
} `json:"infos"`
} `json:"data"`
}
// 文件上传操作的请求参数封装
type UploadFileRequest struct {
Op string `json:"op"`
FileContent string `json:"filecontent"`
Sha string `json:"sha"`
BizAttr string `json:"biz_attr"`
}
// 文件上传操作的返回结果封装
type UploadFileResponse struct {
Response
Data struct {
AccessUrl string `json:"access_url"`
Url string `json:"url"`
ResourcePath string `json:"resource_path"`
} `json:"data"`
}
// 初次文件分片上传操作的请求参数封装
type PrepareToUploadSliceRequest struct {
Op string `json:"op"`
FileSize int64 `json:"filesize"`
Sha string `json:"sha"`
BizAttr string `json:"biz_attr"`
Session string `json:"session"`
SliceSize int64 `json:"slice_size"`
}
// 后续文件分片上传操作的请求参数封装
type UploadSliceRequest struct {
Op string `json:"op"`
FileContent string `json:"filecontent"`
Sha string `json:"sha"`
Session string `json:"session"`
SliceSize int64 `json:"slice_size"`
Offset int64 `json:"offset"`
}
// 文件分片上传操作的返回结果封装
type UploadSliceResponse struct {
Response
Data struct {
Session string `json:"session"`
Offset int64 `json:"offset"`
SliceSize int64 `json:"slice_size"`
AccessUrl string `json:"access_url"`
Url string `json:"url"`
ResourcePath string `json:"resource_path"`
} `json:"data"`
}
// 文件属性更新操作的请求参数封装
type UpdateFileRequest struct {
Request
BizAttr string `json:"biz_attr"`
}
// 文件属性更新操作的返回结果封装
type UpdateFileResponse struct {
Response
}
// 文件查询操作的请求参数封装
type StatFileRequest struct {
Request
}
// 文件查询操作的返回结果封装
type StatFileResponse struct {
Response
Data struct {
Name string `json:"name"`
BizAttr string `json:"biz_attr"`
FileSize string `json:"filesize"`
FileLen string `json:"filelen"`
Sha string `json:"sha"`
Ctime string `json:"ctime"`
Mtime string `json:"mtime"`
AccessUrl string `json:"access_url"`
} `json:"data"`
}
// 文件删除操作的请求参数封装
type DeleteFileRequest struct {
Request
}
// 文件删除操作的返回结果封装
type DeleteFileResponse struct {
Response
}
func (c *Client) generateFileId(bucket, path string) string {
resource := fmt.Sprintf("/%s/%s%s", c.AppId, bucket, path)
return resource
}
func (c *Client) generateResourceUrl(bucket, path string) string {
resource := fmt.Sprintf("%s%s/%s%s", ENDPOINT, c.AppId, bucket, path)
return resource
}
func (c *Client) validateFolderPath(path string) string {
validFolderPath := path
if path == "" {
return "/"
}
if !strings.HasPrefix(path, "/") {
validFolderPath = "/" + path
}
if !strings.HasSuffix(path, "/") {
validFolderPath += "/"
}
return validFolderPath
}
func (c *Client) validateFilePath(path string) string {
validFilePath := path
if path == "" {
return "/"
}
if !strings.HasPrefix(path, "/") {
validFilePath = "/" + path
}
return validFilePath
}
func (c *Client) validateSliceSize(sliceSize int64) int64 {
if sliceSize < 8*1024 {
return 8 * 1024
} else if sliceSize > 2*1024*1024 {
return 2 * 1024 * 1024
}
sliceSize -= 1
sliceSize |= (sliceSize >> 1)
sliceSize |= (sliceSize >> 2)
sliceSize |= (sliceSize >> 4)
sliceSize |= (sliceSize >> 8)
sliceSize |= (sliceSize >> 16)
sliceSize += 1
return sliceSize
}
// 创建目录
// bucket: Bucket 名称
// path: 目录路径
// bizAttr: 目录属性, 由业务端维护
//
// 示例:
//
// client := cos.NewClient(appId, secretId, secretKey)
//
// res, err := client.CreateFolder("cosdemo", "/hello", "hello")
// if err != nil {
// fmt.Println(err)
// return
// }
//
// fmt.Println("Code:", res.Code,
// "\nMessage:", res.Message,
// "\nCtime:", res.Data.Ctime,
// "\nResource Path:", res.Data.ResourcePath)
//
func (c *Client) CreateFolder(bucket, path, bizAttr string) (*CreateFolderResponse, error) {
var cosRequest CreateFolderRequest
var cosResponse CreateFolderResponse
encodedPath := utils.UrlEncode(c.validateFolderPath(path))
resource := c.generateResourceUrl(bucket, encodedPath)
now := time.Now().Unix()
strNow := fmt.Sprintf("%d", now)
strExpires := fmt.Sprintf("%d", now+EXPIRES)
strRand := fmt.Sprintf("%d", rand.Int31())
signer := auth.NewSignature(c.AppId, bucket, c.SecretId, strExpires, strNow, strRand, "")
sign := signer.Sign(c.SecretKey)
cosRequest.Op = "create"
cosRequest.BizAttr = bizAttr
httpRequest := http.Request{
Method: "POST",
Uri: resource,
Timeout: c.Timeout,
ContentType: "application/json",
Body: cosRequest,
}
httpRequest.AddHeader("Authorization", sign)
httpResponse, err := httpRequest.Do()
if err != nil {
return nil, err
}
err = httpResponse.Body.Unmarshal(&cosResponse)
if err != nil {
return nil, err
}
return &cosResponse, nil
}
// 更新目录属性
// bucket: Bucket 名称
// path: 目录路径
// bizAttr: 目录属性, 由业务端维护
//
// 示例:
//
// client := cos.NewClient(appId, secretId, secretKey)
//
// res, err := client.UpdateFolder("cosdemo", "/hello", "hello-new-attr")
// if err != nil {
// fmt.Println(err)
// return
// }
//
// fmt.Println("Code:", res.Code,
// "\nMessage:", res.Message)
//
func (c *Client) UpdateFolder(bucket, path, bizAttr string) (*UpdateFolderResponse, error) {
var cosRequest UpdateFolderRequest
var cosResponse UpdateFolderResponse
encodedPath := utils.UrlEncode(c.validateFolderPath(path))
fileId := c.generateFileId(bucket, encodedPath)
resource := c.generateResourceUrl(bucket, encodedPath)
now := time.Now().Unix()
strNow := fmt.Sprintf("%d", now)
strRand := fmt.Sprintf("%d", rand.Int31())
signer := auth.NewSignature(c.AppId, bucket, c.SecretId, "", strNow, strRand, fileId)
sign := signer.SignOnce(c.SecretKey)
cosRequest.Op = "update"
cosRequest.BizAttr = bizAttr
httpRequest := http.Request{
Method: "POST",
Uri: resource,
Timeout: c.Timeout,
ContentType: "application/json",
Body: cosRequest,
}
httpRequest.AddHeader("Authorization", sign)
httpResponse, err := httpRequest.Do()
if err != nil {
return nil, err
}
err = httpResponse.Body.Unmarshal(&cosResponse)
if err != nil {
return nil, err
}
return &cosResponse, nil
}
// 查询目录属性
// bucket: Bucket 名称
// path: 目录路径
//
// 示例:
//
// client := cos.NewClient(appId, secretId, secretKey)
//
// res, err := client.StatFolder("cosdemo", "/hello")
// if err != nil {
// fmt.Println(err)
// return
// }
//
// fmt.Println("Code:", res.Code,
// "\nMessage:", res.Message,
// "\nName:", res.Data.Name,
// "\nBizAttr:", res.Data.BizAttr,
// "\nCtime:", res.Data.Ctime,
// "\nMtime:", res.Data.Mtime)
//
func (c *Client) StatFolder(bucket, path string) (*StatFolderResponse, error) {
var cosRequest StatFolderRequest
var cosResponse StatFolderResponse
encodedPath := utils.UrlEncode(c.validateFolderPath(path))
resource := c.generateResourceUrl(bucket, encodedPath)
now := time.Now().Unix()
strNow := fmt.Sprintf("%d", now)
strExpires := fmt.Sprintf("%d", now+EXPIRES)
strRand := fmt.Sprintf("%d", rand.Int31())
signer := auth.NewSignature(c.AppId, bucket, c.SecretId, strExpires, strNow, strRand, "")
sign := signer.Sign(c.SecretKey)
cosRequest.Op = "stat"
httpRequest := http.Request{
Method: "GET",
Uri: resource,
Timeout: c.Timeout,
QueryString: cosRequest.Request,
}
httpRequest.AddHeader("Authorization", sign)
httpResponse, err := httpRequest.Do()
if err != nil {
return nil, err
}
err = httpResponse.Body.Unmarshal(&cosResponse)
if err != nil {
return nil, err
}
return &cosResponse, nil
}
// 删除目录
// bucket: Bucket 名称
// path: 目录路径
//
// 示例:
//
// client := cos.NewClient(appId, secretId, secretKey)
//
// res, err := client.DeleteFolder("cosdemo", "/hello")
// if err != nil {
// fmt.Println(err)
// return
// }
//
// fmt.Println("Code:", res.Code,
// "\nMessage:", res.Message)
//
func (c *Client) DeleteFolder(bucket, path string) (*DeleteFolderResponse, error) {
var cosRequest DeleteFolderRequest
var cosResponse DeleteFolderResponse
encodedPath := utils.UrlEncode(c.validateFolderPath(path))
fileId := c.generateFileId(bucket, encodedPath)
resource := c.generateResourceUrl(bucket, encodedPath)
now := time.Now().Unix()
strNow := fmt.Sprintf("%d", now)
strRand := fmt.Sprintf("%d", rand.Int31())
signer := auth.NewSignature(c.AppId, bucket, c.SecretId, "", strNow, strRand, fileId)
sign := signer.SignOnce(c.SecretKey)
cosRequest.Op = "delete"
httpRequest := http.Request{
Method: "POST",
Uri: resource,
Timeout: c.Timeout,
ContentType: "application/json",
Body: cosRequest,
}
httpRequest.AddHeader("Authorization", sign)
httpResponse, err := httpRequest.Do()
if err != nil {
return nil, err
}
err = httpResponse.Body.Unmarshal(&cosResponse)
if err != nil {
return nil, err
}
return &cosResponse, nil
}
// 列举目录和文件
// bucket: Bucket 名称
// path: 目录路径
// context: Context 用于翻页, 需要往前/往后翻页需透传回来
// pattern: 目录列举模式, 可选值为 Both(列举目录和文件), DirectoryOnly(仅列举目录), FileOnly(仅列举文件)
// num: 本次拉取的目录和文件总数
// order: 目录列举排序规则, 可选值为 Asc(正序), Desc(反序)
//
// 示例:
//
// client := cos.NewClient(appId, secretId, secretKey)
//
// res, err := client.ListFolder("cosdemo", "/hello", "", cos.Both, 100, cos.Asc)
// if err != nil {
// fmt.Println(err)
// return
// }
//
// fmt.Println("Code:", res.Code,
// "\nMessage:", res.Message,
// "\nContext:", res.Data.Context,
// "\nHasMore:", res.Data.HasMore,
// "\nDirCount:", res.Data.DirCount,
// "\nFileCount:", res.Data.FileCount,
// )
//
// fmt.Println("*************************************")
// for _, info := range res.Data.Infos {
// fmt.Println("Name:", info.Name,
// "\nBizAttr:", info.BizAttr,
// "\nFileSize:", info.FileSize,
// "\nFileLen:", info.FileLen,
// "\nSha:", info.Sha,
// "\nCtime:", info.Ctime,
// "\nMtime:", info.Mtime,
// "\nAccess URL:", info.AccessUrl,
// )
// fmt.Println("*************************************")
// }
//
func (c *Client) ListFolder(bucket, path, context string, pattern ListPattern, num int, order ListOrder) (*ListFolderResponse, error) {
var cosRequest ListFolderRequest
var cosResponse ListFolderResponse
encodedPath := utils.UrlEncode(c.validateFolderPath(path))
resource := c.generateResourceUrl(bucket, encodedPath)
now := time.Now().Unix()
strNow := fmt.Sprintf("%d", now)
strExpires := fmt.Sprintf("%d", now+EXPIRES)
strRand := fmt.Sprintf("%d", rand.Int31())
signer := auth.NewSignature(c.AppId, bucket, c.SecretId, strExpires, strNow, strRand, "")
sign := signer.Sign(c.SecretKey)
cosRequest.Op = "list"
cosRequest.Pattern = pattern.String()
cosRequest.Context = context
cosRequest.Order = order.Int()
cosRequest.Num = num
httpRequest := http.Request{
Method: "GET",
Uri: resource,
Timeout: c.Timeout,
QueryString: cosRequest,
}
httpRequest.AddHeader("Authorization", sign)
httpResponse, err := httpRequest.Do()
if err != nil {
return nil, err
}
err = httpResponse.Body.Unmarshal(&cosResponse)
if err != nil {
return nil, err
}
return &cosResponse, nil
}
// 前缀搜索目录和文件
// bucket: Bucket 名称
// path: 目录路径
// prefix: 搜索前缀
// context: Context 用于翻页, 需要往前/往后翻页需透传回来
// pattern: 目录列举模式, 可选值为 Both(列举目录和文件), DirectoryOnly(仅列举目录), FileOnly(仅列举文件)
// num: 本次拉取的目录和文件总数
// order: 目录列举排序规则, 可选值为 Asc(正序), Desc(反序)
//
// 示例:
//
// client := cos.NewClient(appId, secretId, secretKey)
//
// res, err := client.PrefixSearch("cosdemo", "/hello", "A", "", cos.Both, 100, cos.Asc)
// if err != nil {
// fmt.Println(err)
// return
// }
//
// fmt.Println("Code:", res.Code,
// "\nMessage:", res.Message,
// "\nContext:", res.Data.Context,
// "\nHasMore:", res.Data.HasMore,
// "\nDirCount:", res.Data.DirCount,
// "\nFileCount:", res.Data.FileCount,
// )
//
// fmt.Println("*************************************")
// for _, info := range res.Data.Infos {
// fmt.Println("Name:", info.Name,
// "\nBizAttr:", info.BizAttr,
// "\nFileSize:", info.FileSize,
// "\nFileLen:", info.FileLen,
// "\nSha:", info.Sha,
// "\nCtime:", info.Ctime,
// "\nMtime:", info.Mtime,
// "\nAccess URL:", info.AccessUrl,
// )
// fmt.Println("*************************************")
// }
//
func (c *Client) PrefixSearch(bucket, path, prefix, context string, pattern ListPattern, num int, order ListOrder) (*ListFolderResponse, error) {
var cosRequest ListFolderRequest
var cosResponse ListFolderResponse
encodedPath := utils.UrlEncode(c.validateFolderPath(path) + prefix)
resource := c.generateResourceUrl(bucket, encodedPath)
now := time.Now().Unix()
strNow := fmt.Sprintf("%d", now)
strExpires := fmt.Sprintf("%d", now+EXPIRES)
strRand := fmt.Sprintf("%d", rand.Int31())
signer := auth.NewSignature(c.AppId, bucket, c.SecretId, strExpires, strNow, strRand, "")
sign := signer.Sign(c.SecretKey)
cosRequest.Op = "list"
cosRequest.Pattern = pattern.String()
cosRequest.Context = context
cosRequest.Order = order.Int()
cosRequest.Num = num
httpRequest := http.Request{
Method: "GET",
Uri: resource,
Timeout: c.Timeout,
QueryString: cosRequest,
}
httpRequest.AddHeader("Authorization", sign)
httpResponse, err := httpRequest.Do()
if err != nil {
return nil, err
}
err = httpResponse.Body.Unmarshal(&cosResponse)
if err != nil {
return nil, err
}
return &cosResponse, nil
}
// 上传文件
// bucket: Bucket 名称
// dstpath: 目的文件路径, 须设置为腾讯云端文件路径
// srcPath: 本地文件路径
// bizAttr: 文件属性, 由业务端维护
//
// 示例:
// client := cos.NewClient(appId, secretId, secretKey)
//
// res, err := client.UploadFile("cosdemo", "/hello/hello.txt", "/users/new.txt", "file attr")
// if err != nil {
// fmt.Println(err)
// return
// }
//
// fmt.Println("Code:", res.Code,
// "\nMessage:", res.Message,
// "\nUrl:", res.Data.Url,
// "\nResourcePath:", res.Data.ResourcePath,
// "\nAccess Url:", res.Data.AccessUrl)
//
func (c *Client) UploadFile(bucket, dstPath, srcPath, bizAttr string) (*UploadFileResponse, error) {
fileContent, err := ioutil.ReadFile(srcPath)
if err != nil {
return nil, err
}
fileSize, err := utils.GetFileSize(srcPath)
if err != nil {
return nil, err
}
if fileSize > 5*1024*1024 {
var res UploadFileResponse
uploadSliceResponse, err := c.UploadSlice(bucket, dstPath, srcPath, bizAttr, "", 1024*512)
if err != nil {
return nil, err
}
uploadSliceResponseBytes, err := json.Marshal(uploadSliceResponse)
if err != nil {
return nil, err
}
err = json.Unmarshal(uploadSliceResponseBytes, &res)
if err != nil {
return nil, err
}
return &res, nil
}
return c.UploadChunk(bucket, dstPath, fileContent, bizAttr)
}
// 上传内存块至云端
// bucket: Bucket 名称
// dstpath: 目的文件路径, 须设置为腾讯云端文件路径
// chunk: 本地内存块
// bizAttr: 文件属性, 由业务端维护
//
// 示例:
// client := cos.NewClient(appId, secretId, secretKey)
//
// res, err := client.UploadChunk("cosdemo", "/hello/hello.txt", []bytes("Hello"), "test hello")
// if err != nil {
// fmt.Println(err)
// return
// }
//
// fmt.Println("Code:", res.Code,
// "\nMessage:", res.Message,
// "\nUrl:", res.Data.Url,
// "\nResourcePath:", res.Data.ResourcePath,
// "\nAccess Url:", res.Data.AccessUrl)
//
func (c *Client) UploadChunk(bucket, dstPath string, chunk []byte, bizAttr string) (*UploadFileResponse, error) {
var cosRequest UploadFileRequest
var cosResponse UploadFileResponse
sha := utils.HashBufferWithSha1(chunk)
encodedPath := utils.UrlEncode(c.validateFilePath(dstPath))
resource := c.generateResourceUrl(bucket, encodedPath)
now := time.Now().Unix()
strNow := fmt.Sprintf("%d", now)
strExpires := fmt.Sprintf("%d", now+EXPIRES)
strRand := fmt.Sprintf("%d", rand.Int31())
signer := auth.NewSignature(c.AppId, bucket, c.SecretId, strExpires, strNow, strRand, "")
sign := signer.Sign(c.SecretKey)
cosRequest.Op = "upload"
cosRequest.FileContent = string(chunk)
cosRequest.Sha = sha
cosRequest.BizAttr = bizAttr
httpRequest := http.Request{
Method: "POST",
Uri: resource,
Timeout: c.Timeout,
Body: cosRequest,
Multipart: true,
}
httpRequest.AddHeader("Authorization", sign)
httpResponse, err := httpRequest.Do()
if err != nil {
return nil, err
}
err = httpResponse.Body.Unmarshal(&cosResponse)
if err != nil {
return nil, err
}
return &cosResponse, nil
}
// 大文件分片上传
// bucket: Bucket 名称
// dstpath: 目的文件路径, 须设置为腾讯云端文件路径
// srcPath: 本地文件路径
// bizAttr: 文件属性, 由业务端维护
// session: 唯一标识此文件传输过程的id, 由后台下发, 调用方透传
// sliceSize: 分片大小, 用户可以根据网络状况自行设置
//
// 示例:
// client := cos.NewClient(appId, secretId, secretKey)
//
// res, err := client.UploadSlice("cosdemo", "/hello/hello.bin", "/users/bigfile.bin", "file attr", "", 512 * 1024)
// if err != nil {
// fmt.Println(err)
// return
// }
//
// fmt.Println("Code:", res.Code,
// "\nMessage:", res.Message,
// "\nUrl:", res.Data.Url,
// "\nResourcePath:", res.Data.ResourcePath,
// "\nAccess Url:", res.Data.AccessUrl)
//
func (c *Client) UploadSlice(bucket, dstPath, srcPath, bizAttr, session string, sliceSize int64) (*UploadSliceResponse, error) {
sliceSize = c.validateSliceSize(sliceSize)
preparing, err := c.PrepareToUploadSlice(bucket, dstPath, srcPath, bizAttr, session, sliceSize)
if err != nil {
return nil, err
}
if preparing.Code != 0 {
return nil, fmt.Errorf("%s", preparing.Message)
}
if len(preparing.Data.Url) != 0 { // 秒传命中
return preparing, nil
}
var offset int64
if preparing.Data.SliceSize != 0 {
sliceSize = preparing.Data.SliceSize
}
if preparing.Data.Offset != 0 {
offset = preparing.Data.Offset
}
if preparing.Data.Session != "" {
session = preparing.Data.Session
}
srcFile, err := os.Open(srcPath)
if err != nil {
return nil, err
}
defer srcFile.Close()
fileInfo, err := srcFile.Stat()
if err != nil {
return nil, err
}
fileSize := fileInfo.Size()
srcFile.Seek(preparing.Data.Offset, 0)
for fileSize > offset {
var rawBytes []byte
if fileSize-offset > sliceSize {
rawBytes = make([]byte, sliceSize)
nbytes, err := io.ReadFull(srcFile, rawBytes)
if int64(nbytes) != sliceSize || err != nil {
return nil, err
}
} else {
leftSize := fileSize - offset
rawBytes = make([]byte, leftSize)
nbytes, err := io.ReadFull(srcFile, rawBytes)
if int64(nbytes) != leftSize || err != nil {
return nil, err
}
}
continuing, err := c.ContinueUploadingSliceData(bucket, dstPath, rawBytes, session, offset)
if err != nil {
return nil, err
}
if len(continuing.Data.Url) > 0 {
return continuing, nil
} else {
offset += sliceSize
}
}
return preparing, nil
}
// 大文件分片上传(首次上传)
// bucket: Bucket 名称
// dstpath: 目的文件路径, 须设置为腾讯云端文件路径
// srcPath: 本地文件路径
// bizAttr: 文件属性, 由业务端维护
// session: 唯一标识此文件传输过程的id, 由后台下发, 调用方透传
// sliceSize: 分片大小, 用户可以根据网络状况自行设置
//
// 示例:
// client := cos.NewClient(appId, secretId, secretKey)
//
// res, err := client.PrepareToUploadSlice("cosdemo", "/hello/hello.bin", "/Users/bigfile.bin", "file attr", "", 512 * 1024)
// if err != nil {
// fmt.Println(err)
// return
// }
//
// fmt.Println("Code:", res.Code,
// "\nMessage:", res.Message,
// "\nSession:", res.Session,
// "\nOffset:", res.Offset,
// "\nSliceSize:", res.SliceSize,
// "\nUrl:", res.Data.Url,
// "\nResourcePath:", res.Data.ResourcePath,
// "\nAccess Url:", res.Data.AccessUrl)
//
func (c *Client) PrepareToUploadSlice(bucket, dstPath, srcPath, bizAttr, session string, sliceSize int64) (*UploadSliceResponse, error) {
var cosRequest PrepareToUploadSliceRequest
var cosResponse UploadSliceResponse
sha, size, err := utils.HashFileWithSha1(srcPath)
if err != nil {
return nil, err
}
encodedPath := utils.UrlEncode(c.validateFilePath(dstPath))
resource := c.generateResourceUrl(bucket, encodedPath)
now := time.Now().Unix()
strNow := fmt.Sprintf("%d", now)
strExpires := fmt.Sprintf("%d", now+EXPIRES)
strRand := fmt.Sprintf("%d", rand.Int31())
signer := auth.NewSignature(c.AppId, bucket, c.SecretId, strExpires, strNow, strRand, "")
sign := signer.Sign(c.SecretKey)
cosRequest.Op = "upload_slice"
cosRequest.FileSize = size
cosRequest.Sha = sha
cosRequest.BizAttr = bizAttr
cosRequest.Session = session
cosRequest.SliceSize = sliceSize
httpRequest := http.Request{
Method: "POST",
Uri: resource,
Timeout: c.Timeout,
Body: cosRequest,