package handler import ( "fmt" "github.com/aws/aws-sdk-go/aws" "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" ) const DefaultAwsRegion = "eu-west-1" var ( s3Session *session.Session s3Client *s3.S3 s3Uploader *s3manager.Uploader ) func init() { var err error s3Session, err = session.NewSession(&aws.Config{Region: aws.String(DefaultAwsRegion)}) if err != nil { panic(err) } s3Client = s3.New(s3Session) s3Uploader = s3manager.NewUploader(s3Session) } type S3Handler struct { Bucket string ACL string } func NewS3Handler(bucket string, acl string) *S3Handler { return &S3Handler{ Bucket: bucket, ACL: acl, } } func (h *S3Handler) AssetAdded(a Asset) error { result, err := s3Uploader.Upload(&s3manager.UploadInput{ Key: aws.String(a.Key), Bucket: aws.String(h.Bucket), ACL: aws.String(h.ACL), Body: a.Body, }) if err != nil { return err } fmt.Println("Uploaded", a.Name, "to", result.Location) return nil } func (h *S3Handler) AssetRemoved(a Asset) error { // TODO consider cleaning up assets every ~60 seconds? // https://github.com/aws/aws-sdk-go/blob/v1.33.4/service/s3/s3manager/batch.go#L255 _, err := s3Client.DeleteObject(&s3.DeleteObjectInput{ Key: aws.String(a.Key), Bucket: aws.String(h.Bucket), }) if err != nil { return err } return nil }