Skip to content

Instantly share code, notes, and snippets.

@Emmanuerl
Last active May 1, 2024 21:33
Show Gist options
  • Save Emmanuerl/19085f6764a3dbaffdca33470302b33a to your computer and use it in GitHub Desktop.
Save Emmanuerl/19085f6764a3dbaffdca33470302b33a to your computer and use it in GitHub Desktop.
Integrate file uploads and S3 Bucket
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/s3/types"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", handleUpload)
log.Println("Server listening on port 8000")
http.ListenAndServe(":8000", mux)
}
func handleUpload(w http.ResponseWriter, r *http.Request) {
r.ParseMultipartForm(1 * 1024 * 1024 * 10) // 10MB
// assuming you set the `file` field in the formData
file, handler, err := r.FormFile("file")
if err != nil {
respond(w, 500, err.Error())
return
}
defer file.Close()
uploader, err := newS3Client()
if err != nil {
respond(w, 500, err.Error())
return
}
// get the content type from the header
contentType := handler.Header.Get("Content-Type")
key := fmt.Sprintf("%d-%s", time.Now().Unix(), handler.Filename)
_, err = uploader.Upload(r.Context(), &s3.PutObjectInput{
Bucket: aws.String(os.Getenv("AWS_BUCKET")),
Key: aws.String(key),
Body: file,
ACL: types.ObjectCannedACL("public-read"),
ContentType: aws.String(contentType),
})
if err != nil {
respond(w, 500, err.Error())
return
}
respond(w, 200, "Uploaded")
}
func respond(w http.ResponseWriter, status int, message string) {
w.WriteHeader(status)
fmt.Fprint(w, message)
}
func newS3Client() (*manager.Uploader, error) {
cfg, err := config.LoadDefaultConfig(context.TODO(), config.WithRegion(os.Getenv("AWS_REGION")))
if err != nil {
return nil, err
}
storage := s3.NewFromConfig(cfg)
return manager.NewUploader(storage), nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment