Giter Club home page Giter Club logo

mps3's Introduction

Multipart to S3 (mps3)

CI

Save uploaded files directly to an S3 compatible API.

Use case

Your app accepts user uploaded files and you need to process those files later in a pool of workers. Instead of saving uploaded files to the web server's tmp and later uploading to a shared staging area, this middleware allows you to upload directly to said staging area. It doesn't allocate disk space in the web server, it uploads to S3 as it reads from the request body.

Example

package main

import (
	"context"
	"log"
	"net/http"
	"strconv"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/gabrielhora/mps3"
)

func main() {
	server := http.NewServeMux()

	server.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		// no need to call `req.ParseMultipartForm()` or `req.ParseForm()`, the middleware
		// will process the data, upload the files and return the following information.

		// suppose a multipart form was posted with fields "file" and "name".
		fileKey := req.Form.Get("file")                                    // "<field>" contains the S3 key where this file was saved
		fileName := req.Form.Get("file_name")                              // "<field>_name" is the original uploaded file name
		fileType := req.Form.Get("file_type")                              // "<field>_type" contains the file content type
		fileSize, _ := strconv.ParseInt(req.Form.Get("file_size"), 10, 64) // "<field>_size" is the file size

		name := req.Form.Get("name") // other fields are accessed normally

		// ...
	}))
	
	s3cfg, _ := config.LoadDefaultConfig(context.Background())

	s3, err := mps3.New(mps3.Config{
		// S3Config you can specify static credentials or custom endpoints if needed.
		// By default if not specified the middleware you load the default configuration.
		S3Config: &s3cfg,

		// ACL used for the bucket when CreateBucket is true
		BucketACL: "private",

		// If true it will try to create the bucket, if the bucket already exists and
		// it belongs to the same account ("BucketAlreadyOwnedByYou") it won't do anything
		CreateBucket: true,

		// ACL used for uploaded files
		FileACL: "private",

		// A logger that is used to print out error messages during request handling
		Logger: log.Default(),

		// Size of the upload chunk to S3 (minimum is 5MB)
		PartSize: 1024 * 1024 * 5,

		// Function called for uploaded files to determine their S3 key prefix.
		// This is the default implementation.
		PrefixFunc: func(req *http.Request) string {
			return time.Now().UTC().Format("/2006/01/02/")
		},
	})
	if err != nil {
		// handle error
	}

	// To use it, just wrap the Handler (either the whole server or specific routes)
	_ = http.ListenAndServe(":8080", s3.Wrap(server))
}

mps3's People

Contributors

gabrielhora avatar

Stargazers

 avatar  avatar  avatar H avatar  avatar yangjun avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.