golangでS3からGetObjectする
- はじめに
github.com/aws/aws-sdk-go このsdkを使ったs3オブジェクトの取得を行うサンプルコードです。
- sample
package main import ( "fmt" "os" "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" "github.com/aws/aws-sdk-go/service/s3/s3manager" ) //ダウンロードするオブジェクトの構造体 type downloader struct { *s3manager.Downloader bucket string file string dir string } func main() { accessKeyId := "AccessKeyId" secretAccessKey := "SecretAccessKey" // The session the S3 Downloader will use sess := session.Must(session.NewSession( &aws.Config{ Credentials: credentials.NewStaticCredentials(accessKeyId, secretAccessKey, ""), Region: aws.String("ap-northeast-1"), })) // Create a downloader with the session and default options downloader := s3manager.NewDownloader(sess) localFilename := "download.tar" // Create a file to write the S3 Object contents to. f, err := os.Create(localFilename) if err != nil { fmt.Printf("failed to create file %q, %v", localFilename, err) } bucketName := "BacketName" key := "targetFileName" // Write the contents of S3 Object to the file n, err := downloader.Download(f, &s3.GetObjectInput{ Bucket: aws.String(bucketName), Key: aws.String(key), }) if err != nil { fmt.Printf("failed to download file, %v", err) } fmt.Printf("file downloaded, %d bytes\n", n) }
- tips
このerror
cannot use \"ap-northeast-1\" (type string) as type *string in field value
// The session the S3 Downloader will use sess := session.Must(session.NewSession( &aws.Config{ Credentials: credentials.NewStaticCredentials(accessKeyId, secretAccessKey, ""), Region: "ap-northeast-1", }))
stringを*string(ポインタ)に変換して、ということらしい。
確かにRegion *string
こうなってます。
ググったらaws.String()
というのもがあることがわかったので、修正しました。
// The session the S3 Downloader will use sess := session.Must(session.NewSession( &aws.Config{ Credentials: credentials.NewStaticCredentials(accessKeyId, secretAccessKey, ""), Region: aws.String("ap-northeast-1"), }))
ポインタは値をコピーせずアドレスを渡すらしい。
おわり