go操作aws s3
- go
- 13天前
- 28热度
- 0评论
v2
官方推荐版本,需要go版本>=1.20
安装
go get github.com/aws/aws-sdk-go-v2
go get github.com/aws/aws-sdk-go-v2/config
go get github.com/aws/aws-sdk-go-v2/service/s3
必要参数
bucket: 存储桶的名称
Region: 存储桶所在区域,例us-east-1
accessKeyID: 访问存储桶所需的KeyID
secretAccessKey: 访问存储桶所需的AccessKey
如何获取accessKeyID和secretAccessKey:指南
var (
s3Client *s3.Client
bucket = "yourbucketname"
)
func InitS3Client() {
accessKeyID := "xxxxx"
secretAccessKey := "xxxxx"
cfg, err := config.LoadDefaultConfig(context.TODO(),
config.WithRegion("ap-east-1"),
config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(accessKeyID, secretAccessKey, "")),
)
if err != nil {
log.Fatalf("unable to load SDK config, %v", err)
}
s3Client = s3.NewFromConfig(cfg)
}
func UploadToS3(filePath, fileName, mimeType string) (string, error) {
file, err := os.Open(filePath)
if err != nil {
return "", fmt.Errorf("failed to open file %q, %v", filePath, err)
}
defer file.Close()
_, err = s3Client.PutObject(context.TODO(), &s3.PutObjectInput{
Bucket: aws.String(bucket),
Key: aws.String(fileName),
Body: file,
ContentType: aws.String(mimeType),
})
if err != nil {
return "", fmt.Errorf("failed to upload file to S3, %v", err)
}
return fmt.Sprintf("https://%s.s3.amazonaws.com/%s", bucket, fileName), nil
}
参考2
// 创建s3Client实例。
payKeyId := "AK***"
paySecret := "oiy***"
accessKeyID := payKeyId
secretAccessKey := paySecret
cfg, err := config.LoadDefaultConfig(context.TODO(),
config.WithRegion("ap-east-1"),
config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(accessKeyID, secretAccessKey, "")),
)
if err != nil {
fmt.Printf("unable to load SDK config, %v", err)
}
name := "test"
s3Client := s3.NewFromConfig(cfg)
filePath := "static/test.jpg"
// 读取本地文件。
fd, err := os.Open(filePath)
if err != nil {
return
}
defer fd.Close()
_, err = s3Client.PutObject(context.TODO(), &s3.PutObjectInput{
Bucket: aws.String("up"),
Key: aws.String("upload/" + name + ".jpg"),
Body: fd,
})
if err != nil {
fmt.Printf("Name: %s\n", err)
return
}
fmt.Printf("上传成功\n")