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
|
func GetClient(ctx context.Context, endpoint, accessKey, secretKey string) (*s3.Client, error) {
cfg, err := config.LoadDefaultConfig(
ctx,
config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(accessKey, secretKey, "")),
config.WithEndpointResolverWithOptions(
aws.EndpointResolverWithOptionsFunc(func(service, region string, options ...interface{}) (aws.Endpoint, error) {
return aws.Endpoint{URL: endpoint}, nil
})),
config.WithRegion("us-east-1"),
)
if err != nil {
return nil, err
}
client := s3.NewFromConfig(cfg, func(o *s3.Options) {
o.UsePathStyle = true
o.EndpointOptions.DisableHTTPS = true
})
return client, nil
}
type S3PutObjectAPI interface {
PutObject(ctx context.Context,
params *s3.PutObjectInput,
optFns ...func(*s3.Options)) (*s3.PutObjectOutput, error)
}
func PutFile(c context.Context, api S3PutObjectAPI, input *s3.PutObjectInput) (*s3.PutObjectOutput, error) {
return api.PutObject(c, input)
}
type S3PutTaggingAPI interface {
PutObjectTagging(ctx context.Context,
params *s3.PutObjectTaggingInput,
optFns ...func(*s3.Options)) (*s3.PutObjectTaggingOutput, error)
}
func putTag(c context.Context, api S3PutTaggingAPI, input *s3.PutObjectTaggingInput) (*s3.PutObjectTaggingOutput, error) {
return api.PutObjectTagging(c, input)
}
// UPutObject 上传对象
func UPutObject(ctx context.Context, client *s3.Client, path, bucket, key string) error {
file, err := os.Open(path)
if err != nil {
return errors.New("上传对象时打开文件失败," + err.Error())
}
defer file.Close()
input := &s3.PutObjectInput{
Bucket: aws.String(bucket),
Key: aws.String(key),
Body: file,
}
_, err = PutFile(ctx, client, input)
if err != nil {
return errors.New("上传对象时发生错误," + err.Error())
}
return nil
}
// UPutTag 上传标签
func UPutTag(ctx context.Context, client *s3.Client, bucket, key string, tags map[string]string) error {
input := &s3.PutObjectTaggingInput{
Bucket: aws.String(bucket),
Key: aws.String(key),
}
index := 0
for k, v := range tags {
input.Tagging.TagSet[index] = types.Tag{Key: aws.String(k), Value: aws.String(v)}
index++
}
_, err := putTag(ctx, client, input)
if err != nil {
return errors.New("上传标签时发生错误," + err.Error())
}
return nil
}
|