在 GO 中使用 AWS SDK V2 上传图片失败

Image upload failed using AWS SDK V2 in GO

我正在使用 AWS S3 服务上传图片。昨天更新了SDK v1到v2,发现图片上传失败,报如下错误:

operation error S3: PutObject, https response error StatusCode: 403, RequestID: XXXXXXXXXXX, HostID: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX, api error SignatureDoesNotMatch: The request signature we calculated does not match the signature you provided. Check your key and signing method.

已更新: 我在 .aws 文件夹中 linux 的主文件夹中有 aws 凭据,格式如下:

[default]
aws_access_key_id = XXXXXXXXXXXXXXXXXXX
aws_secret_access_key = XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXx

代码如下:

package main

import (
    "context"
    "fmt"
    "io"
    "net/http"

    "github.com/aws/aws-sdk-go-v2/aws"
    awsconfig "github.com/aws/aws-sdk-go-v2/config"
    "github.com/aws/aws-sdk-go-v2/feature/s3/manager"
    "github.com/aws/aws-sdk-go-v2/service/s3"
)

func main() {
    fileName := "test123.jpg"
    filePath := "/BUCKET_NAME/uploads/aman/2021/6/25/"

    res, err := http.Get("https://images.app.goo.gl/mpQ5nXYXjdUMKGgW7")
    if err != nil || res.StatusCode != 200 {
        // handle errors
    }
    defer res.Body.Close()
    UploadFileInS3Bucket(res.Body, fileName, filePath)
}

func UploadFileInS3Bucket(file io.Reader, fileName, filePath string) {
    cfg, err := awsconfig.LoadDefaultConfig(context.TODO(),
        awsconfig.WithRegion("REGION"),
    )
    client := s3.NewFromConfig(cfg)
    uploader := manager.NewUploader(client)
    uploadResp, err := uploader.Upload(context.TODO(), &s3.PutObjectInput{
        Bucket:      aws.String(filePath),
        Key:         aws.String(fileName),
        Body:        file,
        ContentType: aws.String("image"),
    })
    fmt.Println(uploadResp)
    fmt.Println(err)
}


我没有更改 code.However 中的任何 credentials/buckets/regions 如果我 运行 使用 SDK v1 的代码然后它工作正常并且图像正在上传。

SDK v2 出了什么问题?

经过几天的时间,我了解到 SDK V2 对 Bucket & Key 字段采用以下格式:

fileName := "uploads/2021/6/25/test123.jpg"
filePath := "BUCKET_NAME"

基本上,对于这些字段,在 SDK V1 和 V2 中存在反之亦然的行为。以上是V2。下面是 V1:

fileName := "test123.jpg"
filePath := "/BUCKET_NAME/uploads/2021/6/25/"