go操作aws s3

v2

官方推荐版本,需要go版本>=1.20

安装

bash 复制代码
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:指南

go 复制代码
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

安装

bash 复制代码
go get github.com/aws/aws-sdk-go
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
}
相关推荐
请你喝好果汁6411 天前
Kingfisher 下载ENA、NCBI SRA、AWS 和 Google Cloud)序列数据和元数据
云计算·aws
九陌斋1 天前
如何使用AWS Lambda构建一个云端工具(超详细)
云计算·aws
嚯——哈哈1 天前
AWS云服务器:开启高效计算的新纪元
服务器·云计算·aws
嚯——哈哈1 天前
从入门到精通:解析如何使用亚马逊云服务器(AWS EC2)
运维·服务器·aws
w_t_y_y1 天前
aws服务(二)机密数据存储
aws
徒步僧1 天前
ThingsBoard规则链节点:AWS SNS 节点详解
云计算·aws
九河云1 天前
如何对AWS进行节省
大数据·云计算·aws
w_t_y_y3 天前
AwsCredentialsProvider认证接口
aws
w_t_y_y3 天前
aws凭证(一)凭证存储
云计算·aws
Lovely_red_scarf3 天前
aws上安装ssm-agent
aws