gpt4 book ai didi

amazon-web-services - 如何使用 golang 从公共(public) s3 存储桶下载

转载 作者:IT王子 更新时间:2023-10-29 02:07:47 24 4
gpt4 key购买 nike

我正在实现一个从 s3 存储桶下载文件的功能。当存储桶是私有(private)的并且我设置了凭据时,这工作正常

os.Setenv("AWS_ACCESS_KEY_ID", "test")
os.Setenv("AWS_SECRET_ACCESS_KEY", "test")

但是,我公开了 s3 存储桶,如 here 中所述现在我想在没有凭据的情况下下载它。

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

知道如何在没有凭据的情况下下载它吗?

最佳答案

我们可以在创建 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")
}

关于amazon-web-services - 如何使用 golang 从公共(public) s3 存储桶下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54555291/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com