
GolangでAmazon S3を使う
こんにちは、Anti-Pattern Inc.の塚本です。
APIサーバからS3に接続して、ファイルをアップロードするユースケースの実装について書こうと思います。
Amazon S3を立てなくてもローカル環境で確認出来る様に、minioを使いました。
minioについてはこちらを参考にしました。ありがとうございます。
https://qiita.com/reflet/items/3e0f07bc9d64314515c1
https://dev.classmethod.jp/articles/s3-compatible-storage-minio/
実装したプログラム
AWS SDK for Go API Referenceを参考に実装してます。
認証情報は環境変数に設定しているので、アプリケーションで設定していません。
https://github.com/aws/aws-sdk-go/blob/master/aws/session/env_config.go
import (
"bytes"
"encoding/base64"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
)
func (s s3Service) Upload(f upload.File) error {
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
Config: aws.Config{
Endpoint: aws.String(s.Endpoints),
S3ForcePathStyle: aws.Bool(true)},
}))
uploader := s3manager.NewUploader(sess)
fname := f.ConvFileName()
data, _ := base64.StdEncoding.DecodeString(f.Data)
wb := new(bytes.Buffer)
wb.Write(data)
// Upload the file to S3.
if _, err := uploader.Upload(&s3manager.UploadInput{
Bucket: aws.String(s.BucketName),
Key: aws.String(fname),
Body: wb,
}); err != nil {
return err
}
return nil
}minioを使う時には、この考慮が必要そうです。
S3ForcePathStyle: aws.Bool(true)},パスの生成が違うんですね。SDKでS3ForcePathStyleのコメントにはこの様に記述されてます。
// Set this to `true` to force the request to use path-style addressing,
// i.e., `http://s3.amazonaws.com/BUCKET/KEY`. By default, the S3 client
// will use virtual hosted bucket addressing when possible
// (`http://BUCKET.s3.amazonaws.com/KEY`).
ちなみにfalseの場合はエラーとなります。
caused by: Put "http://test.minio:9000/5af84b7c80dffc14d769421f68cf4ef5e0d03128858fb648cdcfcc1196dbf3e3": dial tcp: lookup engineed.minio on 127.0.0.11:53: no such host
data, _ := base64.StdEncoding.DecodeString(f.Data)
wb := new(bytes.Buffer)
wb.Write(data)UploadInputのBodyには*bytes.Bufferを設定しています。
s3manager.UploadInputのBodyはio.Reader型です。bytes.BufferもRead(p []byte) (n int, err error)メソッドを実装しているので、Bodyに設定出来るんですね。
ドキュメント充実してるなーと感じた開発でした。
こちらからは以上です!