5
1

More than 3 years have passed since last update.

golangでAWSのS3でPre-Signed URLを作成するコード

Posted at
package main

import (
    "fmt"
    "time"

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

func main() {
    accessKey := "your accessKey"
    privateKey := "your privateKey"
    region := "ap-northeast-1"
    bucketName := "your bucketName"
    fileName := "gazou.png"

    creds := credentials.NewStaticCredentials(accessKey, privateKey, "")
    sess := session.Must(session.NewSession(&aws.Config{
        Credentials: creds,
        Region:      aws.String(region),
    }))
    s3Client := s3.New(sess)

    req, _ := s3Client.PutObjectRequest(&s3.PutObjectInput{
        Bucket: aws.String(bucketName),
        Key:    aws.String("/test/" + fileName),
    })
    u, err := req.Presign(3 * time.Minute) // 有効期限3分
    if err != nil {
        fmt.Println("error presigning request", err)
        return
    }
    fmt.Println(u)
}

出来上がったURLは、postmanとかのGUIクライアント使うとリクエストしやすいです。

postman download

また、下記でcurlできます。file部分がWindowsパス名なので、MacとかLinuxユーザは適宜変えてください。

curl --location --request PUT 'Created Pre-SignedURL' \
--header 'Content-Type: image/png' \
--data-binary '@/C:/test.png'
5
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
1