为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用 golang 从公共 s3 存储桶下载

如何使用 golang 从公共 s3 存储桶下载

Go
aluckdog 2023-06-05 17:26:10
我正在实现一个从 s3 存储桶下载文件的功能。当存储桶是私有的并且我设置了凭据时,这工作正常os.Setenv("AWS_ACCESS_KEY_ID", "test") os.Setenv("AWS_SECRET_ACCESS_KEY", "test")但是,我按照此处所述公开了 s3 存储桶,现在我想在没有凭据的情况下下载它。func DownloadFromS3Bucket(bucket, item, path string) {    file, err := os.Create(filepath.Join(path, item))    if err != nil {        fmt.Printf("Error in downloading from file: %v \n", err)        os.Exit(1)    }    defer file.Close()    sess, _ := session.NewSession(&aws.Config{        Region: aws.String(constants.AWS_REGION)},    )    // Create a downloader with the session and custom options    downloader := s3manager.NewDownloader(sess, func(d *s3manager.Downloader) {        d.PartSize = 64 * 1024 * 1024 // 64MB per part        d.Concurrency = 6    })    numBytes, err := downloader.Download(file,        &s3.GetObjectInput{            Bucket: aws.String(bucket),            Key:    aws.String(item),        })    if err != nil {        fmt.Printf("Error in downloading from file: %v \n", err)        os.Exit(1)    }    fmt.Println("Download completed", file.Name(), numBytes, "bytes")}但是现在我遇到了一个错误。Error in downloading from file: NoCredentialProviders: no valid providers in chain. Deprecated.    For verbose messaging see aws.Config.CredentialsChainVerboseErrors知道如何在没有凭据的情况下下载它吗?
查看完整描述

1 回答

?
拉丁的传说

TA贡献1789条经验 获得超8个赞

我们可以在创建session的时候设置Credentials: credentials.AnonymousCredentials。以下是工作代码。


func DownloadFromS3Bucket(bucket, item, path string) {

    file, err := os.Create(filepath.Join(path, item))

    if err != nil {

        fmt.Printf("Error in downloading from file: %v \n", err)

        os.Exit(1)

    }


    defer file.Close()


    sess, _ := session.NewSession(&aws.Config{

        Region: aws.String(constants.AWS_REGION), Credentials: credentials.AnonymousCredentials},

    )


    // Create a downloader with the session and custom options

    downloader := s3manager.NewDownloader(sess, func(d *s3manager.Downloader) {

        d.PartSize = 64 * 1024 * 1024 // 64MB per part

        d.Concurrency = 6

    })


    numBytes, err := downloader.Download(file,

        &s3.GetObjectInput{

            Bucket: aws.String(bucket),

            Key:    aws.String(item),

        })

    if err != nil {

        fmt.Printf("Error in downloading from file: %v \n", err)

        os.Exit(1)

    }


    fmt.Println("Download completed", file.Name(), numBytes, "bytes")

}


查看完整回答
反对 回复 2023-06-05
  • 1 回答
  • 0 关注
  • 99 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信