[Go] S3 の特定のファイルの Presigned URL を取得する (aws-sdk-go)

作成日: 2023年06月07日

aws-sdk-go を使用して S3 の特定のオブジェクトの署名付き URL ( Presigned URL ) を取得するサンプルコードを示します。

package main

import (
    "fmt"
    "time"

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

func main() {
    sess := session.Must(session.NewSessionWithOptions(session.Options{
        SharedConfigState: session.SharedConfigEnable,
    }))

    svc := s3.New(sess)

    req, _ := svc.GetObjectRequest(&s3.GetObjectInput{
        Bucket: aws.String("dummy.s3.example.com"),
        Key:    aws.String("dummy_files/file1.txt"),
    })

    presignedUrl, err := req.Presign(5 * time.Minute)
    if err != nil {
        panic("何らかのエラー処理")
    }

    fmt.Println("Presigned URL: ", presignedUrl)
}

実行結果は下記のとおりです。

Presigned URL:  https://s3.ap-northeast-1.amazonaws.com/dummy.s3.example.com/dummy_files/file1.txt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAI1234ABCD1234ABC%2F20230608%2Fap-northeast-1%2Fs3%2Faws4_request&X-Amz-Date=20230608T145559Z&X-Amz-Expires=300&X-Amz-SignedHeaders=host&X-Amz-Signature=12342abcd1212dc4bfabcd0c93a07eb3d123438ca0894b8b5c4e1234b245825d
Go AWS