如何使用 golang 从 AWS S3 下载

How to download from AWS S3 using golang

我正在编写一个 go 函数来从 AWS S3 存储桶下载文件。

func DownloadFromS3Bucket() {
    bucket := "cellery-runtime-installation"
    item := "hello-world.txt"

    file, err := os.Create(item)
    if err != nil {
        fmt.Println(err)
    }

    defer file.Close()

    // Initialize a session in us-west-2 that the SDK will use to load
    // credentials from the shared credentials file ~/.aws/credentials.
    sess, _ := session.NewSession(&aws.Config{
        Region: aws.String("us-east-1")},
    )

    downloader := s3manager.NewDownloader(sess)

    numBytes, err := downloader.Download(file,
        &s3.GetObjectInput{
            Bucket: aws.String(bucket),
            Key:    aws.String(item),
        })
    if err != nil {
        fmt.Println(err)
    }

    fmt.Println("Downloaded", file.Name(), numBytes, "bytes")
}

但是,我收到一条要求凭据的错误消息。

NoCredentialProviders: no valid providers in chain. Deprecated. For verbose messaging see aws.Config.CredentialsChainVerboseErrors

文档没有具体说明如何设置凭据。 (访问密钥ID,秘密访问密钥)

有什么想法吗?

设置凭据的方法有多种。更多详情 aws/credentials.

比如可以通过设置环境变量来指定:

AWS_ACCESS_KEY = <your_access_key>
AWS_SECRET_KEY = <your_secret_key>

然后只需在您的配置实例中使用 credentials.NewEnvCredentials()

sess, _ := session.NewSession(&aws.Config{
    Region:      aws.String("us-east-1"),
    Credentials: credentials.NewEnvCredentials(),
})

只需设置 AWS_ACCESS_KEYAWS_SECRET_KEY 环境变量(您不需要调用 credentials.NewEnvCredentials() 作为 session.NewSession 的一部分 - 您所做的是完美的):

func DownloadFromS3Bucket() {
    
    os.Setenv("AWS_ACCESS_KEY","my-key")
    os.Setenv("AWS_SECRET_KEY","my-secret")

    bucket := "cellery-runtime-installation"
    item := "hello-world.txt"

    file, err := os.Create(item)
    if err != nil {
        fmt.Println(err)
    }
    defer file.Close()

    sess, _ := session.NewSession(&aws.Config{Region: aws.String("us-east-1")})
    downloader := s3manager.NewDownloader(sess)
    numBytes, err := downloader.Download(file,
        &s3.GetObjectInput{
            Bucket: aws.String(bucket),
            Key:    aws.String(item),
        })
    if err != nil {
        fmt.Println(err)
    }

    fmt.Println("Downloaded", file.Name(), numBytes, "bytes")
}

这是来自 AWS Go SDK 的完整示例:https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/go/example_code/s3/s3_download_object.go

我写了一篇关于如何测试 S3 下载器 的博客post,并创建了一个可测试的 S3 存储桶扫描器,其中列出了所有存储桶的文件并临时下载了每个文件,请参阅:https://medium.com/@tufin/a-testable-go-aws-s3-scanner-e54de0c26197

在这里你可以找到代码:https://github.com/Tufin/blog/tree/master/s3-scanner