Go Cheatsheet - Upload file to digitalocean space

·

2 min read

Install packages:

go get github.com/aws/aws-sdk-go
go get github.com/gabriel-vasile/mimetype

Files

In main.go

package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "os"
    "s3upload/s3client"
    "time"

    "github.com/gabriel-vasile/mimetype"
)

func main() {
    if len(os.Args) < 2 {
        log.Fatalln("Missing file path argument")
    }
    filePath := os.Args[1]
    fileContent, _ := ioutil.ReadFile(filePath)
    mimeType := mimetype.Detect(fileContent)
    uploadPath := fmt.Sprintf(
        "test/%d%s",
        time.Now().UnixNano(),
        mimeType.Extension(),
    )

    url, err := s3client.UploadFileFromBytes(
        fileContent,
        uploadPath,
        mimeType.String(),
        "public-read",
    )
    if err != nil {
        log.Fatalln(err)
    }
    log.Println(url)
}

Create a folder s3client and add a s3client.go file:

package s3client

import (
    "bytes"
    "fmt"
    "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"
)

const (
    KEY        string = "<key>"
    SECRET     string = "<secret>"
    ENDPOINT   string = "nyc3.digitaloceanspaces.com"
    REGION     string = "nyc3"
    BUCKET     string = "<bucket>"
    URL_PREFIX string = "<file's url prefix, could be your custom domain>"
)

var (
    Client *s3.S3
)

func UploadFileFromBytes(
    fileContent []byte,
    uploadPath string,
    mimeType string,
    acl string,
) (string, error) {
    object := s3.PutObjectInput{
        Bucket:      aws.String(BUCKET),
        Key:         aws.String(uploadPath),
        Body:        bytes.NewReader(fileContent),
        ACL:         aws.String(acl),
        ContentType: aws.String(mimeType),
    }
    _, err := Client.PutObject(&object)
    if err != nil {
        return "", err
    }
    publicUrl := fmt.Sprintf("%s/%s", URL_PREFIX, uploadPath)
    return publicUrl, nil
}

func init() {
    s3Cred := credentials.NewStaticCredentials(KEY, SECRET, "")
    s3Config := &aws.Config{
        Credentials: s3Cred,
        Endpoint:    aws.String(ENDPOINT),
        Region:      aws.String(REGION),
    }
    sess, err := session.NewSession(s3Config)
    if err != nil {
        log.Fatalln("Failed to create s3 session")
    }
    Client = s3.New(sess)
}

Reference