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

我正在实现一个从 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

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


aluckdog
浏览 103回答 1
1回答

拉丁的传说

我们可以在创建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")}
打开App,查看更多内容
随时随地看视频慕课网APP