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

问题描述 投票:0回答:3

我需要使用 golang 和官方 aws go sdk 获取资源的公共永久(未签名)URL。在 Java AWS S3 SDK 中有一个名为

getResourceUrl()
的方法,在 go 中相当于什么?

amazon-web-services go amazon-s3 aws-sdk
3个回答
13
投票

这是使用 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所有可用区域的列表。


0
投票

sdk-go-v2 的更新版本如何获取预签名 URL

package aws

import (
    "context"
    "log"
    "os"
    "time"

    "github.com/aws/aws-sdk-go-v2/aws"
    "github.com/aws/aws-sdk-go-v2/service/s3"
)

// GetFileLink returns a presigned URL for a file in AWS S3.
// This function utilizes the aws-go-v2 SDK.
func GetFileLink(cfg aws.Config, key string) (string, error) {
    // Get the bucket name from the environment variable.
    bucketName := os.Getenv("BUCKET_NAME")

    // Create a new S3 client from the configuration.
    s3Client := s3.NewFromConfig(cfg)
    presignClient := s3.NewPresignClient(s3Client)

    // Get the presigned URL for the file.
    presignUrl, err := presignClient.PresignGetObject(context.Background(),
        &s3.GetObjectInput{
            Bucket: aws.String(bucketName),
            Key:    aws.String(key)},

    s3.WithPresignExpires(time.Minute*15))
    if err != nil {
        // If there's an error getting the presigned URL, return the error.
        return "", err
    }

        return presignUrl.URL, nil
}

使用示例:

main.go

func main() {
    // Load the AWS SDK configuration.
    cfg, err := config.LoadDefaultConfig(context.TODO())
    if err != nil {
        log.Fatalf("unable to load AWS SDK config, %v", err)
    }

    // Set the file key.
    fileKey := "path/to_your/file.txt"

    // Get the presigned URL for the file.
    url, err := adminpanel.GetFileLink(cfg, fileKey)
    if err != nil {
        log.Fatalf("failed to get file link, %v", err)
    }

    // Print the file URL.
    fmt.Println("File URL:", url)
}

-2
投票

看起来几乎干净:

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
© www.soinside.com 2019 - 2024. All rights reserved.