You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

97 lines
2.3 KiB

package util
import (
"context"
"github.com/aws/aws-sdk-go-v2/aws"
v4 "github.com/aws/aws-sdk-go-v2/aws/signer/v4"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/service/s3"
"log"
"zggsong.cn/sandstone/server/response"
)
const (
endPoint = "http://10.58.22.11:8080"
bucket = "test"
accessKey = "bu29-smt-test"
secretKey = "Ksat@12345678"
)
func GetUrl(key string) string {
client := getClient()
url := getObjectUrl(client, bucket, key)
return url
}
func getClient() *s3.Client {
cfg, err := config.LoadDefaultConfig(
context.TODO(),
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
}
client := s3.NewFromConfig(cfg, func(o *s3.Options) {
o.UsePathStyle = true
o.EndpointOptions.DisableHTTPS = true
})
return client
}
type s3PresignGetObjectAPI interface {
PresignGetObject(
ctx context.Context,
params *s3.GetObjectInput,
optFns ...func(*s3.PresignOptions)) (*v4.PresignedHTTPRequest, error)
}
func getPresignedURL(c context.Context, api s3PresignGetObjectAPI, input *s3.GetObjectInput) (*v4.PresignedHTTPRequest, error) {
return api.PresignGetObject(c, input)
}
// 获取预签名的url
func getObjectUrl(client *s3.Client, bucket string, key string) string {
input := &s3.GetObjectInput{
Bucket: aws.String(bucket),
Key: aws.String(key),
}
psClient := s3.NewPresignClient(client)
resp, err := getPresignedURL(context.TODO(), psClient, input)
if err != nil {
return ("get url err: " + err.Error())
}
return resp.URL
}
func GetTags(key string) []response.Tag {
tags := []response.Tag{}
client := getClient()
tagOutPuts, err := client.GetObjectTagging(context.TODO(), &s3.GetObjectTaggingInput{
Bucket: aws.String(bucket),
Key: aws.String(key),
})
if err != nil {
log.Println("get object tags err: ", err.Error())
return tags
}
if tagOutPuts.TagSet != nil {
for _, tag := range tagOutPuts.TagSet {
tags = append(tags, response.Tag{
Key: *tag.Key,
Value: *tag.Value,
})
}
}
return tags
}