Skip to content

File Uploads, S3 & Serving from a CDN ​

"MaxBytesReader prevents clients from accidentally or maliciously sending a large request and wasting server resources." — Go standard library, net/http documentation of MaxBytesReader

Summary: An upload is untrusted bytes plus untrusted metadata (name, type, size) that you must bound, check, rename and park in object storage; a download is the same object served through a CDN with the right cache headers, validators and access control. Focus: multipart/form-data parsing (ParseMultipartForm, FormFile, MultipartReader), http.MaxBytesReader, filename sanitisation and random object keys, content sniffing with http.DetectContentType, image header limits with image.DecodeConfig, the AWS SDK for Go v2 (s3.Client, manager.Uploader, transfermanager, PresignClient, POST policy), S3-compatible stores (MinIO, Cloudflare R2, DigitalOcean Spaces), bucket policy, IAM and encryption, direct browser uploads with CORS, Content-Disposition, CDN caching (Cache-Control, immutable, versioned keys, ETag, Range), signed URLs and cookies, origin access control, resizing, orphan cleanup and lifecycle rules. Learning goal: Build an upload endpoint that cannot be made to eat your memory, disk or bucket; choose between proxying bytes and presigned direct upload; store objects under keys you control; and serve them through a CDN so that a hit never touches your servers and a private file never leaks.

This page owns the upload and object-storage path in Go. It does not re-teach its neighbours: the HTTP server and client are in net/http, readers and writers (the thing a request body is) in The io Package, local files, temp files and os.Root in Files, Directories, Paths & embed, middleware chains (body limits, CORS) in Middlewares, hashing for content keys in Hashing & Crypto, base64 and hex in Binary-to-Text Encoding. The storage and CDN design level is in Object Storage & File Systems and CDN; the attack catalogue is in OWASP Top 10.

Facts below were checked against the Go 1.27 standard-library source on go.dev (net/http, mime/multipart, image, path/filepath; pkg.go.dev returns 403 to scripted fetches), the Go 1.20 release notes and the godebug page, RFC 7578 and RFC 6266, the aws-sdk-go-v2 source (service/s3, feature/s3/manager, feature/s3/transfermanager), the AWS S3 and CloudFront user guides, Cloudflare R2 and Cache docs, DigitalOcean Spaces docs, the MinIO Go client README, the OWASP File Upload cheat sheet, MDN and the Laravel 13 filesystem docs. Snippets declare go 1.24 and pin the AWS SDK versions that still declare go 1.24 in their go.mod (aws-sdk-go-v2 v1.48.2, service/s3 v1.116.2, feature/s3/manager v1.23.30, feature/s3/transfermanager v0.5.14). They were compiled, vetted and tested with -race on Go 1.27.4 (macOS) against an in-memory store and a fake S3 endpoint served by httptest; no real S3, MinIO, R2, Spaces or CDN was contacted, so provider behaviour is cited from documentation, not observed.

Page map ​

If you are looking forGo to
Everything as tables you can memoriseEverything in one minute
Why uploads need their own designWhy it exists
History and version notesWhere it comes from
A before/after handlerGo
How multipart/form-data reaches your codemultipart/form-data and the three Go APIs
Size and count limits, MaxBytesReaderLimits
Names, filepath.Base, path traversal, random keysNames and keys
Sniffing, DetectContentType, allowlistsContent type
Image bombs, DecodeConfig, virus scanImages and malware
Local disk or object storageWhere to store
s3.Client, PutObject, GetObject, HeadObject, DeleteObjectThe S3 client
manager.Uploader, multipart and resumable uploadsMultipart uploads
PresignClient, expiry, bearer-token riskPresigned URLs
POST policy and content-length-rangePOST policy
Browser straight to the bucket, CORSDirect uploads
MinIO, Cloudflare R2, DigitalOcean SpacesS3-compatible stores
Bucket policy, IAM, Block Public AccessAccess control
SSE-S3, SSE-KMSEncryption
Content-Disposition, download namesDownload names
Cache keys, Cache-Control, immutable, versioned keysCDN caching
Origin access control, signed URLs and cookiesPrivate files
ETag, If-None-Match, 304Conditional GET
Range, 206, videoRange requests
Thumbnails: on upload or on the flyResizing
Orphans and lifecycle rulesCleanup
Limits, errors, SigV4 anatomyMechanics
Typical failures and fixesSolving the classic problems
What to use whenChoosing
Monolith to multi-regionIn architecture
Run the tests and read a presigned URLLab
Laravel Storage and FlysystemFor PHP/Laravel developers

Everything in one minute ​

Two ways to get bytes into a bucket.

PathBytes travelYour server doesGood forBad for
Proxy (multipart POST to your app)Browser, app, bucketParse, limit, sniff, streamSmall files you must inspect before storing (avatars, documents)Big files, many users: you pay the bandwidth
Presigned PUT URLBrowser, bucketValidate intent, sign, recordLarge media, mobile appsAnything you must inspect synchronously
Presigned POST policyBrowser, bucketSign a policy with size rangeBrowser forms with a hard size capR2 (POST not supported), non-browser clients
Multipart or resumable uploadBrowser or server, bucket, in partsCreate, sign parts, completeFiles over about 100 MB, flaky networksTiny files (extra round trips)

The seven checks every upload passes.

#CheckGo toolFailure status
1Total body sizehttp.MaxBytesReader413
2Number of parts and fieldsyour MaxParts counter (ReadForm caps at 1000 only for the parse-everything APIs)400
3File nameSanitizeFilename (display only)none: cleaned
4Extension allowlistmap ext to type415
5Content sniffinghttp.DetectContentType on 512 bytes415
6Image header (before anything is stored)image.DecodeConfig via CheckImage422
7Storage keycrypto/rand, never the client's namenone

Vocabulary map. Every term the topic uses and where it is explained.

TermWhere
multipart/form-datamultipart
r.ParseMultipartForm memory limitmultipart, mechanics
r.FormFilemultipart
r.MultipartReader streamingmultipart
http.MaxBytesReaderlimits
file size and count limitslimits
content type sniffing, http.DetectContentTypecontent type
mimetype magic bytes vs Content-Type headercontent type
extension allowlistcontent type
filename sanitisation, filepath.Base, path traversalnames
random object keysnames
image validation/decoding limits, decompression bombs, image.DecodeConfigimages
virus scan pointerimages
storing locally vs object storagewhere
AWS SDK for Go v2 S3, s3.ClientS3 client
PutObject, GetObject, DeleteObject, HeadObjectS3 client
manager.Uploader multipart, resumable/multipart uploadsmultipart upload
presigned URLs PresignClient PutObject/GetObject, expirypresigned
conditions, POST policyPOST policy
direct-to-S3 browser uploads with presigned URL and CORS on the bucketdirect
S3-compatible, MinIO, Cloudflare R2compatible
DigitalOcean Spaces: endpoint, path stylecompatible
bucket policies and IAM least privilegeIAM
server-side encryption, SSE-S3, SSE-KMSSSE
Content-Disposition and download namesdisposition
serving through a CDNCDN cache
CloudFront/Cloudflare: cache keysCDN cache
Cache-Control, immutable, versioned keysCDN cache
signed URLs/cookies, origin access controlprivate
ETag and conditional GETetag
range requests for videorange
image resizing pipeline, on-upload vs on-the-flyresize
cleanup of orphans, lifecycle rulescleanup
Laravel Storage/Flysystem comparisonPHP

Status codes and errors you will meet.

WhereText or codeMeaning
Go net/httphttp: request body too large (*http.MaxBytesError)A read passed the MaxBytesReader limit
Go mime/multipartmultipart: message too large (ErrMessageTooLarge)Non-file parts did not fit in memory
Go net/httphttp: multipart handled by MultipartReaderYou called FormFile after MultipartReader
Go net/httphttp: MultipartReader called twiceSecond call to MultipartReader
S3 APINoSuchKey, HTTP 404Key missing (HEAD returns 404 with no body)
S3 presignedHTTP 403Expired, wrong signed header, wrong method or key
Browserblocked by CORS policyBucket CORS lacks the origin, method or header

Why it exists ​

A file upload is the one place where an anonymous client chooses the size, the name, the claimed type and the content of what you store, and then asks you to serve it back to other people. Each of those choices is an attack or an outage if you accept it as given: a body of 40 GB fills the disk, a name of ../../app/config.php writes outside the folder, a type of image/png on an HTML file becomes stored cross-site scripting, a 70-byte PNG that claims 60,000 by 60,000 pixels asks the decoder for 14 GB of memory, and 100 users uploading 2 GB videos through your web tier take the site down without any attacker.

Handle uploads yourself on local diskHand them to object storage and a CDN
Simple: os.Create and doneA second system, credentials, a bucket policy
Disk fills, backups of user data on app serversStorage scales without you; durability is the provider's promise, read its SLA
One server holds the file: no horizontal scalingAny instance can serve or sign for any object
Served by your app, every byte through your CPUServed by edge caches near the user
You control everythingYou control keys, policy and headers; the provider owns the disks

An everyday picture. A parcel depot. The counter clerk (your handler) weighs the parcel (size limit), checks that the label matches the contents (sniffing, not trusting the sender's note), puts it in a numbered locker whose number the sender did not choose (random key), and gives out a collection slip (URL). Heavy freight skips the counter: the clerk writes a dated loading-dock pass (presigned URL) and the driver unloads straight into the warehouse. The courier network (CDN) keeps popular parcels in local depots so most pickups never reach the warehouse.

Three common misunderstandings, up front ​

  1. "The Content-Type of the part tells me what the file is." It is a string the client typed. Only the bytes (the first 512 are enough to sniff) say what the file looks like, and even that is a guess.
  2. "Go cleans the filename, so I can use it as the path." Part.FileName applies filepath.Base, which is platform dependent: on Linux a Windows path survives. And even a clean name collides, overwrites and leaks information. The storage key must not come from the client.
  3. "A presigned URL is secure because it is signed." It is a bearer token: whoever holds it can do the signed operation until it expires. Sign the narrowest operation, for the shortest time, and never log the URL.

Where it comes from ​

Browsers upload files with multipart/form-data, specified for the web in RFC 7578 (2015). Section 4.2 of that RFC says that if a filename is supplied, "do not use directory path information that may be present", and the Go reader follows it: Part.FileName returns filepath.Base of the parameter. Go 1.20 release notes added limits to mime/multipart as protection against malicious inputs, backported to Go 1.19.8 and 1.20.3: at most 10000 headers per part and 1000 parts per form, tunable with GODEBUG=multipartmaxheaders and multipartmaxparts. http.MaxBytesReader and its error type MaxBytesError live in net/http; http.MaxBytesHandler wraps a whole handler.

On the AWS side, S3 applies server-side encryption with S3-managed keys (SSE-S3) to every new object since January 5, 2023, and newer general purpose buckets disable SSE-C by default (AWS S3 user guide, April 2026 note). In the SDK, feature/s3/manager (the Uploader and Downloader) is marked "Deprecated: superceded by feature/s3/transfermanager"; a maintainer announced transfermanager as generally available on January 30, 2026 (aws-sdk-go-v2 discussion 3306). CloudFront recommends origin access control (OAC) over the legacy origin access identity (OAI) because OAC supports all regions, SSE-KMS and PUT/DELETE to S3.

Go ​

Before ​

The handler from most tutorials. It works on a quiet day, and the test next to it proves six problems: no body limit, the client's name as the file name (so two users overwrite each other), no look at the bytes, a trusted Content-Type, one server's disk, and no cleanup.

go
// Package before is the upload handler most tutorials start with. It works on
// a quiet day and has six problems; the test next to it proves each one.
package before

import (
	"encoding/json"
	"io"
	"net/http"
	"os"
	"path/filepath"
)

// Handler saves the "file" field into dir under the name the client chose.
func Handler(dir string) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// 1. No http.MaxBytesReader: the body can be any size. The 32 MiB only
		//    decides how much stays in memory before spilling to temp files.
		if err := r.ParseMultipartForm(32 << 20); err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
		file, header, err := r.FormFile("file")
		if err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
		defer file.Close()

		// 2. The client's name is the storage key: two users uploading
		//    "avatar.png" overwrite each other, and "index.html" lands next to
		//    your own pages.
		dst, err := os.Create(filepath.Join(dir, header.Filename))
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		defer dst.Close()

		// 3. Nothing looks at the bytes, and the extension is not checked.
		if _, err := io.Copy(dst, file); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		// 4. The Content-Type header is the client's claim; it is echoed back
		//    and would be used when serving the file.
		_ = json.NewEncoder(w).Encode(map[string]string{
			"name":         header.Filename,
			"content_type": header.Header.Get("Content-Type"),
		})
		// 5. The file lives on this server's disk: a second instance cannot
		//    serve it. 6. No cleanup, no record, no quota.
	})
}
go
package before

import (
	"bytes"
	"mime/multipart"
	"net/http"
	"net/http/httptest"
	"net/textproto"
	"os"
	"path/filepath"
	"strings"
	"testing"
)

func upload(t *testing.T, h http.Handler, filename, ctype string, body []byte) *httptest.ResponseRecorder {
	t.Helper()
	var buf bytes.Buffer
	mw := multipart.NewWriter(&buf)
	hdr := textproto.MIMEHeader{}
	hdr.Set("Content-Disposition", `form-data; name="file"; filename="`+filename+`"`)
	hdr.Set("Content-Type", ctype)
	part, _ := mw.CreatePart(hdr)
	_, _ = part.Write(body)
	_ = mw.Close()
	req := httptest.NewRequest(http.MethodPost, "/upload", &buf)
	req.Header.Set("Content-Type", mw.FormDataContentType())
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, req)
	return rec
}

func TestBeforeAcceptsEverything(t *testing.T) {
	dir := t.TempDir()
	h := Handler(dir)

	// Problem 4 + 3: HTML labelled as an image is accepted and the lie is echoed.
	rec := upload(t, h, "cat.png", "image/png", []byte("<script>alert(1)</script>"))
	if rec.Code != 200 || !strings.Contains(rec.Body.String(), `"content_type":"image/png"`) {
		t.Fatalf("expected the lie to be accepted: %d %s", rec.Code, rec.Body)
	}

	// Problem 2: the second upload with the same name silently replaces the first.
	upload(t, h, "avatar.png", "image/png", []byte("alice"))
	upload(t, h, "avatar.png", "image/png", []byte("mallory"))
	got, _ := os.ReadFile(filepath.Join(dir, "avatar.png"))
	if string(got) != "mallory" {
		t.Fatalf("expected overwrite, got %q", got)
	}

	// Problem 3: a .php file is stored as-is; whether it runs depends on the web server in front.
	if rec := upload(t, h, "shell.php", "image/png", []byte("<?php echo 1;")); rec.Code != 200 {
		t.Fatalf("php accepted: %d", rec.Code)
	}

	// Problem 1: 8 MiB goes straight through; nothing caps the body.
	if rec := upload(t, h, "big.bin", "application/octet-stream", bytes.Repeat([]byte("z"), 8<<20)); rec.Code != 200 {
		t.Fatalf("big body: %d", rec.Code)
	}

	// Go's multipart reader already applies filepath.Base to the file name, so
	// a "../" prefix is cut off here. It does NOT cut a Windows-style path on
	// Linux, so the safe design never uses the client's name as a key at all.
	upload(t, h, "../../escape.txt", "text/plain", []byte("x"))
	if _, err := os.Stat(filepath.Join(dir, "escape.txt")); err != nil {
		t.Fatalf("Part.FileName should have reduced the name to its base: %v", err)
	}
}

After ​

The same endpoint hardened: MaxBytesReader, a streaming MultipartReader, per-file cap, file count, sanitised display name, allowlist plus sniffing plus declared type, random key, and a Store interface so S3, MinIO or an in-memory fake all fit.

go
// Package after is the same endpoint, hardened: bounded body, streaming
// multipart parsing, per-file and per-request limits, allowlist plus content
// sniffing, random object keys and a pluggable object store.
package after

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"io"
	"log/slog"
	"mime/multipart"
	"net/http"
	"strings"
	"time"

	"academy/file-uploads-s3-cdn/keys"
	"academy/file-uploads-s3-cdn/objstore"
	"academy/file-uploads-s3-cdn/validate"
)

// Config is the policy. Every limit is explicit.
type Config struct {
	MaxBody   int64 // whole request, including multipart framing
	MaxFile   int64 // one file's bytes
	MaxFiles  int   // file parts per request
	MaxField  int64 // bytes of any non-file field
	MaxParts  int   // all parts, fields and files together
	Image     validate.ImageLimits
	Allowed   validate.Allowlist
	KeyPrefix string
	Now       func() time.Time
}

// Result is what the client gets back (and what you would insert in a table).
type Result struct {
	Key         string `json:"key"`
	Name        string `json:"name"`
	ContentType string `json:"content_type"`
	Size        int64  `json:"size"`
}

// errTooLarge is returned by capReader when a single file passes MaxFile.
var errTooLarge = errors.New("file too large")

// errFieldTooLarge is returned for a text field above MaxField.
var errFieldTooLarge = errors.New("form field too large")

// errTooManyParts means fields plus files exceeded MaxParts.
var errTooManyParts = errors.New("too many parts")

// capReader fails (instead of silently truncating, like io.LimitReader) when
// more than n bytes are read, and counts what it passed on.
type capReader struct {
	r    io.Reader
	left int64
	n    int64
}

func (c *capReader) Read(p []byte) (int, error) {
	if c.left <= 0 {
		// Probe one byte: EOF exactly at the limit is fine.
		var one [1]byte
		n, err := c.r.Read(one[:])
		if n > 0 {
			return 0, errTooLarge
		}
		return 0, err // io.EOF stays EOF; a real failure is not hidden
	}
	if int64(len(p)) > c.left {
		p = p[:c.left]
	}
	n, err := c.r.Read(p)
	c.left -= int64(n)
	c.n += int64(n)
	return n, err
}

// Handler streams each file part to the store without buffering the whole
// file in memory or on disk.
func Handler(cfg Config, store objstore.Store) http.Handler {
	if cfg.Now == nil {
		cfg.Now = time.Now
	}
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Hard cap on the whole body. Reading past it returns *http.MaxBytesError
		// and the server closes the connection after the response.
		r.Body = http.MaxBytesReader(w, r.Body, cfg.MaxBody)

		// MultipartReader parses as a stream. ParseMultipartForm would parse the
		// entire body first (spilling to temp files past its memory limit),
		// which is the wrong shape when the destination is object storage.
		mr, err := r.MultipartReader()
		if err != nil {
			http.Error(w, "expected multipart/form-data", http.StatusBadRequest)
			return
		}
		var results []Result
		parts := 0
		for {
			part, err := mr.NextPart()
			if errors.Is(err, io.EOF) {
				break
			}
			if err != nil {
				discard(r.Context(), store, results)
				writeErr(w, err)
				return
			}
			// Every part counts, fields included: when streaming, nothing else
			// enforces the 1000-part cap that ReadForm applies.
			parts++
			if parts > cfg.MaxParts {
				discard(r.Context(), store, results)
				writeErr(w, errTooManyParts)
				return
			}
			if part.FileName() == "" { // an ordinary form field
				// Read one byte more than allowed and fail: LimitReader alone
				// would silently truncate and the next NextPart would drain the rest.
				n, err := io.Copy(io.Discard, io.LimitReader(part, cfg.MaxField+1))
				if err == nil && n > cfg.MaxField {
					err = errFieldTooLarge
				}
				if err != nil {
					discard(r.Context(), store, results)
					writeErr(w, err)
					return
				}
				continue
			}
			if len(results) >= cfg.MaxFiles {
				discard(r.Context(), store, results)
				http.Error(w, "too many files", http.StatusBadRequest)
				return
			}
			res, err := handleFile(r.Context(), cfg, store, part)
			if err != nil {
				discard(r.Context(), store, results)
				writeErr(w, err)
				return
			}
			results = append(results, res)
		}
		if len(results) == 0 {
			http.Error(w, "no file part", http.StatusBadRequest)
			return
		}
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusCreated)
		_ = json.NewEncoder(w).Encode(results)
	})
}

func handleFile(ctx context.Context, cfg Config, store objstore.Store, part *multipart.Part) (Result, error) {
	// 1. The client's name is display metadata only.
	name := validate.SanitizeFilename(part.FileName())
	ext := validate.Extension(name)

	// 2. Read the first 512 bytes: that is all http.DetectContentType uses.
	head := make([]byte, 512)
	n, err := io.ReadFull(part, head)
	if err != nil && !errors.Is(err, io.ErrUnexpectedEOF) && !errors.Is(err, io.EOF) {
		return Result{}, err
	}
	head = head[:n]

	// 3. Extension allowlist + sniffed type + declared type must agree.
	ctype, err := cfg.Allowed.Check(ext, head, part.Header.Get("Content-Type"))
	if err != nil {
		return Result{}, err
	}

	// 4. A random key; the original name never reaches the store.
	key, err := keys.Random(cfg.KeyPrefix, ext, cfg.Now())
	if err != nil {
		return Result{}, err
	}

	// 5. Stream the sniffed head plus the rest of the part, capped at MaxFile.
	body := &capReader{r: io.MultiReader(bytes.NewReader(head), part), left: cfg.MaxFile}
	var src io.Reader = body
	if strings.HasPrefix(ctype, "image/") {
		// Images: the header can sit past byte 512 (JPEG EXIF), so hold the
		// file (at most MaxFile bytes) and check the dimensions before any
		// byte is stored. Large media should use the direct-upload path.
		data, err := io.ReadAll(body)
		if err != nil {
			return Result{}, err
		}
		if _, _, err := validate.CheckImage(bytes.NewReader(data), cfg.Image); err != nil {
			return Result{}, err
		}
		src = bytes.NewReader(data)
	}
	meta := objstore.Meta{
		ContentType:  ctype,
		CacheControl: "private, max-age=0, must-revalidate",
	}
	if err := store.Put(ctx, key, src, meta); err != nil {
		// A failed Put must not leave a half object behind (the S3 uploader
		// aborts its multipart upload; Delete covers stores that do not).
		if delErr := store.Delete(context.WithoutCancel(ctx), key); delErr != nil {
			slog.Warn("cleanup after failed upload", "key", key, "err", delErr)
		}
		return Result{}, err
	}
	return Result{Key: key, Name: name, ContentType: ctype, Size: body.n}, nil
}

// discard removes files stored earlier in the same request, so a request is
// all-or-nothing from the client's point of view.
func discard(ctx context.Context, store objstore.Store, done []Result) {
	for _, r := range done {
		if err := store.Delete(context.WithoutCancel(ctx), r.Key); err != nil {
			slog.Warn("cleanup", "key", r.Key, "err", err)
		}
	}
}

// writeErr maps internal errors to HTTP statuses.
func writeErr(w http.ResponseWriter, err error) {
	var mbe *http.MaxBytesError
	switch {
	case errors.As(err, &mbe), errors.Is(err, errTooLarge), errors.Is(err, errFieldTooLarge):
		http.Error(w, "payload too large", http.StatusRequestEntityTooLarge)
	case errors.Is(err, validate.ErrExtension), errors.Is(err, validate.ErrSniffed), errors.Is(err, validate.ErrMismatch):
		http.Error(w, "unsupported media type", http.StatusUnsupportedMediaType)
	case errors.Is(err, validate.ErrTooBig), errors.Is(err, validate.ErrNotImage):
		http.Error(w, "image rejected", http.StatusUnprocessableEntity)
	case errors.Is(err, errTooManyParts):
		http.Error(w, "too many parts", http.StatusBadRequest)
	default:
		slog.Error("upload failed", "err", err)
		http.Error(w, "upload failed", http.StatusBadRequest)
	}
}

Tests cover the accept path and the rejections (type, extension, mismatch, file size, body size, file count, total parts, oversized field, huge image dimensions, and a cap reader that must pass through underlying errors), and assert that a rejected request leaves nothing in the store.

go
package after

import (
	"bytes"
	"encoding/binary"
	"encoding/json"
	"errors"
	"hash/crc32"
	"image"
	"image/png"
	"io"
	"mime/multipart"
	"net/http"
	"net/http/httptest"
	"net/textproto"
	"strings"
	"testing"
	"time"

	"academy/file-uploads-s3-cdn/objstore"
	"academy/file-uploads-s3-cdn/validate"
)

func testConfig() Config {
	return Config{
		MaxBody:   64 << 10,
		MaxFile:   32 << 10,
		MaxFiles:  2,
		MaxField:  1 << 10,
		Allowed:   validate.Allowlist{".png": "image/png", ".pdf": "application/pdf"},
		KeyPrefix: "uploads",
		MaxParts:  6,
		Image:     validate.ImageLimits{MaxWidth: 4096, MaxHeight: 4096, MaxPixels: 16 << 20},
		Now:       func() time.Time { return time.Date(2026, 11, 28, 0, 0, 0, 0, time.UTC) },
	}
}

type filePartSpec struct {
	name, ctype string
	body        []byte
}

func post(t *testing.T, h http.Handler, fields map[string]string, files ...filePartSpec) *httptest.ResponseRecorder {
	t.Helper()
	var buf bytes.Buffer
	mw := multipart.NewWriter(&buf)
	for k, v := range fields {
		_ = mw.WriteField(k, v)
	}
	for _, f := range files {
		hdr := textproto.MIMEHeader{}
		hdr.Set("Content-Disposition", `form-data; name="file"; filename="`+f.name+`"`)
		if f.ctype != "" {
			hdr.Set("Content-Type", f.ctype)
		}
		p, _ := mw.CreatePart(hdr)
		_, _ = p.Write(f.body)
	}
	_ = mw.Close()
	req := httptest.NewRequest(http.MethodPost, "/upload", &buf)
	req.Header.Set("Content-Type", mw.FormDataContentType())
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, req)
	return rec
}

func tinyPNG(t *testing.T) []byte {
	t.Helper()
	var b bytes.Buffer
	if err := png.Encode(&b, image.NewRGBA(image.Rect(0, 0, 8, 8))); err != nil {
		t.Fatal(err)
	}
	return b.Bytes()
}

func TestAcceptsValidPNG(t *testing.T) {
	store := objstore.NewMem()
	h := Handler(testConfig(), store)
	rec := post(t, h, map[string]string{"title": "hi"}, filePartSpec{`..\..\my photo.png`, "image/png", tinyPNG(t)})
	if rec.Code != http.StatusCreated {
		t.Fatalf("status %d: %s", rec.Code, rec.Body)
	}
	var res []Result
	if err := json.Unmarshal(rec.Body.Bytes(), &res); err != nil || len(res) != 1 {
		t.Fatalf("%v %s", err, rec.Body)
	}
	r := res[0]
	if r.Name != "my photo.png" || r.ContentType != "image/png" || r.Size != int64(len(tinyPNG(t))) {
		t.Fatalf("result %+v", r)
	}
	if !strings.HasPrefix(r.Key, "uploads/2026/11/") || strings.Contains(r.Key, "photo") {
		t.Fatalf("key must be random and not contain the client's name: %q", r.Key)
	}
	if keys := store.Keys(""); len(keys) != 1 || keys[0] != r.Key {
		t.Fatalf("store has %v", keys)
	}
}

func TestRejections(t *testing.T) {
	good := tinyPNG(t)
	html := []byte("<!DOCTYPE html><script>alert(1)</script>")
	cases := []struct {
		name  string
		files []filePartSpec
		want  int
	}{
		{"html with a lying png header", []filePartSpec{{"cat.png", "image/png", html}}, 415},
		{"php extension", []filePartSpec{{"shell.php", "image/png", good}}, 415},
		{"png bytes declared as html", []filePartSpec{{"cat.png", "text/html", good}}, 415},
		{"png bytes with a pdf name", []filePartSpec{{"cat.pdf", "application/pdf", good}}, 415},
		{"one file over MaxFile", []filePartSpec{{"big.png", "image/png", append(append([]byte{}, good...), bytes.Repeat([]byte{0}, 40<<10)...)}}, 413},
		{"body over MaxBody", []filePartSpec{{"a.png", "image/png", append(append([]byte{}, good...), bytes.Repeat([]byte{0}, 30<<10)...)}, {"b.png", "image/png", append(append([]byte{}, good...), bytes.Repeat([]byte{0}, 30<<10)...)}}, 413},
		{"too many files", []filePartSpec{{"1.png", "image/png", good}, {"2.png", "image/png", good}, {"3.png", "image/png", good}}, 400},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			store := objstore.NewMem()
			cfg := testConfig()
			cfg.MaxBody = 48 << 10 // two 30 KiB files fit one by one but not together
			rec := post(t, Handler(cfg, store), nil, c.files...)
			if rec.Code != c.want {
				t.Fatalf("status %d (%s), want %d", rec.Code, strings.TrimSpace(rec.Body.String()), c.want)
			}
			if got := store.Keys(""); len(got) != 0 {
				t.Fatalf("a rejected request must leave no objects, found %v", got)
			}
		})
	}
}

func TestFileExactlyAtLimitIsAccepted(t *testing.T) {
	cfg := testConfig()
	base := tinyPNG(t)
	cfg.MaxFile = int64(len(base))
	rec := post(t, Handler(cfg, objstore.NewMem()), nil, filePartSpec{"ok.png", "image/png", base})
	if rec.Code != http.StatusCreated {
		t.Fatalf("a file of exactly MaxFile bytes must pass: %d %s", rec.Code, rec.Body)
	}
}

func TestNotMultipart(t *testing.T) {
	req := httptest.NewRequest(http.MethodPost, "/upload", strings.NewReader("{}"))
	req.Header.Set("Content-Type", "application/json")
	rec := httptest.NewRecorder()
	Handler(testConfig(), objstore.NewMem()).ServeHTTP(rec, req)
	if rec.Code != http.StatusBadRequest {
		t.Fatalf("status %d", rec.Code)
	}
}

func TestAllPartsAreCounted(t *testing.T) {
	// 7 text fields, no file: ReadForm's 1000-part cap is not in play when streaming,
	// so the handler must enforce its own cap on every part, fields included.
	fields := map[string]string{}
	for i := 0; i < 7; i++ {
		fields[string(rune('a'+i))] = "x"
	}
	store := objstore.NewMem()
	rec := post(t, Handler(testConfig(), store), fields, filePartSpec{"ok.png", "image/png", tinyPNG(t)})
	if rec.Code != http.StatusBadRequest {
		t.Fatalf("status %d, want 400 (too many parts)", rec.Code)
	}
	if len(store.Keys("")) != 0 {
		t.Fatal("nothing may be stored")
	}
}

func TestOversizedFieldIsRejectedNotTruncated(t *testing.T) {
	store := objstore.NewMem()
	rec := post(t, Handler(testConfig(), store), map[string]string{"title": strings.Repeat("a", 2048)}, filePartSpec{"ok.png", "image/png", tinyPNG(t)})
	if rec.Code != http.StatusRequestEntityTooLarge {
		t.Fatalf("status %d, want 413 for a 2048-byte field under MaxField=1024", rec.Code)
	}
	if len(store.Keys("")) != 0 {
		t.Fatal("nothing may be stored")
	}
}

func bombPNG(t *testing.T, w, h uint32) []byte {
	b := tinyPNG(t)
	binary.BigEndian.PutUint32(b[16:], w)
	binary.BigEndian.PutUint32(b[20:], h)
	binary.BigEndian.PutUint32(b[29:], crc32.ChecksumIEEE(b[12:29]))
	return b
}

func TestHugeDimensionsAreRejectedBeforeStoring(t *testing.T) {
	store := objstore.NewMem()
	rec := post(t, Handler(testConfig(), store), nil, filePartSpec{"bomb.png", "image/png", bombPNG(t, 60000, 60000)})
	if rec.Code != http.StatusUnprocessableEntity {
		t.Fatalf("status %d, want 422", rec.Code)
	}
	if len(store.Keys("")) != 0 {
		t.Fatal("the bomb must not reach the store")
	}
}

type failReader struct{ err error }

func (f failReader) Read([]byte) (int, error) { return 0, f.err }

func TestCapReaderPropagatesUnderlyingError(t *testing.T) {
	boom := errors.New("connection reset")
	c := &capReader{r: failReader{boom}, left: 0}
	if _, err := c.Read(make([]byte, 8)); !errors.Is(err, boom) {
		t.Fatalf("got %v, want the underlying error, not io.EOF", err)
	}
	c = &capReader{r: strings.NewReader("ab"), left: 0}
	if _, err := c.Read(make([]byte, 8)); !errors.Is(err, errTooLarge) {
		t.Fatalf("data past the cap: %v", err)
	}
	c = &capReader{r: strings.NewReader(""), left: 0}
	if _, err := c.Read(make([]byte, 8)); err != io.EOF {
		t.Fatalf("clean EOF at the cap: %v", err)
	}
}
Every check runs before the first byte reaches the bucket1 Cap bodyMaxBytesReader4132 Stream partsMultipartReadercount: 4003 Clean nameBase, no ctrl charsdisplay only4 Extensionallowlist4155 Sniff 512 bytesDetectContentType4156 Comparedeclared = sniffed= extension7 Image headerDecodeConfigw x h limits8 Random keycrypto/randnever the name9 Stream to storecapped per fileabort on error10 Scan, re-encodeasync workerquarantine prefixSolid boxes run in the request. The dashed box runs after the response: a virus scanner or an image re-encodecan take seconds, so the object stays in a pending state until it passes.Nothing here trusts the client: name, Content-Type header, size claim and extension are all inputs, not facts.

The Go angle ​

A request body is an io.Reader, and an object-store upload is an io.Reader consumer, so Go lets you connect them without ever holding the file: MaxBytesReader wraps the body, MultipartReader hands you one part reader at a time, you peek 512 bytes with io.ReadFull, glue them back with io.MultiReader, cap the stream with your own reader and give it to Uploader.Upload. Memory stays at one part buffer, and when any reader returns an error the upload is aborted. The stdlib also gives you the sniffing algorithm (http.DetectContentType), the image header reader (image.DecodeConfig), the cache-aware file server (http.ServeContent) and the content-disposition encoder (mime.FormatMediaType), so most of this chapter is composition, not libraries.

The concept catalogue ​

multipart/form-data and the three Go APIs Must-know ​

In plain words: A browser form with a file input sends one HTTP body made of several parts separated by a boundary string; each part has its own headers (field name, file name, type) and bytes. Go gives you three ways to read it: parse everything first (ParseMultipartForm), ask for one file (FormFile), or walk the parts as a stream (MultipartReader).

Common misunderstanding: "r.ParseMultipartForm(10 << 20) limits uploads to 10 MB." The number is a memory limit, not a size limit. The docs say the whole request body is parsed and up to a total of maxMemory bytes of its file parts are stored in memory "with the remainder stored on disk in temporary files". A 5 GB upload still arrives; it just lands in /tmp.

Definition: Request.ParseMultipartForm(maxMemory) parses the whole body and fills r.MultipartForm; the underlying Reader.ReadForm stores up to maxMemory bytes plus a reserved 10 MB for non-file parts in memory and returns multipart.ErrMessageTooLarge ("multipart: message too large") if the non-file parts do not fit. Request.FormFile(key) calls ParseMultipartForm(32 << 20) if needed (the defaultMaxMemory constant) and returns the first file for that key. Request.MultipartReader() returns a *multipart.Reader "to process the request body as a stream"; after it, FormFile fails with http: multipart handled by MultipartReader. Temporary files are removed by r.MultipartForm.RemoveAll() (the server calls it when the handler returns).

ParseMultipartForm / FormFile                    MultipartReader
1  read headers, find boundary                   read headers, find boundary
2  read ALL parts until the end                  mr.NextPart()  -> part 1 reader
3    small file parts -> memory (up to maxMemory)  you read, check, forward to S3
4    the rest -> os.CreateTemp files              mr.NextPart()  -> part 2 reader
5  handler runs; you open files again            ...
6  server removes the temp files after return    io.EOF: done; nothing on local disk

Real scenario: an avatar endpoint where FormFile is fine because the limit is 2 MB; a video endpoint where ParseMultipartForm wrote 3 GB to /tmp and filled the root volume of a container; a document service that must reject a PDF before the second part is read and therefore uses MultipartReader; a mobile app sending the file field before the metadata field, which breaks any streaming code that assumes the opposite order.

APIReads bodyMemoryDiskOrder of partsUse when
r.ParseMultipartForm(n)All of it, before your code runsUp to n plus 10 MBTemp files above nAnySmall forms, many fields
r.FormFile("file")Same, with n = 32 MBSameSameAnySingle small file
r.MultipartReader() streamingOne part at a timeOne bufferNoneSequential onlyForward to object storage, early rejection
r.Body raw (PUT of bytes)As you readOne bufferNonen/aAPI clients, presigned PUT shape

Fix / how to use it: for anything that ends in object storage, use MultipartReader under MaxBytesReader (the after handler above). Treat fields that must come first (such as an upload id) as part of your protocol and reject requests that send them late.

Limits: MaxBytesReader, size and count Must-know ​

In plain words: Decide the largest request, the largest file, the most files and the longest text field you accept, and make the server stop reading the moment a client crosses any of them.

Common misunderstanding: "I check header.Size or the Content-Length header, so I am protected." FileHeader.Size is not a number the client declared: ReadForm computes it from the bytes it actually read (fh.Size is assigned from the buffer length or the copied byte count). That makes it accurate and also too late: by the time you can read it, the whole body has already been received and spilled to memory or temporary files. Content-Length is a client claim and can be absent (chunked encoding) or wrong. Only counting bytes as they are read, under MaxBytesReader, protects resources.

Definition: http.MaxBytesReader(w, r.Body, n) returns an io.ReadCloser that returns a *http.MaxBytesError (message http: request body too large) for a read beyond n, closes the underlying reader on Close, and "if possible, it tells the ResponseWriter to close the connection after the limit has been reached". http.MaxBytesHandler(h, n) applies it to every request of a handler. Because io.LimitReader silently returns EOF at the limit, it makes a truncated upload look complete; use it only with an explicit check (the capReader in the snippet returns an error on the first byte past the limit instead). mime/multipart limits ReadForm to 1000 parts and 10000 headers (that is, when you use ParseMultipartForm or FormFile); a handler that streams with MultipartReader does not get that cap, so it must count every part, fields included, itself (MaxParts in the snippet).

client                         server (MaxBytesReader 64 KiB)
1  POST 40 GB body ----------> read 64 KiB .......... ok
2                              read byte 65537 ...... *http.MaxBytesError
3  <------- 413 + Connection: close (server stops reading)
4  client sees the reset or the 413, depending on timing

Real scenario: a profile page with one 2 MB photo; a gallery with up to 10 files of 10 MB each (so a 100 MB request cap and a 10 MB file cap, not just one of them); a CSV import of 50 MB under a different route with its own limit; a malicious client sending 10 million empty parts (stopped by your own MaxParts count; the streaming reader has no built-in cap, and ReadForm's 1000-part limit applies only to the full-parse APIs).

LimitWhereTypical valueError to client
Request bodyMaxBytesReader or MaxBytesHandlerSlightly above files times max size413
One fileyour capReaderPer product (2 MB avatar, 100 MB video)413
File countyour counter1 to 10400
Text fieldio.LimitReader plus check1 KiB400 or 413
Parts per formReadForm (1000) applies to ParseMultipartForm/FormFile only; streaming code uses its own MaxPartsGODEBUG=multipartmaxparts is process-wide400
Idle and total timehttp.Server.ReadTimeout, ReadHeaderTimeout, http.ResponseControllerGenerous for uploads, per routeconnection closed
Proxy in frontnginx client_max_body_size, ALB, CDNMatch your limit413 from the proxy

Fix / how to use it: put a body limit in middleware for every non-upload route (small, for example 1 MiB) and a larger explicit one on upload routes; see Middlewares. A long upload needs longer read deadlines on that route only: http.ResponseController.SetReadDeadline extends them per request.

Names and keys: filename sanitisation, path traversal, random object keys Must-know ​

In plain words: The name the user's computer called the file is a label to show back to them, never the place you store it. Store under a key you generate; keep the original name in your database.

Common misunderstanding: "filepath.Base(header.Filename) makes the name safe." Part.FileName already does that, and it fixes ../../x on any OS. It does not fix a Windows path on Linux (..\..\x), a leading dot (.htaccess), a NUL byte, control characters, a 4 KB name, reserved names on Windows, or two users choosing the same name. RFC 7578 itself says not to use the name blindly.

Definition: Path traversal is a name or key that escapes the intended directory (../, absolute paths, encoded separators). filepath.Base returns the last element of a path using the separators of the current platform. A random object key is a key built from crypto/rand bytes (128 bits is enough), optionally with a date prefix, plus an extension taken from your allowlist, not from the client.

client says               what each layer does                         stored key
1  "../../etc/passwd"     Part.FileName -> "passwd"                   uploads/2026/11/9f2c...e1
2  "..\..\evil.exe"       Part.FileName -> unchanged on Linux         (SanitizeFilename -> "evil.exe", display only)
3  ".htaccess"            SanitizeFilename -> "htaccess"
4  "cv.pdf" (user A)      key = random                                uploads/2026/11/3a71...b0
5  "cv.pdf" (user B)      key = random, no overwrite                  uploads/2026/11/c8d4...2f

Real scenario: local-disk storage where uploads/ sits inside the web root and a .php or .html upload is executed or served as a page; a Windows client sending C:\Users\x\cv.pdf; a customer support tool that lists "original name" from the database while the bucket only sees random keys; a predictable uploads/123.png scheme that lets anyone enumerate every file.

ApproachOverwriteEnumerableLeaks client dataVerdict
Client's name as the keyYesIf names are guessableYes (usernames in paths)Never
Counter (1.png, 2.png)NoYesNoOnly behind auth
Random 128-bit (keys.Random)NoNoNoDefault
Content hash (keys.Content)Same bytes, same objectBy known content onlyNoDedupe, immutable caching
Hash prefix in a versioned name (app.3f2a9c1d.css)Per versionNoNoStatic assets

Fix / how to use it: the snippet's validate.SanitizeFilename produces the display name (both separators, no controls, no leading dots, at most 100 runes, file if empty) and keys.Random the key. OWASP's File Upload cheat sheet says the same: "Change the filename to something generated by the application", "Set a filename length limit" and reject : in names (NTFS alternate data streams).

go
// Package validate holds the checks an upload must pass before any byte is
// stored: filename sanitising, extension allowlist, content sniffing and image
// header limits.
package validate

import (
	"errors"
	"fmt"
	"image"
	"io"
	"net/http"
	"path"
	"strings"
	"unicode"

	// Register the decoders image.DecodeConfig can read headers for.
	_ "image/gif"
	_ "image/jpeg"
	_ "image/png"
)

// Errors the handler maps to HTTP status codes.
var (
	ErrExtension = errors.New("extension not allowed")
	ErrSniffed   = errors.New("content does not match an allowed type")
	ErrMismatch  = errors.New("declared type, extension and content disagree")
	ErrTooBig    = errors.New("image dimensions exceed the limit")
	ErrNotImage  = errors.New("not a decodable image")
)

// SanitizeFilename turns a client-supplied name into a safe display name. It
// is NOT used to build storage keys; keys are random (see package keys).
//
// Go's multipart Part.FileName already runs filepath.Base, but that is
// platform dependent: on Linux a Windows path such as C:\x\evil.php survives
// intact. So treat both separators, drop control characters and leading dots,
// and cap the length.
func SanitizeFilename(name string) string {
	name = strings.ReplaceAll(name, `\`, "/")
	name = path.Base(name) // "." for empty, "/" for all separators
	var b strings.Builder
	for _, r := range name {
		switch {
		case r == 0 || unicode.IsControl(r):
			continue
		case r == '"' || r == ';' || r == ':' || r == '<' || r == '>' || r == '|' || r == '*' || r == '?':
			b.WriteRune('_')
		default:
			b.WriteRune(r)
		}
	}
	out := strings.TrimLeft(b.String(), ".")
	out = strings.TrimSpace(out)
	if r := []rune(out); len(r) > 100 {
		out = string(r[:100])
	}
	if out == "" || out == "/" {
		return "file"
	}
	return out
}

// Extension returns the lower-cased extension including the dot, or "".
func Extension(name string) string {
	return strings.ToLower(path.Ext(name))
}

// Allowlist maps a file extension to the one content type we accept for it.
type Allowlist map[string]string

// Check validates extension, sniffed content and the client's declared type
// together and returns the canonical content type to store.
//
//   - ext is the lower-cased extension of the sanitised name.
//   - head is the first bytes of the file (at most 512 are used).
//   - declared is the Content-Type the client put on the part; it is only
//     compared, never trusted.
func (a Allowlist) Check(ext string, head []byte, declared string) (string, error) {
	want, ok := a[ext]
	if !ok {
		return "", fmt.Errorf("%w: %q", ErrExtension, ext)
	}
	sniffed := Sniff(head)
	if sniffed != want {
		return "", fmt.Errorf("%w: sniffed %q, extension %q wants %q", ErrSniffed, sniffed, ext, want)
	}
	if declared != "" && !strings.EqualFold(stripParams(declared), want) {
		return "", fmt.Errorf("%w: declared %q", ErrMismatch, declared)
	}
	return want, nil
}

// Sniff returns the media type of the first 512 bytes using
// http.DetectContentType (the WHATWG MIME Sniffing algorithm), without
// parameters such as "; charset=utf-8".
func Sniff(head []byte) string {
	if len(head) > 512 {
		head = head[:512]
	}
	return stripParams(http.DetectContentType(head))
}

func stripParams(ct string) string {
	if i := strings.IndexByte(ct, ';'); i >= 0 {
		ct = ct[:i]
	}
	return strings.TrimSpace(ct)
}

// ImageLimits bounds what the decoder may be asked to allocate.
type ImageLimits struct {
	MaxWidth, MaxHeight int
	MaxPixels           int64 // width*height; a 16-bit RGBA image costs 8 bytes per pixel
}

// CheckImage reads only the image header (image.DecodeConfig does not
// allocate the pixel buffer) and rejects files whose declared dimensions would
// make a later image.Decode allocate far more memory than the file size
// suggests: a decompression bomb.
func CheckImage(r io.Reader, l ImageLimits) (image.Config, string, error) {
	cfg, format, err := image.DecodeConfig(r)
	if err != nil {
		return image.Config{}, "", fmt.Errorf("%w: %v", ErrNotImage, err)
	}
	if cfg.Width <= 0 || cfg.Height <= 0 ||
		cfg.Width > l.MaxWidth || cfg.Height > l.MaxHeight ||
		int64(cfg.Width)*int64(cfg.Height) > l.MaxPixels {
		return cfg, format, fmt.Errorf("%w: %dx%d", ErrTooBig, cfg.Width, cfg.Height)
	}
	return cfg, format, nil
}
go
// Package keys builds object keys and download headers.
//
// The rule: the storage key is never derived from anything the client chose.
// The client's file name is metadata (a database column, a Content-Disposition
// header), not an address.
package keys

import (
	"crypto/rand"
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"mime"
	"strings"
	"time"
)

// Random returns "<prefix>/<yyyy>/<mm>/<32 hex chars><ext>". 128 random bits
// from crypto/rand make keys unguessable (so a public URL is not enumerable)
// and collision-free in practice; the date prefix helps lifecycle rules and
// listings, and S3 spreads load by key prefix on its own.
func Random(prefix, ext string, now time.Time) (string, error) {
	var b [16]byte
	if _, err := rand.Read(b[:]); err != nil {
		return "", err
	}
	return fmt.Sprintf("%s/%04d/%02d/%s%s", strings.Trim(prefix, "/"), now.Year(), int(now.Month()), hex.EncodeToString(b[:]), ext), nil
}

// Content returns a content-addressed key, "<prefix>/<ab>/<sha256 hex><ext>".
// The same bytes always map to the same key, and a key never changes meaning,
// so it can be cached with "immutable" for a year. Uploading the same file
// twice stores it once.
func Content(prefix string, data []byte, ext string) string {
	sum := sha256.Sum256(data)
	h := hex.EncodeToString(sum[:])
	return fmt.Sprintf("%s/%s/%s%s", strings.Trim(prefix, "/"), h[:2], h, ext)
}

// Versioned inserts a short content hash before the extension:
// "app.css" -> "app.3f2a9c1d.css". Use it for assets whose logical name stays
// stable in your HTML but whose bytes change.
func Versioned(name string, data []byte) string {
	sum := sha256.Sum256(data)
	h := hex.EncodeToString(sum[:])[:8]
	i := strings.LastIndexByte(name, '.')
	if i < 0 {
		return name + "." + h
	}
	return name[:i] + "." + h + name[i:]
}

// Disposition returns a Content-Disposition value ("attachment" or "inline")
// with the file name encoded per RFC 6266 / RFC 5987: ASCII names become
// filename="..." with quotes escaped; other names become the percent-encoded
// extended parameter filename* with the UTF-8 charset label.
// The mime package does the quoting and encoding, so a quote or semicolon in
// the name cannot inject a parameter.
func Disposition(kind, filename string) string {
	if kind != "inline" {
		kind = "attachment"
	}
	if v := mime.FormatMediaType(kind, map[string]string{"filename": filename}); v != "" {
		return v
	}
	return kind // FormatMediaType returns "" for an invalid token
}
go
package keys

import (
	"mime"
	"regexp"
	"strings"
	"testing"
	"time"
)

func TestRandomKeys(t *testing.T) {
	now := time.Date(2026, 11, 28, 10, 0, 0, 0, time.UTC)
	re := regexp.MustCompile(`^uploads/2026/11/[0-9a-f]{32}\.png$`)
	seen := map[string]bool{}
	for i := 0; i < 1000; i++ {
		k, err := Random("/uploads/", ".png", now)
		if err != nil {
			t.Fatal(err)
		}
		if !re.MatchString(k) {
			t.Fatalf("bad key %q", k)
		}
		if seen[k] {
			t.Fatalf("collision on %q", k)
		}
		seen[k] = true
	}
}

func TestContentAndVersionedKeys(t *testing.T) {
	a := Content("assets", []byte("same"), ".css")
	b := Content("assets", []byte("same"), ".css")
	c := Content("assets", []byte("different"), ".css")
	if a != b || a == c {
		t.Fatalf("content keys must be a function of the bytes: %q %q %q", a, b, c)
	}
	if !strings.HasPrefix(a, "assets/") || !strings.HasSuffix(a, ".css") {
		t.Fatalf("shape: %q", a)
	}
	v1, v2 := Versioned("app.css", []byte("v1")), Versioned("app.css", []byte("v2"))
	if v1 == v2 || !strings.HasPrefix(v1, "app.") || !strings.HasSuffix(v1, ".css") || len(v1) != len("app.")+8+len(".css") {
		t.Fatalf("versioned: %q %q", v1, v2)
	}
	if got := Versioned("LICENSE", []byte("x")); !strings.HasPrefix(got, "LICENSE.") {
		t.Fatalf("no extension: %q", got)
	}
}

func TestDisposition(t *testing.T) {
	cases := []struct {
		kind, name string
		wantParam  string
	}{
		{"attachment", "report.pdf", "report.pdf"},
		{"attachment", "Q4 \"final\"; rm -rf.pdf", "Q4 \"final\"; rm -rf.pdf"},
		{"inline", "résumé.pdf", "résumé.pdf"},
		{"attachment", "گزارش.pdf", "گزارش.pdf"},
		{"bogus", "x.txt", "x.txt"},
	}
	for _, c := range cases {
		v := Disposition(c.kind, c.name)
		typ, params, err := mime.ParseMediaType(v)
		if err != nil {
			t.Fatalf("%q does not parse: %v", v, err)
		}
		if params["filename"] != c.wantParam {
			t.Errorf("%q: filename round-trips as %q, want %q", v, params["filename"], c.wantParam)
		}
		if typ != "attachment" && typ != "inline" {
			t.Errorf("type %q", typ)
		}
		if len(params) != 1 {
			t.Errorf("%q: a hostile name must not add parameters: %v", v, params)
		}
	}
	if v := Disposition("attachment", "گزارش.pdf"); !strings.Contains(v, "filename*=utf-8''") {
		t.Errorf("non-ASCII names need the RFC 5987 form: %q", v)
	}
	if v := Disposition("bogus", "x.txt"); !strings.HasPrefix(v, "attachment") {
		t.Errorf("unknown kind falls back to attachment: %q", v)
	}
}

Content type: sniffing, magic bytes and the extension allowlist Must-know ​

In plain words: Three things claim to say what a file is: its extension, the Content-Type the browser put on the part, and its first bytes. Only the bytes are evidence, and even they are only a guess; so accept a file only when all three agree and the type is on your list.

Common misunderstanding: "I check the Content-Type header against my allowlist, so only images get in." The header is whatever the client wrote. A curl -F 'file=@shell.html;type=image/png' passes that check. The OWASP cheat sheet says it directly: "Validate the file type, don't trust the Content-Type header as it can be spoofed".

Definition: Content type sniffing means deducing a media type from content. http.DetectContentType(data) "implements the algorithm described at https://mimesniff.spec.whatwg.org/ to determine the Content-Type of the given data. It considers at most the first 512 bytes" and returns application/octet-stream when nothing matches. Libraries such as github.com/gabriel-vasile/mimetype match more formats by magic bytes (signature at a known offset). An extension allowlist maps the extensions you accept to the single type each must sniff as. The mimetype magic bytes vs Content-Type header comparison is the check that catches a lie.

file bytes                          ext      declared header   sniffed (512 B)    result
1  89 50 4E 47 ...                  .png     image/png         image/png          accept
2  "<!DOCTYPE html><script>..."     .png     image/png         text/html          415
3  89 50 4E 47 ...                  .png     text/html         image/png          415 (disagree)
4  89 50 4E 47 ...                  .php     image/png         image/png          415 (extension)
5  "%PDF-1.7 ..."                   .pdf     application/pdf   application/pdf    accept

Real scenario: an image upload that must never serve HTML from your origin; a document portal accepting .pdf and .docx (a DOCX sniffs as a ZIP, so the allowlist maps .docx to application/zip or you use a library with Office signatures); a polyglot file that is a valid image for its first 512 bytes and a script after that; double extensions (photo.jpg.php) that fool a regex written for .jpg.

CheckCatchesMisses
Extension allowlistExecutable extensions, double extensions (use the last one)Any lie with a good extension
Declared Content-TypeHonest mistakesEverything an attacker controls
DetectContentType on 512 bytesHTML named .png, scripts named .jpgPolyglots, content after byte 512, Office formats (ZIP)
image.DecodeConfigNon-images, huge dimensionsValid images with hostile metadata
Full decode and re-encodeAppended payloads, EXIFDecoder bugs (keep Go updated)
Serve with the stored type plus nosniffBrowser type guessingNothing; always do it

Fix / how to use it: Allowlist.Check in the snippet compares extension, sniffed type and declared type and returns the canonical type to store as the object's Content-Type. The origin handler adds X-Content-Type-Options: nosniff so a browser does not second-guess the stored type. Reject by extension too: double extensions are decided by the last one, and .html, .svg and .js should not be on an allowlist for a user-content origin (SVG can carry script).

Images: validation and decoding limits, decompression bombs, malware Must-know ​

In plain words: A small compressed image can unpack to gigabytes in memory. Read only the header first, compare the claimed width and height with your limits, and only then decode (or better, decode, resize and re-encode, so you store pixels you generated).

Common misunderstanding: "A 70-byte file cannot hurt me." The snippet's test builds a valid PNG of 74 bytes whose header claims 60000 by 60000 pixels: 3.6 billion pixels, 14.4 GB as RGBA. File size says nothing about decoded size.

Definition: A decompression bomb (here an image bomb) is input that is tiny encoded and huge decoded. image.DecodeConfig(r) "reads only format headers and does not allocate a full-size pixel buffer, so it can be used to check dimensions before calling Decode" (comment in image/format.go, Go 1.27). Image validation/decoding limits are your maximum width, height and pixel count, checked against that result. A virus scan pointer is the reminder that none of this finds malware: for documents and archives run an antivirus engine or a content disarm and reconstruction step, asynchronously, with the object in a quarantine state until it passes.

1  client uploads 74-byte PNG, IHDR says 60000 x 60000
2  validate.CheckImage -> image.DecodeConfig reads only the header -> Config{60000, 60000}
3  60000*60000 = 3_600_000_000 pixels > MaxPixels (16 Mi) -> ErrTooBig -> reject (no pixel buffer ever allocated)
4  without step 2: image.Decode would try to allocate width*height*4 bytes

Real scenario: avatar upload where a 10 MP phone photo is fine and a 100 MP panorama is refused; a thumbnail worker killed by the out-of-memory killer on one crafted file; a document service that quarantines uploads under quarantine/ and moves them to clean/ after a scanner callback; a GIF with thousands of frames (check the frame count if you decode GIFs).

LimitMeaningStarting point
Max width and heightRejects absurd single sides8192
Max pixels (width times height)Bounds decoder memory (about 4 bytes per pixel for RGBA, more for 16-bit)16 to 50 million
Max file bytesBounds transfer and storagePer product
Decode concurrencyBounds total memoryA semaphore sized to RAM / worst case
TimeoutBounds the whole job, not a running Decode (the decoders take no context)A deadline around the worker; the real CPU bound is the size and dimension limits above

Fix / how to use it: the hardened handler holds an image part (at most MaxFile bytes), calls validate.CheckImage and only then stores it; resize.Thumbnail also runs CheckImage before image.Decode and re-encodes, which drops EXIF (GPS position, camera serial) and any bytes appended after the image data (its test proves a <?php tail is gone). A context deadline does not bound decoding CPU: image.Decode takes an io.Reader, not a context, and keeps running after the context expires. What bounds it is the input limits (bytes, width, height, pixels), a worker pool with a fixed size so concurrent decodes cannot exhaust memory, and a timeout around the whole job that abandons the result (the goroutine still finishes, which is why the limits matter).

go
package validate

import (
	"bytes"
	"encoding/binary"
	"errors"
	"hash/crc32"
	"image"
	"image/color"
	"image/png"
	"strings"
	"testing"
)

func TestSanitizeFilename(t *testing.T) {
	cases := []struct{ in, want string }{
		{"photo.JPG", "photo.JPG"},
		{"../../etc/passwd", "passwd"},
		{`..\..\windows\system32\evil.exe`, "evil.exe"},
		{`C:\Users\me\cv.pdf`, "cv.pdf"},
		{".htaccess", "htaccess"},
		{"a\x00b.png", "ab.png"},
		{"na\u202eme.png", "na\u202eme.png"}, // bidi override is not a control char in unicode.IsControl; documented limit
		{`we"ird;name.txt`, "we_ird_name.txt"},
		{"", "file"},
		{"///", "file"},
		{strings.Repeat("a", 300) + ".png", strings.Repeat("a", 100)},
	}
	for _, c := range cases {
		if got := SanitizeFilename(c.in); got != c.want {
			t.Errorf("SanitizeFilename(%q) = %q, want %q", c.in, got, c.want)
		}
	}
}

func pngBytes(t *testing.T, w, h int) []byte {
	t.Helper()
	img := image.NewRGBA(image.Rect(0, 0, w, h))
	img.Set(0, 0, color.RGBA{R: 255, A: 255})
	var b bytes.Buffer
	if err := png.Encode(&b, img); err != nil {
		t.Fatal(err)
	}
	return b.Bytes()
}

// bombPNG is a tiny, valid PNG whose IHDR claims huge dimensions. The IDAT
// data is the 1x1 image's; DecodeConfig never reads it.
func bombPNG(t *testing.T, w, h uint32) []byte {
	b := pngBytes(t, 1, 1)
	// IHDR data starts at byte 16 (8 signature + 4 length + 4 type); CRC follows its 13 bytes.
	binary.BigEndian.PutUint32(b[16:], w)
	binary.BigEndian.PutUint32(b[20:], h)
	binary.BigEndian.PutUint32(b[29:], crc32.ChecksumIEEE(b[12:29]))
	return b
}

func TestAllowlistCheck(t *testing.T) {
	al := Allowlist{".png": "image/png", ".jpg": "image/jpeg", ".pdf": "application/pdf"}
	png1 := pngBytes(t, 4, 4)
	html := []byte("<!DOCTYPE html><html><script>alert(1)</script></html>")

	if ct, err := al.Check(".png", png1, "image/png"); err != nil || ct != "image/png" {
		t.Fatalf("good png: %q %v", ct, err)
	}
	if _, err := al.Check(".png", png1, ""); err != nil {
		t.Fatalf("missing declared type is allowed: %v", err)
	}
	if _, err := al.Check(".php", png1, "image/png"); !errors.Is(err, ErrExtension) {
		t.Fatalf("php must be rejected by extension: %v", err)
	}
	if _, err := al.Check(".png", html, "image/png"); !errors.Is(err, ErrSniffed) {
		t.Fatalf("HTML named .png with a lying header must be rejected by sniffing: %v", err)
	}
	if _, err := al.Check(".png", png1, "text/html"); !errors.Is(err, ErrMismatch) {
		t.Fatalf("png bytes declared as text/html must be rejected: %v", err)
	}
	if _, err := al.Check(".jpg", png1, "image/jpeg"); !errors.Is(err, ErrSniffed) {
		t.Fatalf("png bytes with a .jpg name must be rejected: %v", err)
	}
	if got := Sniff([]byte("%PDF-1.7 ...")); got != "application/pdf" {
		t.Fatalf("pdf sniff = %q", got)
	}
}

func TestSniffReadsAtMost512Bytes(t *testing.T) {
	// A polyglot: valid text for 600 bytes, then binary. DetectContentType
	// only looks at the first 512 bytes, so a check on the head cannot see
	// what comes later. That is why we also bound size and re-encode images.
	head := append(bytes.Repeat([]byte("a"), 600), 0x00, 0x01)
	if got := Sniff(head); !strings.HasPrefix(got, "text/plain") {
		t.Fatalf("got %q", got)
	}
}

func TestCheckImageLimits(t *testing.T) {
	lim := ImageLimits{MaxWidth: 4096, MaxHeight: 4096, MaxPixels: 16 << 20}
	if cfg, f, err := CheckImage(bytes.NewReader(pngBytes(t, 640, 480)), lim); err != nil || f != "png" || cfg.Width != 640 {
		t.Fatalf("ok image: %+v %q %v", cfg, f, err)
	}
	b := bombPNG(t, 60000, 60000) // ~3.6 gigapixels in about 70 bytes of file
	if len(b) > 200 {
		t.Fatalf("the bomb should be tiny, got %d bytes", len(b))
	}
	if _, _, err := CheckImage(bytes.NewReader(b), lim); !errors.Is(err, ErrTooBig) {
		t.Fatalf("bomb must be rejected before decoding: %v", err)
	}
	if _, _, err := CheckImage(strings.NewReader("not an image"), lim); !errors.Is(err, ErrNotImage) {
		t.Fatalf("garbage: %v", err)
	}
	// Within each side limit but over the pixel budget.
	if _, _, err := CheckImage(bytes.NewReader(bombPNG(t, 4096, 4096)), ImageLimits{MaxWidth: 4096, MaxHeight: 4096, MaxPixels: 1 << 20}); !errors.Is(err, ErrTooBig) {
		t.Fatalf("pixel budget: %v", err)
	}
}

Storing locally vs object storage Must-know ​

In plain words: Local disk is the simplest place to put a file and the first thing that breaks when you add a second server, a deploy, a container restart or a backup requirement. Object storage is a network service that stores named blobs with HTTP semantics.

Common misunderstanding: "Object storage is a remote file system." It has no directories (a key is a flat string and / is a convention), no append or in-place edit, no rename (copy then delete), no locking, and per-request latency. Treat it as a key-to-blob map with metadata.

Definition: Storing locally vs object storage is a choice of where the bytes of an upload live. Local means a path on the instance's disk (os.Create, see Files & Directories). Object storage means an S3-style bucket reached by HTTPS, addressed by bucket plus key, with operations PutObject, GetObject, HeadObject, DeleteObject and listing.

1  user uploads avatar -> instance A writes /var/app/uploads/a.png
2  next request goes to instance B -> 404 (file is on A's disk)
3  deploy replaces the container -> A's disk is gone
4  object storage: A and B both PutObject/GetObject on bucket "uploads" -> same bytes

Real scenario: a single VPS where local disk plus nightly backup is genuinely fine; Kubernetes pods with ephemeral disks; a shared NFS mount (works, but you rebuilt object storage badly); a laptop dev environment using MinIO or the in-memory Store.

CriterionLocal diskNetwork file systemObject storage
SetupNoneMount, permissionsBucket, credentials, policy
Scales across instancesNoYes, with locking caveatsYes
Survives redeployOnly on a volumeYesYes
Serve directly to browsersThrough your appThrough your appPresigned URL or CDN
Atomic replaceRenameRename (mostly)Overwrite a key is atomic per object
Cost shapeDiskDisk plus IOPSStorage plus requests plus egress

Fix / how to use it: write handlers against objstore.Store (Put, Get, Head, Delete) from day one. The in-memory implementation serves tests, the s3store implementation serves production, and a local-disk implementation can serve a single-server deployment without changing a handler.

go
// Package objstore defines the small storage interface the upload code
// depends on, and an in-memory implementation used by every test.
package objstore

import (
	"context"
	"crypto/md5"
	"encoding/hex"
	"errors"
	"io"
	"sort"
	"strings"
	"sync"
	"time"
)

// ErrNotFound is returned when a key does not exist.
var ErrNotFound = errors.New("objstore: key not found")

// Meta is the metadata the application cares about. It maps onto the S3
// response headers of the same names.
type Meta struct {
	ContentType        string
	Size               int64
	ETag               string
	CacheControl       string
	ContentDisposition string
	LastModified       time.Time
}

// Store is what handlers use. S3, MinIO, Cloudflare R2 and DigitalOcean Spaces
// all fit behind it, and so does the in-memory fake.
type Store interface {
	Put(ctx context.Context, key string, body io.Reader, meta Meta) error
	Get(ctx context.Context, key string) (io.ReadCloser, Meta, error)
	Head(ctx context.Context, key string) (Meta, error)
	Delete(ctx context.Context, key string) error
}

type object struct {
	data []byte
	meta Meta
}

// Mem is a concurrency-safe in-memory Store.
type Mem struct {
	mu   sync.Mutex
	objs map[string]object
	Now  func() time.Time
}

// NewMem returns an empty store.
func NewMem() *Mem { return &Mem{objs: map[string]object{}, Now: time.Now} }

// Put reads the whole body; if the reader fails, nothing is stored (like an
// aborted multipart upload).
func (m *Mem) Put(ctx context.Context, key string, body io.Reader, meta Meta) error {
	data, err := io.ReadAll(body)
	if err != nil {
		return err
	}
	sum := md5.Sum(data)
	meta.Size = int64(len(data))
	meta.ETag = `"` + hex.EncodeToString(sum[:]) + `"`
	meta.LastModified = m.Now()
	m.mu.Lock()
	defer m.mu.Unlock()
	m.objs[key] = object{data: data, meta: meta}
	return nil
}

// Get returns a reader over a copy of the object.
func (m *Mem) Get(ctx context.Context, key string) (io.ReadCloser, Meta, error) {
	m.mu.Lock()
	defer m.mu.Unlock()
	o, ok := m.objs[key]
	if !ok {
		return nil, Meta{}, ErrNotFound
	}
	return io.NopCloser(strings.NewReader(string(o.data))), o.meta, nil
}

// Head returns metadata only.
func (m *Mem) Head(ctx context.Context, key string) (Meta, error) {
	m.mu.Lock()
	defer m.mu.Unlock()
	o, ok := m.objs[key]
	if !ok {
		return Meta{}, ErrNotFound
	}
	return o.meta, nil
}

// Delete is idempotent, like S3: deleting a missing key is not an error.
func (m *Mem) Delete(ctx context.Context, key string) error {
	m.mu.Lock()
	defer m.mu.Unlock()
	delete(m.objs, key)
	return nil
}

// Keys lists keys with the given prefix in lexical order (a stand-in for
// ListObjectsV2).
func (m *Mem) Keys(prefix string) []string {
	m.mu.Lock()
	defer m.mu.Unlock()
	var out []string
	for k := range m.objs {
		if strings.HasPrefix(k, prefix) {
			out = append(out, k)
		}
	}
	sort.Strings(out)
	return out
}

The AWS SDK for Go v2 S3 client: PutObject, GetObject, HeadObject, DeleteObject Must-know ​

In plain words: s3.Client is a typed wrapper over the S3 REST API. You build it once (credentials, region, optional endpoint), share it between goroutines, and call one method per operation. It is the same client for Amazon S3 and for any S3-compatible service.

Common misunderstanding: "I need config.LoadDefaultConfig and the AWS environment to use it." That is the usual path in production (environment variables, shared config, IAM roles, IRSA), but s3.New(s3.Options{...}) with static credentials, Region, BaseEndpoint and UsePathStyle needs no environment at all, which is what makes the snippet tests hermetic.

Definition: github.com/aws/aws-sdk-go-v2/service/s3 exposes PutObject, GetObject, HeadObject and DeleteObject (and ListObjectsV2, CopyObject, multipart operations). Success and failure are values: a missing key is *types.NoSuchKey (GET) or *types.NotFound (HEAD, which has no body), found with errors.As. DeleteObject returns success whether or not the key existed. GetObjectOutput.Body is an io.ReadCloser you must close. PutObject with a plain io.Reader needs its length (the SDK wants a seekable body for signing); streaming a request body of unknown length is what manager.Uploader is for.

op            HTTP                              outcome
1  PutObject    PUT  /bucket/key  (Content-Type, Cache-Control, body)   200 + ETag
2  HeadObject   HEAD /bucket/key                                         200 + size, type, ETag  |  404 NotFound
3  GetObject    GET  /bucket/key  (optional Range, If-None-Match)       200 | 206 | 304 | 404 NoSuchKey
4  DeleteObject DELETE /bucket/key                                      204 (also when absent)

Real scenario: an s3store.Store behind the objstore.Store interface so handlers stay testable; a worker that HeadObjects a key after a direct browser upload to confirm size and type before marking the row committed; a delete job that is safe to re-run because deletes are idempotent; a migration tool that reads from one endpoint and writes to another.

OperationMutatesIdempotentNotes
PutObjectYesYes (same key overwrites)Max 5 GiB per single PUT in S3; use multipart above that
GetObjectNoYesRange, IfNoneMatch, ResponseContentDisposition available
HeadObjectNoYesCheap existence and metadata check
DeleteObjectYesYesNo error for a missing key
CopyObjectYesYesServer-side copy; "rename" is copy plus delete
ListObjectsV2NoYesUp to 1,000 keys per response (SDK doc comment); paginate with the continuation token

Fix / how to use it: build one client per provider config and wrap it. In the snippet NewClient also sets RequestChecksumCalculation and ResponseChecksumValidation to WhenRequired, because many S3-compatible servers predate the default CRC checksums the SDK began sending; if an S3-compatible service rejects requests with checksum or aws-chunked errors, this is the first option to try (stated as a practical note from the SDK options, not tested against any real provider).

go
// Package s3store implements objstore.Store on top of the AWS SDK for Go v2.
// The same code talks to Amazon S3, MinIO, Cloudflare R2 and DigitalOcean
// Spaces: only Config changes.
package s3store

import (
	"context"
	"errors"
	"io"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/credentials"
	"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"

	"academy/file-uploads-s3-cdn/objstore"
)

// Config holds everything that differs between S3-compatible providers.
type Config struct {
	Endpoint  string // empty for AWS; e.g. http://127.0.0.1:9000 (MinIO), https://<account>.r2.cloudflarestorage.com (R2)
	Region    string // "us-east-1" for MinIO, "auto" for R2, e.g. "nyc3" for Spaces
	AccessKey string
	SecretKey string
	PathStyle bool // MinIO and most self-hosted servers need path-style addressing
	Bucket    string
}

// NewClient builds an *s3.Client without touching the environment, so tests
// and local runs never read ~/.aws.
func NewClient(c Config) *s3.Client {
	return s3.New(s3.Options{
		Region:       c.Region,
		Credentials:  credentials.NewStaticCredentialsProvider(c.AccessKey, c.SecretKey, ""),
		BaseEndpoint: endpoint(c.Endpoint),
		UsePathStyle: c.PathStyle,
		// Many S3-compatible servers predate the default CRC32 checksums the
		// SDK started adding in early 2025; compute them only when an operation
		// requires them.
		RequestChecksumCalculation: aws.RequestChecksumCalculationWhenRequired,
		ResponseChecksumValidation: aws.ResponseChecksumValidationWhenRequired,
	})
}

func endpoint(e string) *string {
	if e == "" {
		return nil
	}
	return aws.String(e)
}

// Store is an objstore.Store backed by one bucket.
type Store struct {
	Client   *s3.Client
	Bucket   string
	Uploader *manager.Uploader
}

// New wires a Store. PartSize 5 MiB is the S3 minimum; Concurrency 5 is the
// SDK default.
func New(client *s3.Client, bucket string) *Store {
	return &Store{
		Client: client,
		Bucket: bucket,
		Uploader: manager.NewUploader(client, func(u *manager.Uploader) {
			u.PartSize = manager.MinUploadPartSize
			u.Concurrency = manager.DefaultUploadConcurrency
		}),
	}
}

// Put streams body to S3. The Uploader buffers one part at a time, so memory
// is PartSize x Concurrency, not the object size; bodies that fit in one part
// go out as a single PutObject, larger ones as a multipart upload that is
// aborted if the reader fails.
func (s *Store) Put(ctx context.Context, key string, body io.Reader, m objstore.Meta) error {
	in := &s3.PutObjectInput{
		Bucket: aws.String(s.Bucket),
		Key:    aws.String(key),
		Body:   body,
	}
	if m.ContentType != "" {
		in.ContentType = aws.String(m.ContentType)
	}
	if m.CacheControl != "" {
		in.CacheControl = aws.String(m.CacheControl)
	}
	if m.ContentDisposition != "" {
		in.ContentDisposition = aws.String(m.ContentDisposition)
	}
	_, err := s.Uploader.Upload(ctx, in)
	return err
}

// Get returns the object body; the caller must Close it.
func (s *Store) Get(ctx context.Context, key string) (io.ReadCloser, objstore.Meta, error) {
	out, err := s.Client.GetObject(ctx, &s3.GetObjectInput{Bucket: aws.String(s.Bucket), Key: aws.String(key)})
	if err != nil {
		return nil, objstore.Meta{}, mapErr(err)
	}
	return out.Body, objstore.Meta{
		ContentType:        aws.ToString(out.ContentType),
		Size:               aws.ToInt64(out.ContentLength),
		ETag:               aws.ToString(out.ETag),
		CacheControl:       aws.ToString(out.CacheControl),
		ContentDisposition: aws.ToString(out.ContentDisposition),
		LastModified:       aws.ToTime(out.LastModified),
	}, nil
}

// Head reads metadata without the body.
func (s *Store) Head(ctx context.Context, key string) (objstore.Meta, error) {
	out, err := s.Client.HeadObject(ctx, &s3.HeadObjectInput{Bucket: aws.String(s.Bucket), Key: aws.String(key)})
	if err != nil {
		return objstore.Meta{}, mapErr(err)
	}
	return objstore.Meta{
		ContentType:  aws.ToString(out.ContentType),
		Size:         aws.ToInt64(out.ContentLength),
		ETag:         aws.ToString(out.ETag),
		CacheControl: aws.ToString(out.CacheControl),
		LastModified: aws.ToTime(out.LastModified),
	}, nil
}

// Delete removes the object. S3 answers 204 whether or not the key existed.
func (s *Store) Delete(ctx context.Context, key string) error {
	_, err := s.Client.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: aws.String(s.Bucket), Key: aws.String(key)})
	return mapErr(err)
}

func mapErr(err error) error {
	if err == nil {
		return nil
	}
	var nf *types.NotFound
	var nk *types.NoSuchKey
	if errors.As(err, &nf) || errors.As(err, &nk) {
		return objstore.ErrNotFound
	}
	return err
}

The test runs the whole round trip against an httptest server that speaks path-style S3, and asserts the request URLs the SDK produced:

go
package s3store

import (
	"bytes"
	"errors"
	"io"
	"strings"
	"testing"

	"academy/file-uploads-s3-cdn/objstore"
)

func newStore(t *testing.T) (*Store, *fakeS3) {
	t.Helper()
	f := newFakeS3()
	t.Cleanup(f.srv.Close)
	c := NewClient(Config{Endpoint: f.srv.URL, Region: "us-east-1", AccessKey: "AKIDEXAMPLE", SecretKey: "secret", PathStyle: true, Bucket: "uploads"})
	return New(c, "uploads"), f
}

func TestPutGetHeadDelete(t *testing.T) {
	ctx := t.Context()
	s, f := newStore(t)

	if err := s.Put(ctx, "u/1.txt", strings.NewReader("hello"), objstore.Meta{ContentType: "text/plain"}); err != nil {
		t.Fatal(err)
	}
	// Path-style addressing: the bucket is the first path segment, not a host name.
	if f.count("PUT /uploads/u/1.txt") != 1 {
		t.Fatalf("requests: %v", f.log)
	}
	h, err := s.Head(ctx, "u/1.txt")
	if err != nil || h.Size != 5 || h.ContentType != "text/plain" {
		t.Fatalf("head = %+v, %v", h, err)
	}
	rc, _, err := s.Get(ctx, "u/1.txt")
	if err != nil {
		t.Fatal(err)
	}
	b, _ := io.ReadAll(rc)
	_ = rc.Close()
	if string(b) != "hello" {
		t.Fatalf("body %q", b)
	}
	if err := s.Delete(ctx, "u/1.txt"); err != nil {
		t.Fatal(err)
	}
	if _, err := s.Head(ctx, "u/1.txt"); !errors.Is(err, objstore.ErrNotFound) {
		t.Fatalf("head after delete: %v", err)
	}
	if _, _, err := s.Get(ctx, "u/1.txt"); !errors.Is(err, objstore.ErrNotFound) {
		t.Fatalf("get after delete: %v", err)
	}
}

func TestUploaderUsesMultipartAboveOnePart(t *testing.T) {
	ctx := t.Context()
	s, f := newStore(t)
	// 12 MiB + 1 byte with 5 MiB parts = 3 parts (5, 5, 2 MiB + 1).
	data := bytes.Repeat([]byte("x"), 12<<20+1)

	// A plain io.Reader (no Seek, no length) is exactly what a request body is.
	if err := s.Put(ctx, "big.bin", io.MultiReader(bytes.NewReader(data)), objstore.Meta{ContentType: "application/octet-stream"}); err != nil {
		t.Fatal(err)
	}
	if n := f.count("PUT /uploads/big.bin?partNumber"); n != 3 {
		t.Fatalf("want 3 UploadPart calls, got %d: %v", n, f.log)
	}
	if f.count("POST /uploads/big.bin?uploads") != 1 || f.count("POST /uploads/big.bin?uploadId") != 1 {
		t.Fatalf("want one Create and one Complete: %v", f.log)
	}
	f.mu.Lock()
	defer f.mu.Unlock()
	if !bytes.Equal(f.objects["/uploads/big.bin"], data) {
		t.Fatal("assembled object differs from the input")
	}
}

func TestSmallBodyIsOnePutObject(t *testing.T) {
	s, f := newStore(t)
	if err := s.Put(t.Context(), "small", strings.NewReader("tiny"), objstore.Meta{}); err != nil {
		t.Fatal(err)
	}
	if f.count("PUT /uploads/small?partNumber") != 0 || f.count("POST") != 0 {
		t.Fatalf("a body under one part must be a single PutObject: %v", f.log)
	}
}

type errAfter struct {
	n   int
	err error
}

func (e *errAfter) Read(p []byte) (int, error) {
	if e.n <= 0 {
		return 0, e.err
	}
	n := min(len(p), e.n)
	for i := 0; i < n; i++ {
		p[i] = 'y'
	}
	e.n -= n
	return n, nil
}

func TestReaderErrorAbortsMultipart(t *testing.T) {
	s, f := newStore(t)
	boom := errors.New("client went away")
	err := s.Put(t.Context(), "broken", &errAfter{n: 7 << 20, err: boom}, objstore.Meta{})
	if err == nil {
		t.Fatal("want error")
	}
	if f.count("DELETE /uploads/broken?uploadId") != 1 {
		t.Fatalf("the Uploader must abort the multipart upload so parts are not billed: %v", f.log)
	}
	f.mu.Lock()
	defer f.mu.Unlock()
	if _, ok := f.objects["/uploads/broken"]; ok {
		t.Fatal("a failed upload must not create the object")
	}
}

Multipart, resumable uploads and manager.Uploader Must-know ​

In plain words: Big objects are sent as numbered parts, in parallel and with retries per part, then glued by one final call. If the connection drops you resend one part, not the file.

Common misunderstanding: "If the upload fails, S3 throws away what it got." Uploaded parts of an unfinished multipart upload stay and are billed as storage until someone aborts the upload. The S3 guide recommends a lifecycle rule with AbortIncompleteMultipartUpload (its example uses DaysAfterInitiation 7).

Definition: The S3 multipart protocol is CreateMultipartUpload (returns an upload id), UploadPart for part numbers 1 to 10,000, each 5 MiB to 5 GiB except the last, each returning an ETag, then CompleteMultipartUpload with the list of numbers and ETags, or AbortMultipartUpload. The S3 guide gives the maximum object size as 48.8 TiB and advises considering multipart at around 100 MB. In Go, manager.Uploader (feature/s3/manager) takes an io.Reader, buffers PartSize bytes (minimum manager.MinUploadPartSize = 5 MiB, default the same) with Concurrency goroutines (default 5), uses a single PutObject when the body fits in one part, and aborts the upload when the reader fails unless LeavePartsOnError is set. manager is marked deprecated in favour of feature/s3/transfermanager (transfermanager.New(client) then UploadObject, with defaults of an 8 MiB part and a 16 MiB multipart threshold). Both are tested below against the fake endpoint.

Uploader.Upload(reader of unknown length, PartSize 5 MiB, Concurrency 5)
1  read 5 MiB; reader not exhausted -> CreateMultipartUpload -> uploadId
2  UploadPart 1, 2, 3 ... in parallel goroutines (memory = PartSize x Concurrency)
3  reader error ("client went away")
4  AbortMultipartUpload(uploadId)  -> parts deleted, no object created
   ... or on success: CompleteMultipartUpload(parts[(1,etag1),(2,etag2),(3,etag3)]) -> object appears

Real scenario: a video platform streaming a 4 GB upload from the request body into S3 with 25 MB memory; a backup tool resuming a 200 GB file after a laptop sleep by listing the existing parts (ListParts) and uploading only the missing ones; a browser uploader splitting a file with Blob.slice and requesting a presigned URL per part; a bucket whose bill contained terabytes of abandoned parts until a lifecycle rule was added.

Aspectmanager.Uploader (deprecated)transfermanagerRaw multipart calls
Packagefeature/s3/managerfeature/s3/transfermanagerservice/s3
Part size default5 MiB (minimum)8 MiBYou choose, 5 MiB to 5 GiB
Concurrency default55You write it
Inputio.Readerio.ReaderParts you slice
Aborts on errorYes (unless LeavePartsOnError)YesYou must call Abort
Resumable across processesNoNoYes, via ListParts
StatusDeprecatedCurrentStable

Fix / how to use it: use transfermanager in new code and keep manager where you already have it (this chapter's s3store shows it because the brief and a lot of existing code use it). Always add the AbortIncompleteMultipartUpload lifecycle rule. For browser resumable uploads, expose three endpoints (create, sign part, complete) that map one to one onto the protocol, and store the upload id with the user.

go
package s3store

import (
	"bytes"
	"testing"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/s3/transfermanager"
)

// feature/s3/manager is marked Deprecated in favour of feature/s3/transfermanager
// (GA announced in aws-sdk-go-v2 discussion #3306). Same idea, new API.
func TestTransferManagerMultipart(t *testing.T) {
	f := newFakeS3()
	defer f.srv.Close()
	c := NewClient(Config{Endpoint: f.srv.URL, Region: "us-east-1", AccessKey: "AKID", SecretKey: "s", PathStyle: true})
	tm := transfermanager.New(c, func(o *transfermanager.Options) {
		o.PartSizeBytes = 5 << 20
		o.MultipartUploadThreshold = 5 << 20
	})
	data := bytes.Repeat([]byte("t"), 11<<20)
	_, err := tm.UploadObject(t.Context(), &transfermanager.UploadObjectInput{
		Bucket: aws.String("uploads"), Key: aws.String("tm.bin"), Body: bytes.NewReader(data),
	})
	if err != nil {
		t.Fatal(err)
	}
	if n := f.count("PUT /uploads/tm.bin?partNumber"); n != 3 {
		t.Fatalf("want 3 parts, got %d: %v", n, f.log)
	}
}
Multipart upload: one object, many independent requests1 CreateMultipartUploadreturns UploadId2 UploadPart (parallel, retryable)part 1..10000, 5 MiB..5 GiB each, ETag per part3 CompleteMultipartUploadlist of (number, ETag)part 1 (5 MiB)part 2 (5 MiB)part 3 (last, any)If nobody completes itUploaded parts stay and are billed as storage.Abort on error, and add AbortIncompleteMultipartUpload.In Gomanager.Uploader (deprecated) or transfermanager.Memory = PartSize x Concurrency; bad reader = abort.

Presigned URLs: PresignClient, PutObject and GetObject, expiry Must-know ​

In plain words: A presigned URL is a normal S3 URL with a signature in the query string that says "whoever sends exactly this request before this time may do it". Your server creates it from its own credentials without calling S3; the browser then talks to S3 directly.

Common misunderstanding: "The URL is tied to the user who asked." It is tied to the credentials that signed it and to the signed request (method, bucket, key, signed headers), not to a person. Anyone holding it can use it. The S3 guide: "presigned URLs are bearer tokens that grant access to those who possess them", limited by the permissions of the signer.

Definition: s3.NewPresignClient(client) returns a *s3.PresignClient with PresignPutObject, PresignGetObject, PresignHeadObject, PresignDeleteObject and PresignPostObject. Pass s3.WithPresignExpires(d) for expiry (the default when unset is 900 seconds). The SigV4 query carries X-Amz-Algorithm, X-Amz-Credential, X-Amz-Date, X-Amz-Expires, X-Amz-SignedHeaders and X-Amz-Signature. Expiry rules from the S3 guide: up to 7 days for an IAM user with SigV4; with temporary credentials (an IAM role session, EC2 role credentials) the URL dies when the credentials do, whatever you asked; expiry is checked when the request starts, so a download begun before expiry may finish, but a resume after expiry fails. R2 documents the same range: "from 1 second to 7 days".

server                                     browser                          S3
1  PresignPutObject(bucket,key,type,size)
   signs offline, no network
2  { url, headers } ------------------->
3                                          PUT url
4                                          Content-Type: image/png
5                                          Content-Length: 1234  ----------> verify signature + expiry
6                                          <------------------------------- 200 ETag
7  <-- client posts {key} --- confirm; server HeadObject + validate + mark committed

Real scenario: a mobile app uploading 200 MB videos; a "download invoice" link valid for 60 seconds; an upload URL with Content-Type signed so a browser cannot switch an image slot to HTML; a log line that accidentally recorded a presigned URL (treat it as a leaked secret until it expires).

PropertyPresigned PUTPresigned GETPresigned POST (policy)
What is signedMethod, URL, signed headers (content-type, content-length, host in the test)Same, plus overrides like response-content-dispositionA policy document with conditions
Enforces max sizeOnly if Content-Length is signed (exact value)n/aYes, content-length-range
Enforces typeIf Content-Type is signedn/aYes, condition on Content-Type
Typical expiry5 to 15 minutesSeconds to hours5 to 15 minutes
Works on R2YesYesNo (documented as not supported)

Fix / how to use it: validate the intent first (extension, type, size, quota), generate the key yourself, sign Content-Type and Content-Length, give a short expiry, and never sign a key the client chose. The presign snippet does this and its test asserts the shape of the URL (expiry 300, credential scope, signed headers content-length;content-type;host) without hitting a network.

go
// Package presign issues presigned URLs and POST policies so browsers can
// talk to the bucket directly. Signing is an offline HMAC computation: no
// request is sent to S3 when a URL is created.
package presign

import (
	"context"
	"encoding/json"
	"net/http"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/s3"

	"academy/file-uploads-s3-cdn/keys"
	"academy/file-uploads-s3-cdn/validate"
)

// Signer wraps the SDK's PresignClient.
type Signer struct {
	PC     *s3.PresignClient
	Bucket string
	TTL    time.Duration // URL lifetime; keep it to minutes for uploads
}

// Put presigns a PutObject. ContentType and ContentLength are signed, so the
// browser must send exactly those values or S3 answers 403 SignatureDoesNotMatch.
func (s Signer) Put(ctx context.Context, key, contentType string, size int64) (string, http.Header, error) {
	req, err := s.PC.PresignPutObject(ctx, &s3.PutObjectInput{
		Bucket:        aws.String(s.Bucket),
		Key:           aws.String(key),
		ContentType:   aws.String(contentType),
		ContentLength: aws.Int64(size),
	}, s3.WithPresignExpires(s.TTL))
	if err != nil {
		return "", nil, err
	}
	return req.URL, req.SignedHeader, nil
}

// Get presigns a GetObject. downloadName, when set, becomes the
// response-content-disposition override that is part of the signature.
func (s Signer) Get(ctx context.Context, key, downloadName string, ttl time.Duration) (string, error) {
	in := &s3.GetObjectInput{Bucket: aws.String(s.Bucket), Key: aws.String(key)}
	if downloadName != "" {
		in.ResponseContentDisposition = aws.String(contentDisposition(downloadName))
	}
	req, err := s.PC.PresignGetObject(ctx, in, s3.WithPresignExpires(ttl))
	if err != nil {
		return "", err
	}
	return req.URL, nil
}

// Post builds a browser form POST with a policy that pins the key, the
// content type and a byte range. Unlike a presigned PUT URL, a POST policy can
// enforce a maximum size (content-length-range).
func (s Signer) Post(ctx context.Context, key, contentType string, maxSize int64) (*s3.PresignedPostRequest, error) {
	return s.PC.PresignPostObject(ctx, &s3.PutObjectInput{
		Bucket: aws.String(s.Bucket),
		Key:    aws.String(key),
	}, func(o *s3.PresignPostOptions) {
		o.Expires = s.TTL
		o.Conditions = []any{
			[]any{"content-length-range", 1, maxSize},
			map[string]string{"Content-Type": contentType},
		}
	})
}

func contentDisposition(name string) string { return keys.Disposition("attachment", name) }

// Request is what the browser sends to ask for permission to upload.
type Request struct {
	Filename    string `json:"filename"`
	ContentType string `json:"content_type"`
	Size        int64  `json:"size"`
}

// Response tells the browser exactly what to send.
type Response struct {
	Method    string            `json:"method"`
	URL       string            `json:"url"`
	Headers   map[string]string `json:"headers"`
	Key       string            `json:"key"`
	ExpiresAt time.Time         `json:"expires_at"`
}

// Handler validates the intent (extension, type, size) BEFORE signing; after
// signing, S3 enforces the signed values. The server never sees the bytes.
func Handler(s Signer, allowed validate.Allowlist, maxSize int64, now func() time.Time) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		r.Body = http.MaxBytesReader(w, r.Body, 4<<10)
		var in Request
		if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
			http.Error(w, "bad json", http.StatusBadRequest)
			return
		}
		name := validate.SanitizeFilename(in.Filename)
		ext := validate.Extension(name)
		want, ok := allowed[ext]
		switch {
		case !ok || want != in.ContentType:
			http.Error(w, "type not allowed", http.StatusUnsupportedMediaType)
			return
		case in.Size <= 0 || in.Size > maxSize:
			http.Error(w, "bad size", http.StatusRequestEntityTooLarge)
			return
		}
		key, err := keys.Random("incoming", ext, now())
		if err != nil {
			http.Error(w, "server error", http.StatusInternalServerError)
			return
		}
		u, _, err := s.Put(r.Context(), key, in.ContentType, in.Size)
		if err != nil {
			http.Error(w, "server error", http.StatusInternalServerError)
			return
		}
		// Host and Content-Length are set by the browser itself.
		h := map[string]string{"Content-Type": in.ContentType}
		w.Header().Set("Content-Type", "application/json")
		_ = json.NewEncoder(w).Encode(Response{Method: "PUT", URL: u, Headers: h, Key: key, ExpiresAt: now().Add(s.TTL)})
	})
}
go
package presign

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"
	"testing"
	"time"

	"github.com/aws/aws-sdk-go-v2/service/s3"

	"academy/file-uploads-s3-cdn/s3store"
	"academy/file-uploads-s3-cdn/validate"
)

func signer() Signer {
	c := s3store.NewClient(s3store.Config{Endpoint: "https://s3.example.test", Region: "eu-central-1", AccessKey: "AKIDEXAMPLE", SecretKey: "secret", PathStyle: true})
	return Signer{PC: s3.NewPresignClient(c), Bucket: "uploads", TTL: 5 * time.Minute}
}

func TestPresignedPutIsOffline(t *testing.T) {
	u, hdr, err := signer().Put(t.Context(), "incoming/a.png", "image/png", 1234)
	if err != nil {
		t.Fatal(err)
	}
	pu, _ := url.Parse(u)
	q := pu.Query()
	if pu.Host != "s3.example.test" || !strings.HasPrefix(pu.Path, "/uploads/incoming/a.png") {
		t.Fatalf("path-style URL expected: %s", u)
	}
	if q.Get("X-Amz-Expires") != "300" || q.Get("X-Amz-Algorithm") != "AWS4-HMAC-SHA256" || q.Get("X-Amz-Signature") == "" {
		t.Fatalf("query: %v", q)
	}
	if !strings.Contains(q.Get("X-Amz-Credential"), "AKIDEXAMPLE/") || !strings.Contains(q.Get("X-Amz-Credential"), "/eu-central-1/s3/aws4_request") {
		t.Fatalf("credential scope: %s", q.Get("X-Amz-Credential"))
	}
	signed := q.Get("X-Amz-SignedHeaders")
	if !strings.Contains(signed, "content-type") || !strings.Contains(signed, "host") {
		t.Fatalf("signed headers: %s", signed)
	}
	if !strings.Contains(signed, "content-length") || hdr.Get("Content-Length") != "1234" {
		t.Fatalf("the size must be signed: SignedHeaders=%s header=%v", signed, hdr)
	}
	if hdr.Get("Content-Type") != "image/png" {
		t.Fatalf("the browser must send Content-Type image/png, got %v", hdr)
	}
}

func TestPresignedGetCarriesDownloadName(t *testing.T) {
	u, err := signer().Get(t.Context(), "a/b.pdf", "Q4 report.pdf", time.Minute)
	if err != nil {
		t.Fatal(err)
	}
	q, _ := url.Parse(u)
	rcd := q.Query().Get("response-content-disposition")
	if !strings.HasPrefix(rcd, "attachment;") || !strings.Contains(rcd, "Q4 report.pdf") {
		t.Fatalf("rcd = %q", rcd)
	}
	if q.Query().Get("X-Amz-Expires") != "60" {
		t.Fatalf("expires: %v", q.Query())
	}
}

func TestPostPolicyEnforcesSizeRange(t *testing.T) {
	p, err := signer().Post(t.Context(), "incoming/b.png", "image/png", 5<<20)
	if err != nil {
		t.Fatal(err)
	}
	raw, err := base64.StdEncoding.DecodeString(p.Values["policy"])
	if err != nil {
		t.Fatal(err)
	}
	var pol struct {
		Expiration string
		Conditions []any
	}
	if err := json.Unmarshal(raw, &pol); err != nil {
		t.Fatal(err)
	}
	s := string(raw)
	for _, want := range []string{`"content-length-range",1,5242880`, `"bucket":"uploads"`, `"key":"incoming/b.png"`, `"Content-Type":"image/png"`} {
		if !strings.Contains(s, want) {
			t.Errorf("policy lacks %s: %s", want, s)
		}
	}
	if p.Values["X-Amz-Signature"] == "" || p.Values["key"] != "incoming/b.png" {
		t.Fatalf("form fields: %v", p.Values)
	}
	if _, err := time.Parse(time.RFC3339, pol.Expiration); err != nil {
		t.Fatalf("expiration: %v", err)
	}
}

func TestHandler(t *testing.T) {
	now := func() time.Time { return time.Date(2026, 11, 28, 12, 0, 0, 0, time.UTC) }
	h := Handler(signer(), validate.Allowlist{".png": "image/png"}, 1<<20, now)
	do := func(body string) *httptest.ResponseRecorder {
		rec := httptest.NewRecorder()
		h.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/sign", bytes.NewBufferString(body)))
		return rec
	}
	rec := do(`{"filename":"../x/me.png","content_type":"image/png","size":2048}`)
	if rec.Code != 200 {
		t.Fatalf("%d %s", rec.Code, rec.Body)
	}
	var out Response
	_ = json.Unmarshal(rec.Body.Bytes(), &out)
	if out.Method != "PUT" || !strings.HasPrefix(out.Key, "incoming/2026/11/") || strings.Contains(out.Key, "me") || out.Headers["Content-Type"] != "image/png" {
		t.Fatalf("%+v", out)
	}
	if !out.ExpiresAt.Equal(now().Add(5 * time.Minute)) {
		t.Fatalf("expires %v", out.ExpiresAt)
	}
	for body, want := range map[string]int{
		`{"filename":"a.php","content_type":"image/png","size":10}`:      415,
		`{"filename":"a.png","content_type":"text/html","size":10}`:      415,
		`{"filename":"a.png","content_type":"image/png","size":0}`:       413,
		`{"filename":"a.png","content_type":"image/png","size":9999999}`: 413,
		`nope`: 400,
	} {
		if got := do(body).Code; got != want {
			t.Errorf("%s -> %d, want %d", body, got, want)
		}
	}
}

// TestPresignedPutLogsAnatomy prints the URL pieces; run it with -v for the lab.
func TestPresignedPutLogsAnatomy(t *testing.T) {
	u, hdr, err := signer().Put(t.Context(), "incoming/2026/11/a.png", "image/png", 1234)
	if err != nil {
		t.Fatal(err)
	}
	pu, _ := url.Parse(u)
	t.Logf("host=%s path=%s", pu.Host, pu.Path)
	for _, k := range []string{"X-Amz-Algorithm", "X-Amz-Credential", "X-Amz-Expires", "X-Amz-SignedHeaders"} {
		t.Logf("%s=%s", k, pu.Query().Get(k))
	}
	t.Logf("X-Amz-Signature length=%d", len(pu.Query().Get("X-Amz-Signature")))
	t.Logf("headers the browser must send: %v", hdr)
}

POST policy and conditions Important ​

In plain words: A POST policy is a signed rulebook for an HTML form upload: "this bucket, this key, this content type, between 1 byte and 5 MiB, until 12:36". S3 checks the uploaded form against the rules.

Common misunderstanding: "Presigned PUT can limit the size to a range." It can only fix an exact Content-Length if you sign it. A range (content-length-range) is a feature of the POST policy.

Definition: PresignClient.PresignPostObject(ctx, *PutObjectInput, optFns...) returns *PresignedPostRequest with URL and Values (the form fields: X-Amz-Algorithm, X-Amz-Credential, X-Amz-Date, X-Amz-Signature, key, policy). Extra Conditions []any are added to the policy, which the SDK source builds as base64 JSON with expiration and conditions. If you give no condition on key (an exact match or ["starts-with", "$key", prefix]), the SDK adds {"key": <key>} itself. The browser sends all Values as form fields followed by the file field last, as a multipart/form-data POST to the URL.

policy (decoded from the test run)
{"conditions":[{"X-Amz-Algorithm":"AWS4-HMAC-SHA256"},{"bucket":"uploads"},
  {"X-Amz-Credential":"AKIDEXAMPLE/20261128/eu-central-1/s3/aws4_request"},{"X-Amz-Date":"20261128T203154Z"},
  ["content-length-range",1,5242880],{"Content-Type":"image/png"},{"key":"incoming/b.png"}],
 "expiration":"2026-11-28T20:36:54Z"}

Real scenario: a classic HTML form on a static site posting to the bucket; a policy with ["starts-with", "$key", "incoming/tenant-42/"] letting a client choose the file name under its own prefix; a rule that forces success_action_status. Details of every condition are in the S3 API reference for browser-based POST, whose pages are served as a JavaScript shell and could not be saved here, so this chapter relies on the SDK source and the decoded test output, not on quoted reference text.

ConditionMatchesExample
Exact matchField equals value{"bucket": "uploads"}
starts-withPrefix of the field["starts-with", "$key", "incoming/"]
content-length-rangeMin and max file bytes["content-length-range", 1, 5242880]
Presence in the formField must be sentFields you did not list must be absent or the upload is refused

Fix / how to use it: use POST policy when you need a hard size cap without proxying bytes; use presigned PUT when your client is not a browser form (mobile SDKs) or the provider lacks POST (R2). In both cases still verify with HeadObject after the upload.

Direct-to-S3 browser uploads with presigned URL and CORS on the bucket Must-know ​

In plain words: The browser sends the file straight to the bucket. Because the page is on app.example.test and the bucket is on another origin, the browser first asks the bucket "may this origin send PUT with this header?" That answer is the bucket's CORS configuration.

Common misunderstanding: "CORS is a server-side security feature that protects the bucket." CORS only tells browsers whether JavaScript from another origin may read or send; curl ignores it. Signed URLs and policies protect the bucket; CORS merely stops browsers from blocking your own page.

Definition: S3 evaluates a preflight against the bucket's CORS configuration and "uses the first CORSRule rule that matches": the Origin must match AllowedOrigins, the Access-Control-Request-Method must match AllowedMethods, and every Access-Control-Request-Headers entry must match AllowedHeaders. Policies and ACLs still apply. A response header the page needs to read (the ETag of a part in a multipart upload) must be listed in ExposeHeaders.

browser (https://app.example.test)                         bucket
1  OPTIONS /key  Origin: app...  Access-Control-Request-Method: PUT
2               Access-Control-Request-Headers: content-type
3  <---- 200  Access-Control-Allow-Origin: https://app.example.test  (rule matched)
4  PUT /key?X-Amz-...  Content-Type: image/png  + body ----------->
5  <---- 200  ETag (readable only if ExposeHeaders lists ETag)
json
[
  {
    "AllowedOrigins": ["https://app.example.test"],
    "AllowedMethods": ["PUT", "POST"],
    "AllowedHeaders": ["content-type"],
    "ExposeHeaders": ["ETag"],
    "MaxAgeSeconds": 3000
  }
]

Real scenario: an upload widget that works in curl and fails in the browser with "blocked by CORS policy" because AllowedHeaders lacks content-type; a staging site whose origin was missing; a rule with AllowedOrigins: ["*"] on a bucket that serves signed uploads (it works and is rarely what you want); R2 and Spaces, which have their own CORS settings with the same field names.

SymptomLikely causeFix
Preflight 403Origin or method not in any ruleAdd them to the bucket CORS rule
PUT works, ETag unreadable in JSExposeHeaders missingAdd ETag
403 SignatureDoesNotMatch after preflight passesHeader sent differs from signed headerSend exactly the signed Content-Type
Works locally onlyDifferent origin in productionList both origins explicitly

Fix / how to use it: follow the diagram: ask your server for a URL (it validates intent), fetch(url, {method: "PUT", headers, body: file}), then tell your server the key so it can HeadObject and commit the row. Treat the object as unverified until that step.

A. Proxy upload: bytes pass through your serverBrowsermultipart/form-dataGo app serverMaxBytesReader + sniff + streamObject storePutObject / multipartfile bytesfile bytes+ you can inspect every byte - your bandwidth, CPU and connections carry the loadB. Direct upload: bytes go browser to storageBrowserfetch / XHR PUTGo app servervalidates intent, signs, recordsObject storeCORS on the bucket1 name, type, size2 presigned URL3 PUT file bytes straight to the signed URL4 client confirms; app HEADs the object,checks size/type, marks the row committed+ no upload traffic on your servers - you see the bytes only after they landed: scan or re-validate asynchronously

S3-compatible stores: MinIO, Cloudflare R2, DigitalOcean Spaces Must-know ​

In plain words: Many services copy the S3 API. The same Go client works if you change the endpoint, the region string, the credentials and sometimes the addressing style.

Common misunderstanding: "S3-compatible means identical." Each service implements a subset. Spaces says it "provides an S3-compatible API with partial support" and lists unsupported calls that return NotImplemented; R2 documents that POST form uploads are not supported for presigned URLs; behaviour of checksums, lifecycle, encryption settings and tags differs.

Definition: S3-compatible means speaking the S3 REST API with SigV4. Addressing is virtual-hosted style (https://bucket.host/key) or path style (https://host/bucket/key); AWS says it supports both and has delayed the deprecation of path-style, but a self-hosted MinIO without wildcard DNS needs UsePathStyle. In the SDK: Options.BaseEndpoint (or o.BaseEndpoint in LoadDefaultConfig clients), Region, UsePathStyle.

ProviderEndpointRegion stringAddressingNotes from the docs
Amazon S3none (SDK resolves)real region, for example eu-central-1Virtual-hosted (path-style still accepted)Presigned URLs up to 7 days with an IAM user
MinIOhttp://127.0.0.1:9000 or your hosta region string the server accepts (the MinIO README examples use us-east-1; check your server)Path style on self-hostedminio-go is MinIO's own Go client for any S3-compatible store
Cloudflare R2https://ACCOUNT_ID.r2.cloudflarestorage.comauto ("required by SDK but not used by R2")S3 API domainPresigned GET, HEAD, PUT, DELETE; POST not supported; presigned URLs work only on the S3 API domain, not custom domains
DigitalOcean Spaces: endpointhttps://REGION.digitaloceanspaces.com, bucket as subdomainSpaces region such as nyc3Virtual-hosted shown in its examplesPresigned URLs with SigV2 and V4; lifecycle limited to time-based and incomplete multipart; CDN at SPACE.REGION.cdn.digitaloceanspaces.com
config                         AWS               MinIO (dev)                R2                              Spaces
1  Endpoint                    (empty)           http://127.0.0.1:9000      https://<account>.r2...com      https://nyc3.digitaloceanspaces.com
2  Region                      eu-central-1      us-east-1                  auto                            nyc3
3  PathStyle                   false             true                       false                           false
4  Credentials                 IAM role/keys     root or service account    R2 API token (access key pair)  Spaces key pair

Real scenario: local development against MinIO in a container while production uses S3 or R2 (same code, different Config); moving 40 TB from S3 to R2 to cut egress cost; a vendor that offers "S3 API" but returns 501 for lifecycle; a test suite that runs against the in-memory Store and a small conformance test against whichever endpoint the CI provides.

Fix / how to use it: keep provider differences in one Config struct (the snippet's s3store.Config), never hard-code AWS URLs, and write a small contract test that exercises Put, Head, Get, Delete, a multipart upload and a presigned GET against any endpoint you depend on. MinIO's own Go client (minio-go) is an alternative to the AWS SDK; its README describes it as a client "to access any Amazon S3 compatible object storage".

Access control: bucket policies and IAM least privilege Must-know ​

In plain words: The credentials your Go service holds can do only what its policy allows. Give the upload service permission to put objects under one prefix and nothing else; give the CDN permission to read; keep the bucket private.

Common misunderstanding: "Making the bucket public is the easy way to serve files." A public bucket serves everything to everyone, including files uploaded by mistake, and leaks are a recurring breach cause. S3 Block Public Access exists to prevent it; AWS recommends turning all four settings on.

Definition: An IAM policy attached to the principal says what it may do; a bucket policy attached to the bucket says who may do what to it (including other accounts and services such as CloudFront). Least privilege means the narrowest action list and resource ARNs that work. Deny statements and conditions (for example s3:signatureAge, shown in the AWS guide to reject presigned requests older than 10 minutes) can restrict how a presigned URL is used. Presigned URLs inherit the signer's permissions, so a signer with broad rights makes broad URLs.

json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "UploadServiceWritesIncomingOnly",
      "Effect": "Allow",
      "Action": ["s3:PutObject", "s3:AbortMultipartUpload", "s3:GetObject", "s3:DeleteObject"],
      "Resource": "arn:aws:s3:::example-uploads/incoming/*"
    },
    {
      "Sid": "ListIncomingForSweeper",
      "Effect": "Allow",
      "Action": "s3:ListBucket",
      "Resource": "arn:aws:s3:::example-uploads",
      "Condition": { "StringLike": { "s3:prefix": ["incoming/*"] } }
    }
  ]
}

Real scenario: an upload service with s3:* on * whose credential leaked from a log; a thumbnail worker that can read incoming/ and write thumb/ only; a bucket policy that denies any request not over TLS; a presigned-URL signer running as a role with a 1-hour session (so URLs die in an hour at most).

PrincipalNeedsDoes not need
Upload API (signer)PutObject on the incoming prefix (to sign), HeadObject/GetObject to verifyDeleteBucket, policy edits, other prefixes
Thumbnail workerGetObject on incoming/*, PutObject on thumb/*Delete
SweeperListBucket, DeleteObject on incoming/*Read of private data
CDNGetObject on public/* via bucket policy (origin access control)Anything else
BrowserNothing: a presigned URLCredentials, ever

Fix / how to use it: one IAM role per service, prefix-scoped, short-lived credentials from the platform (not keys in environment files), Block Public Access on, bucket policy only for the CDN principal. Test the policy by trying what should fail.

Server-side encryption: SSE-S3 and SSE-KMS Important ​

In plain words: The provider encrypts the object on its disks and decrypts it for authorised requests. You are protected against someone walking out with a disk, not against a leaked credential.

Common misunderstanding: "Encryption at rest means the files are private." Server-side encryption is transparent to any caller with permission; it does not replace access control, and a public object is served in clear.

Definition: Per the S3 guide, "Starting January 5, 2023, all new object uploads to Amazon S3 are automatically encrypted at no additional cost": SSE-S3 (S3-managed keys, each object with its own key) is the base level. SSE-KMS uses AWS KMS keys, with key policy control and audit trails, and can be set as a bucket default; changing the default does not re-encrypt existing objects (use S3 Batch Operations copy). Set per object with ServerSideEncryption and SSEKMSKeyId on PutObjectInput. With CloudFront, OAC supports SSE-KMS origins (the older OAI does not).

ModeKeysAuditExtra costUse when
SSE-S3S3 managedS3 levelNoneDefault for most uploads
SSE-KMSKMS key you controlKMS logs per useKMS request chargesCompliance, per-tenant keys, revocation
DSSE-KMSTwo layers with KMSKMS logsHigherSpecific compliance needs
SSE-CYou supply the key per requestYoursNoneDisabled by default on new buckets since April 2026

Fix / how to use it: rely on the default SSE-S3 unless you have a requirement; if you pick SSE-KMS, grant kms:GenerateDataKey and kms:Decrypt to the writers and readers and remember that presigned GETs need decrypt permission too. Pre-encrypting before upload (client-side) is a separate design; see Hashing & Crypto for the primitives.

Content-Disposition and download names Important ​

In plain words: Content-Disposition tells the browser "show this inline" or "save it as a file called X". Use it to give downloads a friendly name even though the object key is random.

Common misunderstanding: "Put the user's file name in filename="..." and you are done." Quotes and semicolons in the name inject parameters, and non-ASCII names need the RFC 5987/6266 extended form. Let a library encode it.

Definition: RFC 6266 defines the header: first parameter inline (default) or attachment, then filename and filename* (extended, percent-encoded, with a charset label). MDN shows Content-Disposition: attachment; filename*=UTF-8''file%20name.jpg. In Go mime.FormatMediaType("attachment", map[string]string{"filename": name}) quotes and escapes, and for non-ASCII names emits the filename*=utf-8''... form (its doc comment says it returns the empty string when an argument violates the standard; the snippet test parses the result back with mime.ParseMediaType and requires exactly one parameter). On S3, set it on the object (PutObjectInput.ContentDisposition) or per response with ResponseContentDisposition on a presigned GET.

1  object key:  uploads/2026/11/9f2c...e1.pdf       (random, no name)
2  DB row:      original_name = 'Q4 "final"; report.pdf'
3  download:    GET /files/42/download -> 302 presigned GET with
               response-content-disposition=attachment; filename="Q4 \"final\"; report.pdf"
4  browser saves: Q4 "final"; report.pdf   (and no extra parameter was injected)

Real scenario: invoices downloaded as invoice-2026-11.pdf while stored under random keys; user content that must never render in your origin (attachment plus nosniff); a Persian file name that shows as garbage because only filename= was sent.

ChoiceEffectRisk
inlineBrowser renders (images, PDF)Active content (HTML, SVG) runs on your origin
attachmentDownload dialogNone for rendering; user can still open it
filename= onlyASCII worksNon-ASCII mangled
filename*=UTF-8 namesVery old clients ignore it
Both (what browsers expect)Widest supportSlightly longer header

Fix / how to use it: keys.Disposition(kind, name) in the snippet; apply attachment to everything that is not an image you resized yourself.

CDN: serving what you stored ​

Serving through a CDN: cache keys, Cache-Control, immutable, versioned keys Must-know ​

In plain words: A CDN keeps copies of your files in many cities. The first request in a city goes to your bucket (a miss); the next thousand are answered locally (hits). You control how long copies live with Cache-Control and what counts as "the same file" with the cache key.

Common misunderstanding: "I can overwrite logo.png and the new one appears." Edge caches and browsers keep the old copy until it expires; invalidation is slow, costs money at volume and does not reach browser caches. AWS recommends versioned file names for files you update often because invalidating may leave users on the old version.

Definition: CloudFront/Cloudflare: cache keys decide whether two requests are the same entry. CloudFront's default cache key is the URL path and host; you can add query strings, headers and cookies, and the guide advises including only the minimum, because every extra value splits the cache. TTL comes from your Cache-Control (max-age, s-maxage) or the distribution's TTL settings; CloudFront's default TTL without a cache policy is 24 hours. Cache-Control: public, max-age=31536000, immutable says the response will not change while fresh; MDN: immutable "avoids those kinds of unnecessary conditional requests". Cloudflare, with Origin Cache Control, follows the origin's directives as specified (enabled by default for Free, Pro and Business plans). Versioned keys put a content hash in the name so that new bytes mean a new URL.

request                             cache key                  result
1  GET /assets/ab/9f2c.png          host + path                MISS -> origin -> store 1 year
2  GET /assets/ab/9f2c.png          same                       HIT  (no origin request)
3  GET /assets/ab/9f2c.png?utm=1    host + path (+ query if the policy includes it)  HIT or MISS depending on policy
4  upload changed bytes             new key /assets/ab/aa31.png  MISS, old key untouched

Real scenario: user avatars under random keys cached for a year with immutable (a changed avatar gets a new key, the database stores the new one); app.3f2a9c1d.css versioned assets; a product feed that must refresh in 60 seconds (max-age=60); a marketing query string (?utm_source=) that fragmented the cache until it was removed from the cache key.

ContentKey styleCache-ControlWhy
Uploaded image, resized variantRandom or content hashpublic, max-age=31536000, immutableNever changes under that key
Fingerprinted CSS/JSapp.3f2a9c1d.cssSameDeploy changes the name
Mutable file under a stable nameStablepublic, max-age=0, must-revalidate + ETagAlways revalidate cheaply
Private documentRandomprivate, no-store or signed URL with short TTLNever in shared caches
Index/listing pageStablemax-age=60Freshness tolerance

Fix / how to use it: cdn.Handler in the snippet sets Immutable for keys under assets/, Revalidate otherwise, plus ETag, nosniff and an optional download name. On S3 you set CacheControl at upload (the snippet's Meta.CacheControl) so the origin response already carries it.

go
// Package cdn is the origin side of "serve through a CDN": correct cache
// headers, validators (ETag), range support and a signed-URL scheme.
package cdn

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"io"
	"net/http"
	"strconv"
	"strings"
	"time"

	"academy/file-uploads-s3-cdn/keys"
	"academy/file-uploads-s3-cdn/objstore"
)

// Opener gives the handler a seekable view of an object. http.ServeContent
// needs io.ReadSeeker to answer Range requests; for S3 you would implement it
// with GetObject and the Range parameter.
type Opener interface {
	Open(key string) (io.ReadSeeker, objstore.Meta, error)
}

// Immutable is the Cache-Control for content-addressed or versioned keys.
const Immutable = "public, max-age=31536000, immutable"

// Revalidate is for keys whose bytes may change: caches must ask each time,
// and the ETag makes that ask cheap (304 Not Modified).
const Revalidate = "public, max-age=0, must-revalidate"

// Handler serves GET/HEAD /<key>. ?download=<name> forces a download name.
func Handler(o Opener) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		key := strings.TrimPrefix(r.URL.Path, "/")
		rs, meta, err := o.Open(key)
		if err != nil {
			http.NotFound(w, r)
			return
		}
		h := w.Header()
		h.Set("Content-Type", meta.ContentType)
		h.Set("ETag", meta.ETag)
		// Without nosniff a browser may "upgrade" a mislabelled file to HTML.
		h.Set("X-Content-Type-Options", "nosniff")
		if meta.CacheControl != "" {
			h.Set("Cache-Control", meta.CacheControl)
		} else if strings.HasPrefix(key, "assets/") {
			h.Set("Cache-Control", Immutable)
		} else {
			h.Set("Cache-Control", Revalidate)
		}
		if name := r.URL.Query().Get("download"); name != "" {
			h.Set("Content-Disposition", keys.Disposition("attachment", name))
		}
		// ServeContent adds Accept-Ranges, answers Range with 206 and
		// Content-Range, and answers If-None-Match / If-Modified-Since with 304.
		http.ServeContent(w, r, "", meta.LastModified, rs)
	})
}

// Sign returns path?exp=<unix>&sig=<hex>, an HMAC-SHA256 over path and
// expiry. This is the idea behind CloudFront, Cloudflare and nginx
// secure_link tokens, but NOT their wire formats: CloudFront signs a policy
// with an RSA key pair and Cloudflare/nginx have their own layouts.
func Sign(secret []byte, path string, exp time.Time) string {
	e := strconv.FormatInt(exp.Unix(), 10)
	return path + "?exp=" + e + "&sig=" + mac(secret, path, e)
}

func mac(secret []byte, path, exp string) string {
	m := hmac.New(sha256.New, secret)
	m.Write([]byte(path + "\n" + exp))
	return hex.EncodeToString(m.Sum(nil))
}

// Verify checks signature and expiry, in constant time for the signature.
func Verify(secret []byte, r *http.Request, now time.Time) bool {
	q := r.URL.Query()
	exp, sig := q.Get("exp"), q.Get("sig")
	sec, err := strconv.ParseInt(exp, 10, 64)
	if err != nil || now.Unix() > sec {
		return false
	}
	want := mac(secret, r.URL.Path, exp)
	return hmac.Equal([]byte(want), []byte(sig))
}

// RequireSignature rejects unsigned or expired requests with 403.
func RequireSignature(secret []byte, now func() time.Time, next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if !Verify(secret, r, now()) {
			http.Error(w, "forbidden", http.StatusForbidden)
			return
		}
		next.ServeHTTP(w, r)
	})
}
Browser, edge cache, private bucketBrowserGET /assets/ab/f.pngRange, If-None-MatchCDN edgecache key = host + path(+ chosen query / headers)TTL from Cache-ControlPrivate bucketno public accesspolicy: only the CDNrequest200 / 206 / 304only on MISSobject + ETagImmutable keys (content hash in the name)Cache-Control: public, max-age=31536000, immutableNew bytes = new key = new URL. Nothing to purge.Old keys expire by lifecycle rule, not by invalidation.Hit ratio near 100 %, origin requests near zero.Use for uploads, thumbnails, fingerprinted assets.Mutable keys (same name, new bytes)Cache-Control: public, max-age=0, must-revalidateEdge asks origin: If-None-Match: "etag"Origin: 304 Not Modified (no body) or 200 + new body.Or a short max-age plus an explicit invalidation.Private files: signed URL or signed cookie.

Private files: origin access control, signed URLs and cookies Must-know ​

In plain words: Keep the bucket closed to the world, let only the CDN read it, and let the CDN hand a file to someone only if the URL (or a cookie) carries a valid signature that has not expired.

Common misunderstanding: "A presigned S3 URL is the same as a CDN signed URL." A presigned S3 URL is checked by S3 (and bypasses the CDN cache unless you sign for the CDN hostname). A CloudFront signed URL or cookie is checked at the edge using a key pair and is cacheable according to the policy. Different signers, different formats.

Definition: Origin access control (OAC) is CloudFront's way of sending authenticated (SigV4) requests to a private S3 bucket; the bucket policy then allows only that distribution. AWS recommends OAC over the legacy OAI (OAC supports all regions, SSE-KMS and PUT/DELETE) and requires S3 Object Ownership "Bucket owner enforced" or "Bucket owner preferred". Signed URLs/cookies: a CloudFront signed URL uses either a canned policy (one resource, expiry) or a custom policy (wildcards, start time, IP range, longer URL); signed cookies sign many files at once, useful for video segments. The snippet's Sign/Verify is a generic HMAC scheme (path plus expiry) for an origin or edge function you control; it is not CloudFront's RSA wire format and is not a drop-in for it.

1  user logs in; app decides: may read file 42
2  app signs CDN URL: /files/9f2c.pdf?exp=1700000300&sig=hmac(secret, path\nexp)
3  browser GET -> CDN edge validates sig+exp (edge function or built-in signed URL check)
4  valid: serve from cache or fetch from bucket via OAC; invalid or expired: 403

Real scenario: paid course videos where signed cookies authorise every HLS segment; invoices with 60-second links; a share link that expires in 7 days; an S3 bucket that denies everything except the CloudFront service principal for one distribution.

MechanismChecked byCacheable at edgePer-user controlSetup cost
Public CDN URLNobodyYesNoneLow
S3 presigned GETS3 (origin)Poor (query string varies)Per URLLow
CloudFront signed URL, canned policyEdgeYes, if key excludes the signatureOne file, expiryKey group, RSA key
CloudFront signed URL, custom policyEdgeYesWildcards, IP, start timeSame, longer URLs
CloudFront signed cookiesEdgeYesMany files, one authSame, cookie domain
Cloudflare signed/tokenised URLEdge rule or WorkerYesPer ruleRule or code (not covered here)

Fix / how to use it: public things get public immutable URLs; private things get a signed URL or cookie with the shortest practical TTL; and the bucket stays private either way. Check the policy by requesting the bucket's own URL directly: it must return 403.

go
package cdn

import (
	"bytes"
	"io"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"time"

	"academy/file-uploads-s3-cdn/objstore"
)

type memOpener map[string]struct {
	data []byte
	meta objstore.Meta
}

func (m memOpener) Open(key string) (io.ReadSeeker, objstore.Meta, error) {
	o, ok := m[key]
	if !ok {
		return nil, objstore.Meta{}, objstore.ErrNotFound
	}
	return bytes.NewReader(o.data), o.meta, nil
}

func fixture() memOpener {
	mod := time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC)
	return memOpener{
		"assets/ab/app.css": {[]byte("0123456789abcdefghij"), objstore.Meta{ContentType: "text/css", ETag: `"v1"`, LastModified: mod}},
		"uploads/x.pdf":     {[]byte("%PDF-1.7 body"), objstore.Meta{ContentType: "application/pdf", ETag: `"p1"`, LastModified: mod}},
	}
}

func get(h http.Handler, path string, hdr ...string) *httptest.ResponseRecorder {
	req := httptest.NewRequest(http.MethodGet, path, nil)
	for i := 0; i+1 < len(hdr); i += 2 {
		req.Header.Set(hdr[i], hdr[i+1])
	}
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, req)
	return rec
}

func TestHeadersAndConditionalGET(t *testing.T) {
	h := Handler(fixture())
	r := get(h, "/assets/ab/app.css")
	if r.Code != 200 || r.Header().Get("Cache-Control") != Immutable || r.Header().Get("ETag") != `"v1"` ||
		r.Header().Get("X-Content-Type-Options") != "nosniff" || r.Header().Get("Accept-Ranges") != "bytes" {
		t.Fatalf("%d %v", r.Code, r.Header())
	}
	// The validator makes revalidation cheap: no body, same ETag.
	r = get(h, "/assets/ab/app.css", "If-None-Match", `"v1"`)
	if r.Code != http.StatusNotModified || r.Body.Len() != 0 {
		t.Fatalf("want 304 without body, got %d (%d bytes)", r.Code, r.Body.Len())
	}
	r = get(h, "/assets/ab/app.css", "If-None-Match", `"stale"`)
	if r.Code != 200 {
		t.Fatalf("stale validator: %d", r.Code)
	}
	if r := get(h, "/uploads/x.pdf"); r.Header().Get("Cache-Control") != Revalidate {
		t.Fatalf("mutable keys must revalidate: %v", r.Header())
	}
	if r := get(h, "/nope"); r.Code != 404 {
		t.Fatalf("404 expected, got %d", r.Code)
	}
}

func TestRangeRequests(t *testing.T) {
	h := Handler(fixture())
	r := get(h, "/assets/ab/app.css", "Range", "bytes=2-5")
	if r.Code != http.StatusPartialContent || r.Body.String() != "2345" || r.Header().Get("Content-Range") != "bytes 2-5/20" {
		t.Fatalf("%d %q %v", r.Code, r.Body, r.Header())
	}
	r = get(h, "/assets/ab/app.css", "Range", "bytes=-4")
	if r.Body.String() != "ghij" {
		t.Fatalf("suffix range: %q", r.Body)
	}
	r = get(h, "/assets/ab/app.css", "Range", "bytes=100-")
	if r.Code != http.StatusRequestedRangeNotSatisfiable {
		t.Fatalf("out of range: %d", r.Code)
	}
	// If-Range with a stale validator falls back to the full 200.
	r = get(h, "/assets/ab/app.css", "Range", "bytes=0-1", "If-Range", `"old"`)
	if r.Code != 200 || r.Body.Len() != 20 {
		t.Fatalf("If-Range mismatch must return the whole object: %d", r.Code)
	}
}

func TestDownloadName(t *testing.T) {
	r := get(Handler(fixture()), "/uploads/x.pdf?download=Q4%20%22final%22.pdf")
	cd := r.Header().Get("Content-Disposition")
	if !strings.HasPrefix(cd, "attachment;") || !strings.Contains(cd, `\"final\"`) {
		t.Fatalf("Content-Disposition = %q", cd)
	}
}

func TestSignedURLs(t *testing.T) {
	secret := []byte("0123456789abcdef0123456789abcdef")
	now := time.Date(2026, 11, 28, 12, 0, 0, 0, time.UTC)
	h := RequireSignature(secret, func() time.Time { return now }, Handler(fixture()))

	good := Sign(secret, "/uploads/x.pdf", now.Add(time.Minute))
	if r := get(h, good); r.Code != 200 {
		t.Fatalf("valid signature: %d", r.Code)
	}
	if r := get(h, "/uploads/x.pdf"); r.Code != 403 {
		t.Fatalf("unsigned: %d", r.Code)
	}
	if r := get(h, strings.Replace(good, "x.pdf", "y.pdf", 1)); r.Code != 403 {
		t.Fatalf("path swapped under the same signature: %d", r.Code)
	}
	expired := Sign(secret, "/uploads/x.pdf", now.Add(-time.Second))
	if r := get(h, expired); r.Code != 403 {
		t.Fatalf("expired: %d", r.Code)
	}
	forged := strings.Replace(good, "exp=", "exp=9", 1)
	if r := get(h, forged); r.Code != 403 {
		t.Fatalf("extended expiry: %d", r.Code)
	}
}

ETag and conditional GET Must-know ​

In plain words: An ETag is a fingerprint of a specific version of a file. When a copy gets old, the client asks "I have fingerprint X, is it still current?" and gets a tiny 304 reply instead of the whole body.

Common misunderstanding: "The S3 ETag is the MD5 of the file." For a single PutObject without KMS it usually is, but the S3 guide says the multipart ETag "is not necessarily an MD5 hash of the object data". Treat it as an opaque validator, never as a checksum (use the checksum features for integrity).

Definition: The server sends ETag: "abc"; the client later sends If-None-Match: "abc"; if unchanged the server answers 304 Not Modified without a body. MDN distinguishes strong validators (suitable for byte-range caching) from weak ones (W/ prefix). http.ServeContent implements the conditional logic (If-None-Match, If-Modified-Since, If-Range) when you set the ETag header and the modification time.

1  GET /uploads/x.pdf                         -> 200 ETag: "p1"  Cache-Control: max-age=0, must-revalidate
2  (later) GET /uploads/x.pdf  If-None-Match: "p1"  -> 304 (no body)
3  object replaced; GET ... If-None-Match: "p1"      -> 200 ETag: "p2" + new body

Real scenario: a mutable profile PDF revalidated on each view at 200 bytes instead of 4 MB; a CDN revalidating with the bucket every hour; a client with If-Range resuming a download only if the object did not change.

ValidatorHeader pairStrengthNotes
ETagIf-None-MatchStrong (or weak with W/)Preferred
Last-ModifiedIf-Modified-SinceOne-second resolutionFallback
If-Rangewith RangeSame validatorsSafe resume

Fix / how to use it: the cdn test asserts a 304 with an empty body for a matching If-None-Match and a 200 for a stale one.

Range requests for video Important ​

In plain words: A video player asks for "bytes 1,000,000 to 2,000,000" so seeking works and nothing downloads twice. The server answers 206 with just those bytes.

Common misunderstanding: "Range support is something my Go code must implement for video." If you serve the bytes through http.ServeContent (an io.ReadSeeker), it already does Range, Content-Range, Accept-Ranges and 416. If you let the CDN and bucket serve them, the bucket and the CDN do it and your Go code is not involved.

Definition: The server advertises Accept-Ranges: bytes; the client sends Range: bytes=2-5; the server replies 206 Partial Content with Content-Range: bytes 2-5/20, or 416 when the range is outside the object. MDN notes that a response without Accept-Ranges means no range support. CloudFront handles Range GET requests at the edge for objects it caches. For S3 itself, GetObjectInput.Range takes the same bytes= syntax, which is how a Go proxy forwards ranges.

1  GET /v.mp4  Range: bytes=0-1048575        -> 206  Content-Range: bytes 0-1048575/52428800
2  user seeks: Range: bytes=31457280-         -> 206  from that offset
3  Range: bytes=999999999-                    -> 416  (outside the object)
4  Range + If-Range: "old-etag"             -> 200 whole object if the ETag changed

Real scenario: an MP4 on S3 behind CloudFront where seeking works without any code; a Go origin that proxies S3 and forgot to forward Range, so every seek downloads from byte 0; large downloads that resume after a network change; HLS, which avoids ranges by splitting into small segment files (cached as ordinary objects, authorised by signed cookies).

CaseWho serves rangesYour code
CDN to S3CDN and S3None
Go handler over a local file or bytes.Readerhttp.ServeContentProvide a ReadSeeker, ETag, mod time
Go proxy over S3YouParse Range, pass it as GetObjectInput.Range, return 206 and Content-Range yourself
Presigned S3 GETS3None; the browser sends Range

Fix / how to use it: serve media from the bucket through the CDN; use http.ServeContent only for small objects or local files. The cdn test checks the 206 body and Content-Range, the suffix form bytes=-4, 416, and the If-Range fallback.

Resizing: image resizing pipeline, on-upload vs on-the-fly Important ​

In plain words: Phones upload 6 MB photos; pages need 320-pixel thumbnails. Either make the small versions when the file arrives, or make them the first time somebody asks and cache the result.

Common misunderstanding: "On the fly is more flexible, so it is better." It is also an unauthenticated CPU job: any URL with ?w=1,2,3,... creates a new cache entry and a new resize. Restrict variants to an allowlist and let the CDN cache the result.

Definition: On-upload means a worker (or the request itself) creates a fixed set of variants and stores them under derived keys (thumb/w320/<key>). On-the-fly means an image service computes a variant on a cache miss, usually behind the CDN, from the original. Either way: validate the header first (CheckImage), cap decode concurrency, re-encode (drops EXIF and appended bytes), never upscale, and cache with immutable. The snippet resizes with nearest-neighbour using only the standard library to keep the code dependency-free; production uses golang.org/x/image/draw or libvips for quality.

on upload                                  on the fly
1  PUT original (private)                  1  GET /img/w320/<key> -> CDN MISS
2  queue job {key}                         2  origin: Variant(320) allowed? else 400
3  worker: CheckImage, decode, 3 sizes     3  fetch original, CheckImage, resize, re-encode
4  PUT thumb/w160|w320|w640/<key>          4  respond with Cache-Control: immutable
5  mark row ready                          5  CDN stores; next requests are HITs

Real scenario: an e-commerce catalogue with four fixed sizes generated on upload; a CMS where designers request arbitrary crops on the fly behind a cache; a worker killed by a 100-megapixel upload before limits were added; an Accept header that selects WebP or AVIF variants (the cache key must then include Accept or you must use separate URLs).

AspectOn uploadOn the fly
First-view latencyFastSlow on first miss
StorageOne object per variantSame, after first request
FlexibilityFixed set; adding a size needs a backfillAny allowed variant instantly
Attack surfaceContained (worker, queue)Public CPU endpoint: needs allowlist, rate limit, concurrency cap
Failure modeVariant missing until job doneOrigin overload on a cold cache

Fix / how to use it: default to on-upload for the sizes you know, add an on-the-fly path only for long-tail variants with an allowlist (resize.Sizes) and a semaphore.

go
// Package resize creates thumbnails on upload (or on demand) with the
// standard library only. Production code usually uses golang.org/x/image/draw
// or libvips for quality and speed; the shape of the pipeline is the point.
package resize

import (
	"bytes"
	"errors"
	"fmt"
	"image"
	"image/jpeg"
	"image/png"
	"io"

	"academy/file-uploads-s3-cdn/validate"
)

// Sizes is the allowlist of widths the on-the-fly endpoint will produce. An
// open "?w=<any number>" parameter lets anyone create unlimited cache entries
// and unlimited CPU work.
var Sizes = map[int]bool{160: true, 320: true, 640: true, 1280: true}

// ErrSize means the requested width is not in Sizes.
var ErrSize = errors.New("width not allowed")

// Variant returns the object key of a derived image: "thumb/w320/<key>".
func Variant(w int, key string) (string, error) {
	if !Sizes[w] {
		return "", fmt.Errorf("%w: %d", ErrSize, w)
	}
	return fmt.Sprintf("thumb/w%d/%s", w, key), nil
}

// Thumbnail decodes src (after the header check), scales it to at most
// maxW pixels wide keeping the aspect ratio, and re-encodes it. Re-encoding
// drops EXIF (GPS position, camera serial) and any bytes appended to the file.
func Thumbnail(src []byte, maxW int, lim validate.ImageLimits) ([]byte, string, error) {
	if _, _, err := validate.CheckImage(bytes.NewReader(src), lim); err != nil {
		return nil, "", err
	}
	img, format, err := image.Decode(bytes.NewReader(src))
	if err != nil {
		return nil, "", err
	}
	b := img.Bounds()
	w, h := b.Dx(), b.Dy()
	if w > maxW {
		h = h * maxW / w
		w = maxW
	}
	if h < 1 {
		h = 1
	}
	dst := image.NewRGBA(image.Rect(0, 0, w, h))
	for y := 0; y < h; y++ {
		for x := 0; x < w; x++ { // nearest neighbour
			dst.Set(x, y, img.At(b.Min.X+x*b.Dx()/w, b.Min.Y+y*b.Dy()/h))
		}
	}
	var out bytes.Buffer
	var ctype string
	if format == "jpeg" {
		err, ctype = jpeg.Encode(&out, dst, &jpeg.Options{Quality: 82}), "image/jpeg"
	} else {
		err, ctype = png.Encode(&out, dst), "image/png"
	}
	if err != nil {
		return nil, "", err
	}
	return out.Bytes(), ctype, nil
}

// ReadAllLimited reads at most max bytes and fails if there is more.
func ReadAllLimited(r io.Reader, max int64) ([]byte, error) {
	b, err := io.ReadAll(io.LimitReader(r, max+1))
	if err != nil {
		return nil, err
	}
	if int64(len(b)) > max {
		return nil, errors.New("input too large")
	}
	return b, nil
}

Cleanup of orphans and lifecycle rules Must-know ​

In plain words: Uploads create an object in one system and a row in another, and no transaction spans both. Sooner or later one exists without the other. Plan the cleanup before the first user does.

Common misunderstanding: "If the database insert fails I just delete the object in the error handler." The process can crash between the two steps, the delete itself can fail, and a browser can abandon a presigned upload after you wrote the row. Only a periodic sweep is reliable.

Definition: An orphan is an object with no row (crash before insert, abandoned direct upload) or a row whose object never arrived. Two-phase pattern: write a pending row with the planned key, upload, then mark it committed; a sweeper deletes objects of rows still pending after a TTL and objects older than a grace period that no row knows. Lifecycle rules are bucket-level automation: transition or expire by prefix and age, and AbortIncompleteMultipartUpload for stuck multipart uploads. Spaces supports time-based expiry and removing incomplete multipart uploads but not tag-based rules (its S3 compatibility table).

1  POST /uploads/sign   -> INSERT uploads(key, status='pending', created_at=now)
2  browser PUT to bucket (may never happen)
3  POST /uploads/42/confirm -> HeadObject ok -> UPDATE status='committed'
4  sweeper every 10 min: pending older than 1 h -> DeleteObject + status='deleted'
5  reconcile nightly: objects older than 24 h with no row -> DeleteObject
sql
CREATE TABLE uploads (
  id            bigserial PRIMARY KEY,
  owner_id      bigint      NOT NULL,
  object_key    text        NOT NULL UNIQUE,
  original_name text        NOT NULL,
  content_type  text        NOT NULL,
  size_bytes    bigint      CHECK (size_bytes >= 0),
  status        text        NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'committed', 'deleted')),
  created_at    timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX uploads_pending_idx ON uploads (created_at) WHERE status = 'pending';

-- the sweeper's query (FOR UPDATE SKIP LOCKED lets several sweepers share the work)
SELECT id, object_key FROM uploads
WHERE status = 'pending' AND created_at < now() - interval '1 hour'
ORDER BY created_at LIMIT 100
FOR UPDATE SKIP LOCKED;
json
{
  "Rules": [
    {
      "ID": "abort-stuck-multipart",
      "Status": "Enabled",
      "Filter": { "Prefix": "" },
      "AbortIncompleteMultipartUpload": { "DaysAfterInitiation": 7 }
    },
    {
      "ID": "expire-incoming",
      "Status": "Enabled",
      "Filter": { "Prefix": "incoming/" },
      "Expiration": { "Days": 2 }
    }
  ]
}

Real scenario: a signup flow where half the avatars were abandoned uploads; a bucket whose bill included terabytes of incomplete multipart parts; a user deletion request (privacy) that must remove objects and derived thumbnails by prefix; versioned buckets where deleting writes a delete marker and old versions still cost money (use noncurrent-version expiry).

ToolHandlesDoes not handle
TransactionRow consistencyThe object
SweepPendingAbandoned direct uploads, failed confirmsObjects with no row
ReconcileCrashes before the row insertIn-flight uploads (hence the grace period)
Lifecycle Expiration on incoming/Anything never movedAnything you must keep
AbortIncompleteMultipartUploadStuck partsCompleted objects

Fix / how to use it: the orphans package implements both sweeps against interfaces and its tests prove idempotence and that in-flight and known objects survive.

go
// Package orphans removes objects that no database row points to. Uploads
// create two things (an object and a row) and no transaction spans both, so
// one of them can be left behind. The two-phase pattern: write a "pending"
// row first, upload, then mark it "committed"; a sweeper deletes what stayed
// pending too long.
package orphans

import (
	"context"
	"time"

	"academy/file-uploads-s3-cdn/objstore"
)

// Status of an upload row.
type Status string

// The row life cycle.
const (
	Pending   Status = "pending"
	Committed Status = "committed"
	Deleted   Status = "deleted"
)

// Row mirrors the uploads table (see the SQL on the page).
type Row struct {
	Key       string
	Status    Status
	CreatedAt time.Time
}

// Repo is the slice of the database the sweeper needs.
type Repo interface {
	StalePending(ctx context.Context, before time.Time) ([]Row, error)
	MarkDeleted(ctx context.Context, key string) error
}

// Lister lists objects under a prefix with their last-modified time (S3
// ListObjectsV2 pages in real code).
type Lister interface {
	List(ctx context.Context, prefix string) (map[string]time.Time, error)
	Known(ctx context.Context, keys []string) (map[string]bool, error)
}

// SweepPending deletes the object of every upload still pending after ttl,
// then marks the row. Deleting a missing object is not an error, so the job
// is safe to re-run after a crash.
func SweepPending(ctx context.Context, repo Repo, store objstore.Store, now time.Time, ttl time.Duration) (int, error) {
	rows, err := repo.StalePending(ctx, now.Add(-ttl))
	if err != nil {
		return 0, err
	}
	n := 0
	for _, r := range rows {
		if err := store.Delete(ctx, r.Key); err != nil {
			return n, err
		}
		if err := repo.MarkDeleted(ctx, r.Key); err != nil {
			return n, err
		}
		n++
	}
	return n, nil
}

// Reconcile finds objects older than grace that have no row at all (the
// crash happened before the row was written) and deletes them. The grace
// period protects uploads that are still in flight.
func Reconcile(ctx context.Context, l Lister, store objstore.Store, prefix string, now time.Time, grace time.Duration) (int, error) {
	objs, err := l.List(ctx, prefix)
	if err != nil {
		return 0, err
	}
	var old []string
	for k, mod := range objs {
		if now.Sub(mod) > grace {
			old = append(old, k)
		}
	}
	known, err := l.Known(ctx, old)
	if err != nil {
		return 0, err
	}
	n := 0
	for _, k := range old {
		if known[k] {
			continue
		}
		if err := store.Delete(ctx, k); err != nil {
			return n, err
		}
		n++
	}
	return n, nil
}

Mechanics ​

Limits and defaults, with their sources Important ​

ItemValueSource
FormFile default memory32 MiB (defaultMaxMemory)net/http/request.go
Extra memory reserved for non-file parts in ReadForm10 MB on top of maxMemorymime/multipart/formdata.go
Parts per form1000 (GODEBUG=multipartmaxparts)mime/multipart package doc, Go 1.20 notes
Headers per part10000 (GODEBUG=multipartmaxheaders)same
Bytes DetectContentType reads512net/http/sniff.go
Uploader part size, minimum and default5 MiB (MinUploadPartSize)feature/s3/manager/upload.go
Uploader concurrency, default5same
Uploader max parts10000 (MaxUploadParts)same
transfermanager part size, threshold, concurrency8 MiB, 16 MiB, 5feature/s3/transfermanager/api_client.go
S3 multipart: parts, part size, last part1 to 10,000; 5 MiB to 5 GiB; no minimum for the lastS3 user guide, multipart limits
S3 max object size48.8 TiBsame page
Presigned URL expiry (default in the SDK)900 s (15 min); POST policy also 15 minservice/s3 source comments
Presigned URL expiry (maximum)7 days for an IAM user (SigV4); bounded by temporary credentialsS3 user guide
CloudFront default TTL without a cache policy24 hoursCloudFront guide

Anatomy of a presigned URL Important ​

The values below are real output of the presign test with fake credentials AKIDEXAMPLE:

host         s3.example.test              path /uploads/incoming/2026/11/a.png   (path style)
X-Amz-Algorithm      AWS4-HMAC-SHA256
X-Amz-Credential     AKIDEXAMPLE/20261128/eu-central-1/s3/aws4_request     key id / date / region / service / terminator
X-Amz-Date           (UTC timestamp of signing)
X-Amz-Expires        300                                                   seconds from X-Amz-Date
X-Amz-SignedHeaders  content-length;content-type;host
X-Amz-Signature      64 hex characters = HMAC-SHA256 over the canonical request

The signature is an HMAC chain keyed by the secret, the date, the region and the service, so S3 recomputes it from the request it receives: change any signed header, the method, the key or the expiry and the signature no longer matches (HTTP 403). Unsigned headers can change freely, which is why you sign Content-Type. A POST policy signs the base64 policy document instead of a request.

Why FormFile uses disk, and what the server cleans up Good to know ​

ReadForm keeps file bytes in memory while the running total is below maxMemory, then writes the part to a temporary file in os.TempDir() (container root volumes are often small). The net/http server calls MultipartForm.RemoveAll() after the handler returns, but a handler that spawns a goroutine using FormFile data after returning reads files that no longer exist. Streaming with MultipartReader never touches the disk.

Exact error texts Must-know ​

ErrorTextTest with
Body over MaxBytesReaderhttp: request body too largeerrors.As(err, &mbe) with var mbe *http.MaxBytesError
Non-file parts too largemultipart: message too largeerrors.Is(err, multipart.ErrMessageTooLarge)
Wrong API orderhttp: multipart handled by MultipartReader or http: multipart handled by ParseMultipartFormDo not mix the APIs
Not a multipart requestrequest Content-Type isn't multipart/form-data (http.ErrNotMultipart)errors.Is(err, http.ErrNotMultipart)
Missing file fieldhttp: no such file (http.ErrMissingFile)errors.Is
S3 key missingNoSuchKey (GET) / NotFound (HEAD)errors.As with *types.NoSuchKey, *types.NotFound
Part too small in multipartpart size must be at least 5242880 bytes (SDK Uploader)Set PartSize at least MinUploadPartSize

Solving the classic problems ​

ProblemSolutionHowCost
Memory or disk exhausted by big bodiesBound and streamMaxBytesReader plus MultipartReader into UploaderCannot parse out-of-order forms
Stored XSS via mislabelled HTML or SVGAllowlist, sniff, nosniff, attachment, separate originAllowlist.Check, cdn headersSome formats refused
Image bombHeader check then re-encodeCheckImage, ThumbnailCPU for re-encoding
Two users overwrite one fileRandom keyskeys.RandomNames live in the database
Bandwidth bill and slow pagesDirect upload plus CDNPresigned PUT or POST, immutable keysVerification after the fact
Stuck multipart parts billedAbort plus lifecycleUploader aborts; AbortIncompleteMultipartUploadNone
Orphan objects and rowsTwo-phase status plus sweepsorphans package, SQL belowA cron job
Private file leaked by URLShort-lived signed URL, private bucketPresign or CDN signatureLinks expire
Stale file after replaceNew key, not purgeVersioned or content keysUpdate the reference

Direct upload without trusting the client ​

The weak point of direct upload is that the bytes never pass your code. Close the gap in three layers: the signature pins the key, type and size; the confirm endpoint calls HeadObject and compares size and Content-Type with what you signed; and an asynchronous worker downloads the first 512 bytes (a ranged GetObject), sniffs, runs CheckImage and the virus scan, then moves the object from incoming/ to its final prefix or deletes it. Only the final prefix is reachable from the CDN.

Private downloads without proxying ​

Return a 302 to a presigned GET (S3 checks it) or to a CDN signed URL (the edge checks it). Add ResponseContentDisposition for the friendly name. Keep the TTL to seconds or minutes for sensitive files; log the file id, never the URL.

Retrying and idempotency ​

PutObject of the same key and bytes is idempotent, DeleteObject too, so retries on network errors are safe; the SDK retries by itself with its retry middleware. A confirm endpoint should be idempotent (committing twice is a no-op), and a presign endpoint should return a fresh URL per call without reusing keys.

Choosing ​

SituationRecommendationExtra techniqueReason
Avatar up to 2 MB, must be validatedProxy through your handlerMaxBytesReader, CheckImage, re-encodeYou see every byte
Video up to several GBPresigned multipart or transfermanagerCORS plus ExposeHeaders ETag, lifecycle abort ruleYour servers carry nothing
Browser form with a hard size capPOST policycontent-length-range, starts-with keySize enforced by S3
Mobile app, any providerPresigned PUTSign Content-Type and Content-LengthWorks everywhere, even R2
Public imagesPublic immutable URLs on a CDNContent or random key, immutableCache hit ratio, no purges
Private documentsPrivate bucket plus signed URL or cookieOAC, short TTLNo public bucket
Many sizes of an imageVariants on upload, long tail on the flyAllowlist of widthsCPU control
Single small server, few filesLocal disk behind the Store interfaceBackups, file permissionsSimplest correct thing
Compliance on key controlSSE-KMSPer-tenant keys, KMS auditRevocation and audit
Vendor flexibilityAWS SDK v2 with a Config structContract test per endpointSame code across S3, MinIO, R2, Spaces

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

The simplest correct monolith has a Store interface with a local-disk implementation outside the web root, random keys, one uploads table with a status column, and files served by a handler that authorises by row (someid to file) rather than by path, as OWASP advises. Limits and sniffing already apply. When the server moves to two instances behind a load balancer, switch the implementation to object storage; handlers do not change. Example: a Go and PostgreSQL blog with 2 MB cover images stored under /var/data/uploads/<random>, served by http.ServeContent with an ETag, with a nightly rsync.

Modular monolith and multiple databases ​

Give the storage module the only credentials and the only bucket client; other modules call Upload(ctx, owner, reader) and receive a key or an upload id. Keep the table with the object keys in the module that owns the file's meaning (documents, avatars), and let each module use its own prefix (avatars/, invoices/) with prefix-scoped IAM. A cross-module delete (user removal) becomes a call per module, each of which deletes rows then objects through the sweeper so a crash cannot strand data.

Microservices ​

An upload service owns presigning, confirmation and the bucket; other services refer to files by id and ask it for a short-lived download URL. Example flow: the web app asks uploads for a presigned PUT, the browser uploads straight to the bucket, S3 emits an object-created event to a queue, a media service consumes it (see Event-Driven Go), validates and creates thumbnails, and publishes file.ready; orders stores only the file id. What does not survive a service boundary: the pending-row and the object are still two stores, so events must be idempotent and the sweeper must cover them, and a signed URL minted by one service is valid for anyone, so pass ids, not URLs, between services.

Distributed data: replicas, caches, sharded databases, multi-region ​

Object stores replicate for you but with their own rules: a bucket lives in one region unless you configure replication, which is asynchronous and can lag. A CDN is a cache with its own consistency: after you replace an object under the same key, edges may serve the old copy until the TTL ends or an invalidation completes, which is why immutable keys are the distributed-systems answer, not a trick. Database replicas matter too: if the confirm endpoint writes to the primary and the next page reads a replica, the new file may not be listed yet, so return the file URL in the confirm response. For multi-region, keep the metadata row in your regional database and put the bucket region next to the writers; cross-region copy by a worker, not by clients.

Scaling path: 1×, 10×, 100× ​

LoadWhat breaksPractice
1× (one instance)Disk space, abuseLimits, allowlist, random keys, local Store or one bucket
10× (several instances, real users)Disk locality, bandwidth through the appObject storage, direct uploads for big files, CDN for reads, sweepers
100× (many services and regions)Origin load on cold caches, resize CPU, cost of egress and requestsImmutable keys, shielded origin, resize workers with queues and concurrency caps, lifecycle tiering, per-tenant prefixes and quotas, rate limiting the sign endpoint

Lab ​

1. Run the tests (real) ​

cd docs/snippets/go/file-uploads-s3-cdn/go
gofmt -l . && go vet ./... && go test -race -count=1 ./...
# ok  academy/file-uploads-s3-cdn/after
# ok  academy/file-uploads-s3-cdn/before
# ok  academy/file-uploads-s3-cdn/cdn
# ok  academy/file-uploads-s3-cdn/keys
# ok  academy/file-uploads-s3-cdn/objstore
# ok  academy/file-uploads-s3-cdn/orphans
# ok  academy/file-uploads-s3-cdn/presign
# ok  academy/file-uploads-s3-cdn/resize
# ok  academy/file-uploads-s3-cdn/s3store
# ok  academy/file-uploads-s3-cdn/validate

2. Read a presigned URL without any S3 (real) ​

go test -count=1 -v -run TestPresignedPutLogsAnatomy ./presign signs with fake credentials and a made-up host and logs the pieces (real output, Go 1.27.4). Nothing is sent over the network.

host=s3.example.test path=/uploads/incoming/2026/11/a.png
X-Amz-Algorithm=AWS4-HMAC-SHA256
X-Amz-Credential=AKIDEXAMPLE/20261128/eu-central-1/s3/aws4_request
X-Amz-Expires=300
X-Amz-SignedHeaders=content-length;content-type;host
X-Amz-Signature length=64
headers the browser must send: map[Content-Length:[1234] Content-Type:[image/png] Host:[s3.example.test]]

TestPresignedPutIsOffline asserts content-length is among the signed headers; removing ContentLength from the signer makes it fail (the size must be signed: SignedHeaders=content-type;host).

3. The 74-byte image bomb (real) ​

validate_test.go patches the IHDR width and height of a 1x1 PNG and recomputes its CRC. Measured in the test run: the file is 74 bytes, the claimed size 60000 x 60000 is 3,600,000,000 pixels (14,400,000,000 bytes as RGBA), and CheckImage rejects it with ErrTooBig after reading the header only.

4. Multipart against a fake S3 (real) ​

TestUploaderUsesMultipartAboveOnePart uploads 12 MiB + 1 byte from a plain reader and asserts exactly three UploadPart calls, one create and one complete; TestReaderErrorAbortsMultipart makes the reader fail after 7 MiB and asserts an AbortMultipartUpload (DELETE ...?uploadId=) and no object. transfermanager is run the same way.

5. Direct browser upload with CORS against a real bucket (expected, not run) ​

# 1. apply the CORS JSON from the CORS section to the bucket
# 2. ask your server for a URL
curl -s -X POST localhost:8080/uploads/sign -d '{"filename":"a.png","content_type":"image/png","size":1234}'
# expected: {"method":"PUT","url":"https://.../uploads/incoming/2026/11/<hex>.png?X-Amz-...","headers":{"Content-Type":"image/png"},...}
# 3. upload with the same headers
curl -X PUT -H 'Content-Type: image/png' --data-binary @a.png "<url>"      # expected: HTTP 200
curl -X PUT -H 'Content-Type: text/html' --data-binary @a.png "<url>"     # expected: HTTP 403 (signed header differs)

6. CDN headers and ranges against a real distribution (expected, not run) ​

curl -sI https://cdn.example.test/assets/ab/<hash>.png | grep -i -E 'cache-control|etag|age|x-cache'
# expected: cache-control: public, max-age=31536000, immutable ; an ETag ; a hit header on the second call
curl -s -o /dev/null -w '%{http_code}\n' -H 'Range: bytes=0-99' https://cdn.example.test/v.mp4        # expected: 206
curl -s -o /dev/null -w '%{http_code}\n' https://example-uploads.s3.eu-central-1.amazonaws.com/v.mp4  # expected: 403 (bucket private)

For PHP/Laravel developers ​

Laravel's filesystem layer is Flysystem: "simple drivers for working with local filesystems, SFTP, and Amazon S3", with the S3 driver installed through league/flysystem-aws-s3-v3. Storage::putFile streams an uploaded file and, by default, "will generate a unique ID to serve as the filename" with the extension from the file's MIME type, which is the random-key rule built in; the temporary-URL helper is Storage::temporaryUrl for the local and s3 drivers, the counterpart of PresignGetObject, and Storage::temporaryUploadUrl is the counterpart of PresignPutObject. AWS_USE_PATH_STYLE_ENDPOINT and AWS_ENDPOINT are the same two knobs as UsePathStyle and BaseEndpoint.

php
// Laravel: validate, store under a random name on the s3 disk, hand out a 5-minute link.
$request->validate(['photo' => ['required', 'image', 'max:2048']]);   // max is in KB
$path = Storage::disk('s3')->putFile('photos', $request->file('photo'));
$url  = Storage::disk('s3')->temporaryUrl($path, now()->addMinutes(5));
Laravel / PHPGo in this chapter
upload_max_filesize, post_max_size (php.ini)http.MaxBytesReader, per-file capReader
$request->file(), UploadedFiler.MultipartReader() parts
image, mimes, max validation rulesAllowlist.Check, CheckImage, size caps
Storage::putFile (random name)keys.Random plus Store.Put
Storage::disk('s3')s3store.Store
Storage::temporaryUrlSigner.Get
Storage::temporaryUploadUrl (returns url and headers)Signer.Put
Flysystem adapters for MinIO, R2, SpacesOne s3store.Config with Endpoint and PathStyle
visibility public/privateBucket policy and CDN; keys are not guessable

The big difference is the process model: a Go handler streams the body as it arrives, so the limit must be enforced by your code and, with MultipartReader, the file never exists locally; PHP's upload limits are configuration (upload_max_filesize, post_max_size in php.ini, and the web server). For direct browser uploads Laravel has a counterpart of PresignClient: Storage::temporaryUploadUrl, supported by the s3 and local drivers, returns the URL and the headers to send, and the docs call it "primarily useful in serverless environments that require the client-side application to directly upload files to a cloud storage system such as Amazon S3".

Common misconceptions ​

BeliefReality
ParseMultipartForm(n) limits the upload to n bytesIt limits memory; the rest goes to temp files
Content-Type of the part proves the file typeIt is client input; sniff the bytes and compare
filepath.Base makes any name safePlatform dependent; and names must not be keys anyway
io.LimitReader is enough for a size limitIt truncates silently; use MaxBytesReader or an erroring reader
A small file cannot be dangerousAn image header can claim billions of pixels
Presigned URLs are tied to the userThey are bearer tokens tied to the signer's permissions
CORS protects the bucketIt only tells browsers what to allow; curl ignores it
Public bucket is the easy way to serve filesUse a private bucket with CDN origin access control
S3 ETag is always the MD5 of the objectNot for multipart uploads or some encryption modes
Failed multipart uploads cost nothingUploaded parts are stored and billed until aborted
Replacing a file under the same key updates every userCaches keep the old copy; use new keys
S3-compatible means identicalEach provider supports a subset (R2 has no POST policy; Spaces has partial support)
manager.Uploader is the current APIIt is marked deprecated in favour of transfermanager

Cheat sheet ​

TopicRemember
Body limithttp.MaxBytesReader; check *http.MaxBytesError; answer 413
ParsingMultipartReader to stream; ParseMultipartForm only for small forms
NameDisplay only; SanitizeFilename; never the key
Keycrypto/rand, 128 bits, prefix by date; content hash for immutable assets
TypeExtension allowlist + DetectContentType (512 bytes) + declared type must agree
Imagesimage.DecodeConfig before Decode; limit pixels; re-encode
MalwareScan asynchronously; quarantine prefix
S3 clients3.New with BaseEndpoint, UsePathStyle, Region; WhenRequired checksums for S3-compatible servers
Big filestransfermanager (or deprecated manager.Uploader); abort on error; lifecycle abort rule
PresignedSign type and length; 5 to 15 minutes; never log; bearer token
POST policycontent-length-range, key prefix; not on R2
CORSOrigin, method, headers; ExposeHeaders ETag
AccessPrivate bucket, prefix-scoped IAM, Block Public Access, OAC for CDN
EncryptionSSE-S3 by default; SSE-KMS for key control
DownloadsContent-Disposition via mime.FormatMediaType; nosniff
CDNImmutable keys, max-age=31536000, immutable; mutable keys revalidate with ETag
Rangeshttp.ServeContent or leave it to bucket and CDN
Cleanuppending rows, sweeps, lifecycle rules

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — What does the argument of r.ParseMultipartForm limit? Must-know ​

Answer

Answer: Memory, not request size. File parts beyond maxMemory (plus a 10 MB reserve for non-file parts) go to temporary files, so a huge upload still arrives and fills /tmp. Wrap the body in http.MaxBytesReader to bound it. See multipart.

2 — Why is io.LimitReader the wrong tool for an upload size limit? Must-know ​

Answer

Answer: It returns EOF at the limit, so an oversized file looks complete and is stored truncated. http.MaxBytesReader returns *http.MaxBytesError (and closes the connection); the snippet's capReader returns an error on the first byte past the cap. See limits.

3 — A client sends filename="..\..\evil.exe" to a Go server on Linux. What does Part.FileName() return, and what should you do? Must-know ​

Answer

Answer: It applies filepath.Base, which on Linux treats only / as a separator, so the backslash path is returned unchanged. Normalise both separators for the display name and never use any client name as the storage key; generate a random key. See names.

4 — Why compare the extension, the declared Content-Type and the sniffed type? Must-know ​

Answer

Answer: Each is client-controlled except the bytes, and the bytes only give a guess from the first 512 bytes. Requiring all three to agree and the type to be on an allowlist catches HTML named .png, PHP with an image header, and honest mistakes. Serve with the stored type and X-Content-Type-Options: nosniff. See content type.

5 — How can a 74-byte file exhaust memory, and how do you stop it? Important ​

Answer

Answer: An image header can claim 60000 by 60000 pixels; image.Decode would allocate the full pixel buffer. image.DecodeConfig reads only the header, so compare width, height and width times height with limits before decoding, then re-encode. See images.

6 — What is the difference between a presigned PUT URL and a POST policy for size control? Important ​

Answer

Answer: A presigned PUT can only fix an exact Content-Length (if you sign it). A POST policy can carry content-length-range with a minimum and maximum, a key prefix and a content-type condition. R2 documents that POST form uploads are not supported. See POST policy.

7 — A browser upload to a presigned URL fails with a CORS error but curl works. Why? Must-know ​

Answer

Answer: curl does no preflight. The browser asks the bucket whether the origin, the method (PUT) and the headers (for example content-type) are allowed; the bucket's first matching CORSRule decides. Add the origin, method and headers, and list ETag in ExposeHeaders if the page reads it. See direct.

8 — What happens to the parts of a multipart upload that is never completed? Important ​

Answer

Answer: They remain and are billed as storage. The SDK uploader aborts when its reader fails, but crashed clients leave uploads behind, so add a lifecycle rule with AbortIncompleteMultipartUpload (the AWS example uses 7 days). See multipart upload.

9 — Which AWS SDK package should new code use for large uploads, and what is the status of manager.Uploader? Good to know ​

Answer

Answer: feature/s3/transfermanager (announced generally available January 30, 2026). feature/s3/manager carries a "Deprecated: superceded by feature/s3/transfermanager" notice, though it still compiles and works. See multipart upload.

10 — Why do immutable, content-addressed keys beat cache invalidation for uploads? Important ​

Answer

Answer: New bytes get a new URL, so edges and browsers can cache the old one for a year with immutable; there is nothing to purge, and invalidation neither reaches browser caches nor is free at volume. AWS itself recommends versioned file names for files updated often. See CDN cache.

11 — How do you serve a private file through a CDN without making the bucket public? Important ​

Answer

Answer: Keep the bucket private, grant read only to the distribution with origin access control (CloudFront OAC), and have the edge require a signed URL or signed cookie with a short expiry. A presigned S3 URL is checked by S3 instead and varies the cache key. See private.

12 — A client says If-None-Match: "p1" and the object is unchanged. What does the origin return and why does it matter? Good to know ​

Answer

Answer: 304 Not Modified with no body, so a revalidation costs a few hundred bytes instead of the file. Do not assume the S3 ETag is an MD5: for multipart uploads it is not. See ETag.

13 — How do you keep uploads, database rows and objects consistent when no transaction spans them? Important ​

Answer

Answer: Insert a pending row, upload, confirm with HeadObject and mark committed; sweep pending rows older than a TTL and objects older than a grace period with no row; add lifecycle rules for the incoming prefix. All deletes are idempotent so the jobs can be retried. See cleanup.

Glossary ​

TermMeaning
multipart/form-dataBody format of HTML file forms: parts with their own headers separated by a boundary (RFC 7578)
ParseMultipartFormParses the whole body; its argument is a memory limit, the rest goes to temp files
FormFileReturns the first file for a key; parses with a 32 MiB memory limit if needed
MultipartReaderStreams parts one by one without buffering the body
http.MaxBytesReaderReader wrapper that errors past a byte limit and can close the connection
http.DetectContentTypeSniffs a media type from at most the first 512 bytes (WHATWG MIME sniffing)
Magic bytesFixed signature at a known offset that identifies a format
Extension allowlistMap of accepted extensions to the one type each must sniff as
filepath.BaseLast element of a path using the platform's separators
Path traversalA name or key that escapes the intended directory
Random object keyStorage key built from crypto/rand, not from client input
Decompression bombTiny encoded input that expands to huge memory when decoded
image.DecodeConfigReads an image header (size, color model) without allocating pixels
Virus scanAntivirus or content disarm step run asynchronously on stored uploads
s3.ClientAWS SDK for Go v2 S3 client; one per configuration, safe for concurrent use
PutObject, GetObject, HeadObject, DeleteObjectThe four basic S3 object operations
manager.UploaderSDK helper that streams a reader as single or multipart upload (deprecated)
transfermanagerSuccessor transfer helper for uploads and downloads
Multipart uploadObject sent as numbered parts (5 MiB to 5 GiB each) and then completed
PresignClientSDK type that builds presigned requests offline
Presigned URLURL with a SigV4 signature authorising one request until it expires
ExpiryLifetime of a presigned URL; up to 7 days, bounded by credential lifetime
POST policySigned JSON rulebook for a browser form upload (conditions, size range, key prefix)
ConditionsThe individual rules in a POST policy (eq, starts-with, content-length-range)
S3-compatibleA service that implements the S3 REST API with SigV4, usually partially
MinIOOpen-source S3-compatible object server and its Go client
Cloudflare R2Cloudflare's S3-compatible store; region auto, no POST policy
DigitalOcean SpacesDigitalOcean's S3-compatible store with a built-in CDN
EndpointBase URL of the S3 API (BaseEndpoint in the SDK)
Path stylehttps://host/bucket/key addressing, versus bucket in the host name
Bucket policyResource policy attached to a bucket
IAM least privilegeGranting only the actions and resources a principal needs
Block Public AccessS3 setting group that prevents public access to buckets and objects
SSE-S3Server-side encryption with S3-managed keys; default for new objects
SSE-KMSServer-side encryption with AWS KMS keys you control and audit
CORSBrowser mechanism by which a bucket allows cross-origin requests
Content-DispositionHeader choosing inline or attachment and the download file name (RFC 6266)
CDNNetwork of edge caches serving copies of your objects
Cache keyThe values (path, chosen query strings, headers, cookies) identifying a cached entry
Cache-ControlHeader controlling who may cache a response and for how long
immutableCache-Control directive: the response will not change while fresh
Versioned keyObject name containing a content hash or version, so changes mean new URLs
Origin access control (OAC)CloudFront feature that signs requests to a private S3 origin
Signed URL / signed cookieTime-limited, signature-checked access to CDN content
ETagOpaque validator of one version of a resource
Conditional GETRequest with If-None-Match or If-Modified-Since answered by 304 when unchanged
Range requestRequest for part of a resource; answered with 206 and Content-Range
OrphanObject without a database row, or a row without an object
Lifecycle ruleBucket automation that expires or transitions objects and aborts stuck uploads
FlysystemPHP filesystem abstraction underneath Laravel's Storage

References ​

Built by Morteza Negahi