go操作aws s3

avatar
作者
筋斗云
阅读量: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

如何获取accessKeyIDsecretAccessKey:指南

var ( 	s3Client *s3.Client 	bucket   = "yourbucketname" )  func InitS3Client() { 	accessKeyID := "xxxxx" 	secretAccessKey := "xxxxx"  	cfg, err := config.LoadDefaultConfig(context.TODO(), 		config.WithRegion("us-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 } 

若不想升级go1.20,可以使用v1版本

v1

安装

go get github.com/aws/aws-sdk-go 
var ( 	s3Client *s3.S3 	bucket   = "yourbucketname" )  func InitS3Client() { 	accessKeyID := "xxxxx" 	secretAccessKey := "xxxxx"  	sess, err := session.NewSession(&aws.Config{ 		Region:      aws.String("us-east-1"), 		Credentials: credentials.NewStaticCredentials(accessKeyID, secretAccessKey, ""), 	}) 	if err != nil { 		log.Fatalf("unable to create AWS session, %v", err) 	}  	s3Client = s3.New(sess) }  func UploadToS3(content []byte, fileName, mimeType string) (string, error) { 	_, err := s3Client.PutObject(&s3.PutObjectInput{ 		Bucket:      aws.String(bucket), 		Key:         aws.String(fileName), 		Body:        bytes.NewReader(content), 		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 } 

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!