こちらで、Goのコード上からAWS S3にアップロードする方法を紹介しましたが、これをLambda関数化して同様に実行するとBodyHashError
が起こります。
該当箇所は、
f err := os.Open(fileName + ".json") if err != nil { fmt.Errorf("failed to open file %q, %v", "test.json", err) } // Upload the file to S3. res, err := uploader.Upload(&s3manager.UploadInput{ Bucket: aws.String("retweet-users"), Key: aws.String(fileName + ".json"), Body: f, })
のところです。
os.Open
がLambda上からは使用できないのは当然でした。
bytes.Buffer
を使用すればいいのです。
func uploadToS3(fileName string) { sess := session.Must(session.NewSession(&aws.Config{ Credentials: credentials.NewStaticCredentials("アクセスキー", "シークレットアクセスキー", ""), Region: aws.String("ap-northeast-1"), })) uploader := s3manager.NewUploader(sess) wb := new(bytes.Buffer) fmt.Fprint(wb, "テキスト") // Upload the file to S3. res, err := uploader.Upload(&s3manager.UploadInput{ Bucket: aws.String("retweet-users"), Key: aws.String(fileName + ".json"), Body: bytes.NewReader(wb.Bytes()), }) if err != nil { fmt.Println(res) if err, ok := err.(awserr.Error); ok && err.Code() == request.CanceledErrorCode { fmt.Fprintf(os.Stderr, "upload canceled due to timeout, %v\n", err) } else { fmt.Fprintf(os.Stderr, "failed to upload object, %v\n", err) } os.Exit(1) } fmt.Printf("successfully uploaded file to %s/%s\n", "retweet-users") }
Amazon Web Services パターン別構築・運用ガイド 改訂第2版 (Informatics&IDEA)
- 作者: NRIネットコム株式会社,佐々木拓郎,林晋一郎,小西秀和,佐藤瞬
- 出版社/メーカー: SBクリエイティブ
- 発売日: 2018/03/23
- メディア: 単行本
- この商品を含むブログ (1件) を見る
Amazon Web Services 基礎からのネットワーク&サーバー構築 改訂版
- 作者: 玉川憲,片山暁雄,今井雄太,大澤文孝
- 出版社/メーカー: 日経BP社
- 発売日: 2017/04/13
- メディア: 単行本
- この商品を含むブログを見る