[Go Revel] S3からファイルをDownloadする

まずHTMLとroutingを作ります。

    <button type=“button” onclick="location.href='/test/download'">download</button>
GET		/test 				  App.Test
GET     /test/download		  App.Download

続いてaws-sdk-goをget
$ go get -u github.com/aws/aws-sdk-go

最後にcontroller
app.go
L ファイルのリターンはc.RenderFileName(“${file_path}”, revel.Attachment)

import (
	"github.com/revel/revel"
	"os"
	"log"

	"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"
)
func (c App) Download() revel.Result {


	creds := credentials.NewStaticCredentials("${AWS_ACCESS_KEY_ID}","${AWS_SECRET_ACCESS_KEY}","")
	sess := session.Must(session.NewSession(&aws.Config{
		Credentials: creds,
		Region: aws.String("ap-northeast-1"),
	}))

	f, err := os.Create("public/tmp/sample.json")
	if err != nil {
		log.Fatal(err)
	}

	bucketName := "${bucketName}"
	objectKey := "${file}"

	downloader := s3manager.NewDownloader(sess)
	n, err := downloader.Download(f, &s3.GetObjectInput{
		Bucket: aws.String(bucketName),
		Key: aws.String(objectKey),
	})

	if err != nil {
		log.Fatal(err)
	}
	log.Printf("DownloadedSize: %d byte", n)


	return c.RenderFileName("public/tmp/sample.json", revel.Attachment)
}

動作テスト

OKOK, これで議事録機能はできたかな
ファイルパスのところを、/public/tmp/sample.json って書いてハマってしまったorz
さあ続いてKVS