如何在golang中从AWS S3获取资源URL

fkvaft9z  于 2023-01-15  发布在  Go
关注(0)|答案(2)|浏览(204)

我需要使用golang和official aws go sdk获取资源的公共永久(未签名)URL。在Java AWS S3 SDK中有一个名为getResourceUrl()的方法,在go中的等效方法是什么?

xfyts7mz

xfyts7mz1#

这就是你如何使用go sdk获得预先签名的URL:

func GetFileLink(key string) (string, error) {
    svc := s3.New(some params)

    params := &s3.GetObjectInput{
        Bucket: aws.String(a bucket name),
        Key:    aws.String(key),
    }

    req, _ := svc.GetObjectRequest(params)

    url, err := req.Presign(15 * time.Minute) // Set link expiration time
    if err != nil {
        global.Log("[AWS GET LINK]:", params, err)
    }

    return url, err
}

如果您需要的只是公共访问对象的URL,则可以自己构建URL:

https://<region>.amazonaws.com/<bucket-name>/<key>

其中<region>类似于us-east-2,所以使用go,它将类似于:

url := "https://%s.amazonaws.com/%s/%s"
url = fmt.Sprintf(url, "us-east-2", "my-bucket-name", "some-file.txt")

以下是S3所有可用区域的列表。

nvbavucw

nvbavucw2#

看起来几乎干净:

import "github.com/aws/aws-sdk-go/private/protocol/rest"

...

params := &s3.GetObjectInput{
    Bucket: aws.String(a bucket name),
    Key:    aws.String(key),
}
req, _ := svc.GetObjectRequest(params)
rest.Build(req) // aws method to build URL in request object
url = req.HTTPRequest.URL.String() // complete URL to resource

相关问题