mps3

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 30, 2022 License: MIT Imports: 20 Imported by: 0

README

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))
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	// S3Config specifies credentials and endpoint configuration. If not specified the middleware
	// will load the default configuration with a background context.
	//
	// To provide a custom endpoint (required when not using AWS S3 API) you can do something like this
	// (more info at https://aws.github.io/aws-sdk-go-v2/docs/configuring-sdk/endpoints/):
	//
	//	resolver := aws.EndpointResolverWithOptionsFunc(func(service, region string, options ...interface{}) (aws.Endpoint, error) {
	//		if service == s3.ServiceID {
	//			return aws.Endpoint{
	//				URL:               "http://localhost:9000",
	//				SigningRegion:     "eu-central-1",
	//				HostnameImmutable: true,
	//			}, nil
	//		}
	//		// returning EndpointNotFoundError will allow the service to fallback to it's default resolution
	//		return aws.Endpoint{}, &aws.EndpointNotFoundError{}
	//	})
	//
	//	s3cfg, err := config.LoadDefaultConfig(context.Background(), config.WithEndpointResolverWithOptions(resolver))
	S3Config *aws.Config

	// Bucket name of the bucket to use to store uploaded files
	Bucket string

	// BucketACL if CreateBucket is true the bucket will be created with this ACL (default: "private")
	BucketACL string

	// CreateBucket if true it will try to create a bucket with the specified Bucket name.
	// Error of type BucketAlreadyOwnedByYou will be silently ignored (default: true)
	CreateBucket bool

	// FileACL defines ACL string to use for uploaded files (default: "private")
	FileACL string

	// PartSize defines the size of the chunk that is uploaded to S3, by default is 5 MB,
	// which is the minimum part size. If a value smaller than the minimum is set, it
	// will be silently adjusted to the minimum.
	PartSize int64

	// PrefixFunc defines a function that gets executed to define the S3 key prefix
	// for each uploaded file. By default it's a function that returns the current date
	// in the format `/YYYY/MM/DD/`
	PrefixFunc func(*http.Request) string

	// Logger is used to log errors during request processing (default: log.Default())
	Logger Logger
}

type Logger

type Logger interface {
	Printf(format string, args ...any)
}

type Wrapper

type Wrapper struct {
	// contains filtered or unexported fields
}

func New

func New(cfg Config) (*Wrapper, error)

func (Wrapper) Wrap

func (wr Wrapper) Wrap(next http.Handler) http.Handler

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL