Go S3 upload

Posted on Fri 28 April 2017 in Golang

package main

import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/service/s3/s3manager"
    "github.com/aws/aws-sdk-go/aws/session"
    "log"
    "os"
)

func s3Upload(bucket, path, region string) {
    sess := session.Must(session.NewSession(&aws.Config{
        Region: aws.String(region),
    }))

    file, err := os.Open(path)
    if err != nil {
        log.Fatalln("Error when opening", path, err)
    }

    filename := file.Name()

    upparams := &s3manager.UploadInput{
        Bucket: &bucket,
        Key: &filename,
        Body: file,
        ACL: aws.String("private"),
    }

    uploader := s3manager.NewUploader(sess)
    _, err = uploader.Upload(upparams)
    if err != nil {
        log.Fatalln("Error when uploading to S3", err)
    }
}

The above will attempt to retrieve AWS credentials from file (~/.aws/credentials on Linux I think) or fallback to environment variables, ie. AWS_ACCESS_KEY_ID and AWS_SECRET_KEY.

You may want to change the filename variable to get the value from filepath.Base(file.Name()) instead (import "path/filepath"), unless you want to recreate the directory structure for path in S3.