golang中使用aws-sdk-go-v2

2024-09-03 22:36
文章标签 sdk go golang 使用 v2 aws

本文主要是介绍golang中使用aws-sdk-go-v2,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1.aws-sdk-go-v2常用api

1.引入所需包

   

import ("context""fmt""log""os""path/filepath""sync""time""github.com/aws/aws-sdk-go-v2/aws""github.com/aws/aws-sdk-go-v2/config""github.com/aws/aws-sdk-go-v2/credentials""github.com/aws/aws-sdk-go-v2/feature/s3/manager""github.com/aws/aws-sdk-go-v2/service/s3""github.com/aws/aws-sdk-go-v2/service/s3/types""github.com/gabriel-vasile/mimetype"
)

2.初始化aws配置

func initAwsConfig(partitionID, url, region, key, secret string) (cfg aws.Config) {customResolver := aws.EndpointResolverWithOptionsFunc(func(service, region string, options ...interface{}) (aws.Endpoint, error) {return aws.Endpoint{PartitionID:   partitionID,URL:           url,SigningRegion: region,}, nil})creds := credentials.NewStaticCredentialsProvider(key, secret, "")cfg, err := config.LoadDefaultConfig(context.TODO(), config.WithCredentialsProvider(creds), config.WithEndpointResolverWithOptions(customResolver))if err != nil {log.Printf("error: %v", err)return}return cfg
}

3.初始化aws客户端

func initAwsClient(region, url string, cfg aws.Config, style bool) *s3.Client {awsS3Client := s3.NewFromConfig(cfg, func(o *s3.Options) {o.UsePathStyle = styleo.Region = *aws.String(region)o.BaseEndpoint = aws.String(url)})return awsS3Client
}

4.创建bucket

func createBUcket(bucket string, awsS3Client *s3.Client, storeyType string) {createInput := &s3.CreateBucketInput{Bucket: aws.String(bucket),ACL:    types.BucketCannedACLPublicRead,}out, err := awsS3Client.CreateBucket(context.TODO(), createInput)fmt.Println(storeyType+"创建bucket返回信息:", out)fmt.Println(storeyType+"创建bucket错误信息", err)
}

5.获取bucket信息

func headBucketInfo(bucket string, awsS3Client *s3.Client, storeyType string) {input := &s3.HeadBucketInput{Bucket: aws.String(bucket)}out, err := awsS3Client.HeadBucket(context.TODO(), input)if out != nil {fmt.Println(storeyType+"返回bucket信息:", *out.BucketRegion)}if err != nil {fmt.Println(storeyType+"错误信息", err)}
}

4.普通文件上传

func uploadFile(bucket string, awsS3Client *s3.Client) {// 打开要上传的文件file, err := os.Open("D:\\DefaultInfo\\Pictures\\06.jpg")if err != nil {fmt.Println("上传文件报错", err)}defer file.Close()putInput := &s3.PutObjectInput{Bucket: aws.String(bucket),Key:    aws.String("image/20240522101923-aws.jpg"),Body:   file,}awsS3Client.PutObject(context.TODO(), putInput)
}

5.分块上传

// 分块上传 默认分块大小5m
func upload(bucket string, awsS3Client *s3.Client) {//https://aws.github.io/aws-sdk-go-v2/docs/sdk-utilities/s3/uploader := manager.NewUploader(awsS3Client)filePath := "D:\\DefaultInfo\\Pictures\\06.jpg"file, err := os.Open(filePath)if err != nil {fmt.Println("上传文件报错", err)}defer file.Close()//检测文件的content-typemtype, _ := mimetype.DetectReader(file)putInput := &s3.PutObjectInput{Bucket:      aws.String(bucket),Key:         aws.String("image/20240522101923-manager222.jpg"),Body:        file,ContentType: aws.String(mtype.String()),}result, err := uploader.Upload(context.TODO(), putInput)fmt.Println("上传文件返回结果", result)fmt.Println("上传文件", err)}

6.获取文件信息

func getObjectinfo(bucket, key, storeyType string, awsS3Client *s3.Client) {headObjectInput := &s3.HeadObjectInput{Bucket: aws.String(bucket),Key:    aws.String("image/20240522101923-manager222.jpg"),}out, err := awsS3Client.HeadObject(context.TODO(), headObjectInput)if out != nil {fmt.Printf(storeyType+"获取文件信息:", *out.ContentType)}if err != nil {fmt.Println(storeyType+"获取文件信息失败:", err)}}

7.对象复制

func copyObject(bucket, key, storeyType string, awsS3Client *s3.Client) {copyInput := &s3.CopyObjectInput{//目标文件bucketBucket: aws.String(bucket),//拷贝后目标文件Key: aws.String("image/20240522101923-copy-manager222.jpg"),//源文件CopySource: aws.String(bucket + "/image/20240522101923-manager222.jpg"),}out, err := awsS3Client.CopyObject(context.TODO(), copyInput)if out != nil {fmt.Printf(storeyType+"拷贝文件信息:", *out.CopyObjectResult)}if err != nil {fmt.Println(storeyType+"拷贝文件信息失败:", err)}
}

8.获取临时url

func getPresignedUrl(bucket, key, storeyType string, awsS3Client *s3.Client) {presign := s3.NewPresignClient(awsS3Client)duration := 10 * time.Minutefmt.Println("换算为秒:", duration.Seconds())options := func(o *s3.PresignOptions) {o.Expires = duration}input := &s3.GetObjectInput{Bucket: aws.String(bucket),Key:    aws.String("image/20240522101923-manager222.jpg"),}req, err := presign.PresignGetObject(context.TODO(), input, options)fmt.Println(storeyType+"临时url信息:", req.URL)fmt.Println(err)
}

9.获取指定bucket下的对象列表

func GetObjectList(bucket string, awsS3Client *s3.Client) {input := &s3.ListObjectsV2Input{Bucket: aws.String(bucket),}out, err := awsS3Client.ListObjectsV2(context.TODO(), input)fmt.Println("out===", *out.KeyCount)fmt.Println(err)// for _, object := range out.Contents {// 	fmt.Println(*object.Key)// }}

10.拷贝所有的对象到指定的bucket

func CopyALlObject(bucket, distbucket, storeyType string, awsS3Client *s3.Client) {listinput := &s3.ListObjectsV2Input{Bucket: aws.String(bucket),}listFile, err := awsS3Client.ListObjectsV2(context.TODO(), listinput)fmt.Printf(storeyType+"获取文件信息失败:", err)for _, fileName := range listFile.Contents {copyInput := &s3.CopyObjectInput{//目标文件bucketBucket: aws.String(distbucket),//拷贝后目标文件Key: aws.String(*fileName.Key),//源文件CopySource: aws.String(bucket + "/" + *fileName.Key),}out, err := awsS3Client.CopyObject(context.TODO(), copyInput)if out != nil {fmt.Printf(storeyType+"拷贝文件信息:", *out.CopyObjectResult)}if err != nil {fmt.Println(storeyType+"拷贝文件信息失败:", err)}}}

2.常用云存储使用awssdk

1.oss--阿里云

func OssClient() {partitionID := "oss"url := "https://oss-cn-shanghai.aliyuncs.com"region := "ap-shanghai"key := "xxxxxx"secret := "xxxxx"bucket := "bucket"cfg := initAwsConfig(partitionID, url, region, key, secret)awsS3Client := initAwsClient(region, url, cfg, false)headBucketInfo(bucket, awsS3Client, "阿里云cos")//createBUcket(bucket, awsS3Client, "阿里云cos")//uploadFile(bucket, awsS3Client)
}

2.cos--腾讯云

func CosClient() {partitionID := "cos"url := "https://cos.ap-shanghai.myqcloud.com"region := "ap-shanghai"key := "xxxxxx"secret := "xxxxxxx"bucket := "xxxx-456798"cfg := initAwsConfig(partitionID, url, region, key, secret)awsS3Client := initAwsClient(region, url, cfg, false)headBucketInfo(bucket, awsS3Client, "腾讯云cos")//createBUcket(bucket, awsS3Client, "腾讯云cos")//uploadFile(bucket, awsS3Client)//upload(bucket, awsS3Client)//getObjectinfo(bucket, key, "腾讯云cos", awsS3Client)//copyObject(bucket, key, "腾讯云cos", awsS3Client)//getPresignedUrl(bucket, key, "腾讯云cos", awsS3Client)}

3.obs--华为云

func InitObs() {url := "https://obs.myhuaweicloud.com"region := "cn-east-3"partitionID := "obs"key := "xxxxxxx"secret := "xxxxxx"bucket := "bucket"cfg := initAwsConfig(partitionID, url, region, key, secret)awsS3Client := initAwsClient(region, url, cfg, false)headBucketInfo(bucket, awsS3Client, "华为云obs")//createBUcket(bucket, awsS3Client, "华为云obs")//upload(bucket, awsS3Client)
}

4.minio

func InitMinIo() {partitionID := "minio"url := "http://127.0.0.1:9001"region := "cn-east-1"key := "minioadmin"secret := "minioadmin"//bucket := "bucket"cfg := initAwsConfig(partitionID, url, region, key, secret)awsS3Client := initAwsClient(region, url, cfg, true)//headBucketInfo(bucket, awsS3Client, "minio")//CopyALlObject("xbzqnewbkt", "chinareformbkt", "minio", awsS3Client)//GetObjectList("gdqhbkt", awsS3Client)downFileBysuffix("dfzqbkt", awsS3Client)//createBUcket(bucket, awsS3Client, "minio")//uploadFile(bucket, awsS3Client)//upload(bucket, awsS3Client)//getObjectinfo(bucket, key, "minio", awsS3Client)//copyObject(bucket, key, "minio", awsS3Client)//getPresignedUrl(bucket, key, "minio", awsS3Client)}

这篇关于golang中使用aws-sdk-go-v2的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1134241

相关文章

全面解析Golang 中的 Gorilla CORS 中间件正确用法

《全面解析Golang中的GorillaCORS中间件正确用法》Golang中使用gorilla/mux路由器配合rs/cors中间件库可以优雅地解决这个问题,然而,很多人刚开始使用时会遇到配... 目录如何让 golang 中的 Gorilla CORS 中间件正确工作一、基础依赖二、错误用法(很多人一开

Android Paging 分页加载库使用实践

《AndroidPaging分页加载库使用实践》AndroidPaging库是Jetpack组件的一部分,它提供了一套完整的解决方案来处理大型数据集的分页加载,本文将深入探讨Paging库... 目录前言一、Paging 库概述二、Paging 3 核心组件1. PagingSource2. Pager3.

python使用try函数详解

《python使用try函数详解》Pythontry语句用于异常处理,支持捕获特定/多种异常、else/final子句确保资源释放,结合with语句自动清理,可自定义异常及嵌套结构,灵活应对错误场景... 目录try 函数的基本语法捕获特定异常捕获多个异常使用 else 子句使用 finally 子句捕获所

C++11右值引用与Lambda表达式的使用

《C++11右值引用与Lambda表达式的使用》C++11引入右值引用,实现移动语义提升性能,支持资源转移与完美转发;同时引入Lambda表达式,简化匿名函数定义,通过捕获列表和参数列表灵活处理变量... 目录C++11新特性右值引用和移动语义左值 / 右值常见的左值和右值移动语义移动构造函数移动复制运算符

Python对接支付宝支付之使用AliPay实现的详细操作指南

《Python对接支付宝支付之使用AliPay实现的详细操作指南》支付宝没有提供PythonSDK,但是强大的github就有提供python-alipay-sdk,封装里很多复杂操作,使用这个我们就... 目录一、引言二、准备工作2.1 支付宝开放平台入驻与应用创建2.2 密钥生成与配置2.3 安装ali

C#中lock关键字的使用小结

《C#中lock关键字的使用小结》在C#中,lock关键字用于确保当一个线程位于给定实例的代码块中时,其他线程无法访问同一实例的该代码块,下面就来介绍一下lock关键字的使用... 目录使用方式工作原理注意事项示例代码为什么不能lock值类型在C#中,lock关键字用于确保当一个线程位于给定实例的代码块中时

MySQL 强制使用特定索引的操作

《MySQL强制使用特定索引的操作》MySQL可通过FORCEINDEX、USEINDEX等语法强制查询使用特定索引,但优化器可能不采纳,需结合EXPLAIN分析执行计划,避免性能下降,注意版本差异... 目录1. 使用FORCE INDEX语法2. 使用USE INDEX语法3. 使用IGNORE IND

C# $字符串插值的使用

《C#$字符串插值的使用》本文介绍了C#中的字符串插值功能,详细介绍了使用$符号的实现方式,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习吧... 目录$ 字符使用方式创建内插字符串包含不同的数据类型控制内插表达式的格式控制内插表达式的对齐方式内插表达式中使用转义序列内插表达式中使用

flask库中sessions.py的使用小结

《flask库中sessions.py的使用小结》在Flask中Session是一种用于在不同请求之间存储用户数据的机制,Session默认是基于客户端Cookie的,但数据会经过加密签名,防止篡改,... 目录1. Flask Session 的基本使用(1) 启用 Session(2) 存储和读取 Se

Java Thread中join方法使用举例详解

《JavaThread中join方法使用举例详解》JavaThread中join()方法主要是让调用改方法的thread完成run方法里面的东西后,在执行join()方法后面的代码,这篇文章主要介绍... 目录前言1.join()方法的定义和作用2.join()方法的三个重载版本3.join()方法的工作原