亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 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 關注
  • 173 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號