怠慢プログラマーの備忘録

怠慢でナマケモノなプログラマーの備忘録です。

【Golang】AWSLambdaからS3にアップロードする

yutaabe200.hatenablog.com

こちらで、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)

Amazon Web Services パターン別構築・運用ガイド 改訂第2版 (Informatics&IDEA)

Amazon Web Services 基礎からのネットワーク&サーバー構築 改訂版

Amazon Web Services 基礎からのネットワーク&サーバー構築 改訂版