File uploads

suggest change

Browsers and HTTP clients upload files with a POST request whose body is encoded as multipart/form-data. Go supports it in the standard library:

This article shows how to receive uploads on the server, how to limit and validate them, how to stream large files without buffering them, and how to upload files from a Go client. For other kinds of POST bodies see HTTP POST.

What a multipart body looks like

A multipart body is a list of parts separated by a boundary string. Each part has its own headers. A file part has a filename in its Content-Disposition header, and a regular form field doesn't.

We can see the exact bytes by encoding a body with multipart.Writer:

package main

import (
	"bytes"
	"fmt"
	"log"
	"mime/multipart"
)

func main() {
	var body bytes.Buffer
	mw := multipart.NewWriter(&body)
	// a fixed boundary only to make the output stable; normally you
	// let NewWriter pick a random one
	if err := mw.SetBoundary("XyZ123"); err != nil {
		log.Fatal(err)
	}

	mw.WriteField("title", "Holiday notes")

	fw, err := mw.CreateFormFile("file", "notes.txt")
	if err != nil {
		log.Fatal(err)
	}
	fw.Write([]byte("Day 1: beach\nDay 2: mountains\n"))

	// Close writes the final boundary
	if err := mw.Close(); err != nil {
		log.Fatal(err)
	}

	fmt.Println("Content-Type:", mw.FormDataContentType())
	fmt.Println()
	fmt.Print(body.String())
}
Content-Type: multipart/form-data; boundary=XyZ123

--XyZ123
Content-Disposition: form-data; name="title"

Holiday notes
--XyZ123
Content-Disposition: form-data; name="file"; filename="notes.txt"
Content-Type: application/octet-stream

Day 1: beach
Day 2: mountains

--XyZ123--

Things to know:

An HTML upload form

On the browser side, the form must use method="post" and enctype="multipart/form-data". Without enctype the browser sends only the file name, not its content.

package main

import (
	"fmt"
	"log"
	"net/http"
)

const page = `<!doctype html>
<form action="/upload" method="post" enctype="multipart/form-data">
  <input type="text" name="title">
  <input type="file" name="files" multiple accept="image/*">
  <button>Upload</button>
</form>`

func main() {
	http.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		fmt.Fprint(w, page)
	})
	http.HandleFunc("POST /upload", func(w http.ResponseWriter, r *http.Request) {
		r.Body = http.MaxBytesReader(w, r.Body, 20<<20)
		if err := r.ParseMultipartForm(1 << 20); err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
		for _, fh := range r.MultipartForm.File["files"] {
			fmt.Fprintf(w, "%s: %d bytes\n", fh.Filename, fh.Size)
		}
	})
	log.Fatal(http.ListenAndServe("localhost:8090", nil))
}

curl -F sends the same kind of request as the browser, which is handy for testing:

$ curl -F title=x -F files=@a.txt -F files=@b.txt http://localhost:8090/upload
a.txt: 3 bytes
b.txt: 6 bytes

accept="image/*" only filters the browser's file picker. Anyone can send anything to your server, so all checks must happen on the server.

Receiving a file with FormFile

The simplest way to get an uploaded file is r.FormFile(name). It returns:

The example below runs a test server with httptest, uploads a file to it and saves the file in an upload directory:

package main

import (
	"bytes"
	"fmt"
	"io"
	"log"
	"mime/multipart"
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"
)

var uploadDir *os.Root

func handleUpload(w http.ResponseWriter, r *http.Request) {
	// parse the body; up to 32 MB of file data is kept in memory,
	// anything larger goes to temporary files on disk
	if err := r.ParseMultipartForm(32 << 20); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	title := r.FormValue("title")

	file, header, err := r.FormFile("file")
	if err != nil {
		http.Error(w, "missing file: "+err.Error(), http.StatusBadRequest)
		return
	}
	defer file.Close()

	// never trust the client's file name as a path
	name := filepath.Base(header.Filename)
	dst, err := uploadDir.Create(name)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer dst.Close()

	n, err := io.Copy(dst, file)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	fmt.Fprintf(w, "saved %q (%d bytes, title %q, client type %q)\n",
		name, n, title, header.Header.Get("Content-Type"))
}

func upload(url, path string) {
	var body bytes.Buffer
	mw := multipart.NewWriter(&body)
	mw.WriteField("title", "Holiday notes")

	f, err := os.Open(path)
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()

	fw, err := mw.CreateFormFile("file", filepath.Base(path))
	if err != nil {
		log.Fatal(err)
	}
	if _, err := io.Copy(fw, f); err != nil {
		log.Fatal(err)
	}
	mw.Close()

	resp, err := http.Post(url, mw.FormDataContentType(), &body)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()
	msg, _ := io.ReadAll(resp.Body)
	fmt.Printf("%s %s", resp.Status, msg)
}

func main() {
	dir, _ := os.MkdirTemp("", "uploads")
	defer os.RemoveAll(dir)
	var err error
	uploadDir, err = os.OpenRoot(dir)
	if err != nil {
		log.Fatal(err)
	}
	defer uploadDir.Close()

	mux := http.NewServeMux()
	mux.HandleFunc("POST /upload", handleUpload)
	srv := httptest.NewServer(mux)
	defer srv.Close()

	// create a file to upload
	src := filepath.Join(os.TempDir(), "notes.txt")
	os.WriteFile(src, []byte("Day 1: beach\nDay 2: mountains\n"), 0o644)
	defer os.Remove(src)

	upload(srv.URL+"/upload", src)

	data, _ := uploadDir.ReadFile("notes.txt")
	fmt.Printf("on disk: %q\n", data)
}
200 OK saved "notes.txt" (30 bytes, title "Holiday notes", client type "application/octet-stream")
on disk: "Day 1: beach\nDay 2: mountains\n"

How it works:

Limiting upload size

maxMemory is not a limit on the upload size. It only decides what goes to memory and what goes to disk. Without a limit, a client can fill your disk with one request.

Wrap the body with http.MaxBytesReader before parsing. Reading past the limit returns an *http.MaxBytesError, which you can check with errors.As:

package main

import (
	"bytes"
	"errors"
	"fmt"
	"io"
	"mime/multipart"
	"net/http"
	"net/http/httptest"
)

const maxUploadSize = 1 << 20 // 1 MB

func handleUpload(w http.ResponseWriter, r *http.Request) {
	// reading more than maxUploadSize bytes of body returns an error
	r.Body = http.MaxBytesReader(w, r.Body, maxUploadSize)

	if err := r.ParseMultipartForm(256 << 10); err != nil {
		var maxErr *http.MaxBytesError
		if errors.As(err, &maxErr) {
			msg := fmt.Sprintf("file too large (limit is %d bytes)", maxErr.Limit)
			http.Error(w, msg, http.StatusRequestEntityTooLarge)
			return
		}
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	_, header, err := r.FormFile("file")
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	fmt.Fprintf(w, "accepted %s: %d bytes\n", header.Filename, header.Size)
}

func upload(url string, size int) {
	var body bytes.Buffer
	mw := multipart.NewWriter(&body)
	fw, _ := mw.CreateFormFile("file", fmt.Sprintf("data-%d.bin", size))
	fw.Write(make([]byte, size))
	mw.Close()

	resp, err := http.Post(url, mw.FormDataContentType(), &body)
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	defer resp.Body.Close()
	msg, _ := io.ReadAll(resp.Body)
	fmt.Printf("%d bytes -> %s: %s", size, resp.Status, msg)
}

func main() {
	srv := httptest.NewServer(http.HandlerFunc(handleUpload))
	defer srv.Close()

	upload(srv.URL, 500_000)
	upload(srv.URL, 2_000_000)
}
500000 bytes -> 200 OK: accepted data-500000.bin: 500000 bytes
2000000 bytes -> 413 Request Entity Too Large: file too large (limit is 1048576 bytes)

Notes:

Multiple files

<input type="file" multiple> sends every file as a separate part with the same field name. FormFile returns only the first one, so iterate r.MultipartForm.File[name] instead:

package main

import (
	"bytes"
	"crypto/sha256"
	"fmt"
	"io"
	"mime/multipart"
	"net/http"
	"net/http/httptest"
	"os"
	"strings"
)

func handleUpload(w http.ResponseWriter, r *http.Request) {
	r.Body = http.MaxBytesReader(w, r.Body, 10<<20)
	// keep at most 64 KB in memory, spill the rest to temp files
	if err := r.ParseMultipartForm(64 << 10); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	fmt.Fprintf(w, "tags: %v\n", r.MultipartForm.Value["tag"])

	for _, fh := range r.MultipartForm.File["files"] {
		f, err := fh.Open()
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		h := sha256.New()
		io.Copy(h, f)
		f.Close()

		where := "memory"
		if _, onDisk := f.(*os.File); onDisk {
			where = "temp file"
		}
		fmt.Fprintf(w, "%-10s %7d bytes  %-9s  sha256 %x\n",
			fh.Filename, fh.Size, where, h.Sum(nil)[:6])
	}
	// net/http deletes the temp files after the handler returns
}

func main() {
	srv := httptest.NewServer(http.HandlerFunc(handleUpload))
	defer srv.Close()

	var body bytes.Buffer
	mw := multipart.NewWriter(&body)
	mw.WriteField("tag", "photos")
	mw.WriteField("tag", "2026")
	files := map[string]string{
		"a.txt": "small file",
		"b.txt": strings.Repeat("x", 200_000),
		"c.txt": "",
	}
	for _, name := range []string{"a.txt", "b.txt", "c.txt"} {
		// same field name for all files, like <input type="file" multiple>
		fw, _ := mw.CreateFormFile("files", name)
		io.WriteString(fw, files[name])
	}
	mw.Close()

	resp, err := http.Post(srv.URL, mw.FormDataContentType(), &body)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	io.Copy(os.Stdout, resp.Body)
}
tags: [photos 2026]
a.txt           10 bytes  memory     sha256 fadd1986cc26
b.txt       200000 bytes  temp file  sha256 91e3faafd322
c.txt            0 bytes  memory     sha256 e3b0c44298fc

The 200 KB file didn't fit in the 64 KB memory budget, so it was stored in a temporary file. Your code doesn't need to care: fh.Open() returns a multipart.File either way. An empty file is still a valid part with Size 0, so check for it if empty files make no sense in your application.

Streaming uploads with MultipartReader

ParseMultipartForm reads the entire body before your handler sees any of it. For large files that means writing everything to a temporary file and then copying it again to its final place.

r.MultipartReader() gives you the parts one at a time, as they arrive. You read each part directly from the network, with no temporary files and no memory buffering. The trade-off is that parts come in the order the client sent them, and you can't go back.

This handler streams each file to disk, computes its SHA-256 on the way, enforces a per-file size limit and names the file after its hash:

package main

import (
	"bytes"
	"crypto/rand"
	"crypto/sha256"
	"encoding/hex"
	"errors"
	"fmt"
	"io"
	"log"
	"mime/multipart"
	"net/http"
	"net/http/httptest"
	"os"
	"strings"
)

const maxFileSize = 100_000

var uploadDir *os.Root

var errTooLarge = errors.New("file too large")

// saveStream copies at most limit bytes from src to a new file and returns
// its size and SHA-256. The file is named after its hash, so the client
// never chooses a path.
func saveStream(src io.Reader, limit int64) (int64, string, error) {
	// random temporary name so concurrent uploads don't collide
	tmpName := rand.Text() + ".tmp"
	tmp, err := uploadDir.Create(tmpName)
	if err != nil {
		return 0, "", err
	}
	h := sha256.New()
	// read one byte more than the limit to detect files that are too big
	n, err := io.Copy(io.MultiWriter(tmp, h), io.LimitReader(src, limit+1))
	tmp.Close()
	if err == nil && n > limit {
		err = errTooLarge
	}
	if err != nil {
		uploadDir.Remove(tmpName)
		return 0, "", err
	}
	sum := hex.EncodeToString(h.Sum(nil))
	return n, sum, uploadDir.Rename(tmpName, sum)
}

func handleUpload(w http.ResponseWriter, r *http.Request) {
	r.Body = http.MaxBytesReader(w, r.Body, 10<<20)
	mr, err := r.MultipartReader()
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	// don't write to w until all parts are processed, so that we can
	// still send an error status
	var out strings.Builder
	for {
		part, err := mr.NextPart()
		if err == io.EOF {
			break
		}
		if err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}

		if part.FileName() == "" {
			// a regular form field
			v, _ := io.ReadAll(io.LimitReader(part, 1024))
			fmt.Fprintf(&out, "field %s = %q\n", part.FormName(), v)
			continue
		}

		n, sum, err := saveStream(part, maxFileSize)
		if errors.Is(err, errTooLarge) {
			http.Error(w, part.FileName()+": too large", http.StatusRequestEntityTooLarge)
			return
		}
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		fmt.Fprintf(&out, "file %s: %d bytes, stored as %s...\n", part.FileName(), n, sum[:12])
	}
	io.WriteString(w, out.String())
}

func post(url string, files map[string]string) {
	var body bytes.Buffer
	mw := multipart.NewWriter(&body)
	mw.WriteField("album", "summer")
	for name, content := range files {
		fw, _ := mw.CreateFormFile("file", name)
		io.WriteString(fw, content)
	}
	mw.Close()
	resp, err := http.Post(url, mw.FormDataContentType(), &body)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()
	fmt.Println(resp.Status)
	io.Copy(os.Stdout, resp.Body)
}

func main() {
	dir, _ := os.MkdirTemp("", "uploads")
	defer os.RemoveAll(dir)
	uploadDir, _ = os.OpenRoot(dir)
	defer uploadDir.Close()

	srv := httptest.NewServer(http.HandlerFunc(handleUpload))
	defer srv.Close()

	post(srv.URL, map[string]string{"photo.jpg": strings.Repeat("j", 80_000)})
	post(srv.URL, map[string]string{"video.mp4": strings.Repeat("v", 150_000)})

	entries, _ := os.ReadDir(dir)
	fmt.Println("files on disk:", len(entries))
}
200 OK
field album = "summer"
file photo.jpg: 80000 bytes, stored as 1b1de026d963...
413 Request Entity Too Large
video.mp4: too large
files on disk: 1

Details worth noting:

Validating the content

The file name extension and the part's Content-Type header are both chosen by the client and prove nothing. To check what a file really is, look at its content. http.DetectContentType sniffs the first 512 bytes using the algorithm browsers use:

package main

import (
	"bytes"
	"fmt"
	"io"
	"mime/multipart"
	"net/http"
	"net/http/httptest"
	"net/textproto"
	"os"
)

var allowedTypes = map[string]string{
	"image/png":       ".png",
	"image/jpeg":      ".jpg",
	"application/pdf": ".pdf",
}

func handleUpload(w http.ResponseWriter, r *http.Request) {
	r.Body = http.MaxBytesReader(w, r.Body, 5<<20)
	file, header, err := r.FormFile("file")
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	defer file.Close()

	// sniff the real type from the first 512 bytes
	buf := make([]byte, 512)
	n, err := io.ReadFull(file, buf)
	if err != nil && err != io.ErrUnexpectedEOF {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	detected := http.DetectContentType(buf[:n])
	ext, ok := allowedTypes[detected]
	if !ok {
		msg := fmt.Sprintf("%s: type %s not allowed (client said %s)",
			header.Filename, detected, header.Header.Get("Content-Type"))
		http.Error(w, msg, http.StatusUnsupportedMediaType)
		return
	}

	// multipart.File is an io.Seeker: rewind before saving the whole file
	if _, err := file.Seek(0, io.SeekStart); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	// ... save file under a server-generated name with extension ext ...
	fmt.Fprintf(w, "%s: ok, %s, will be saved with extension %s\n",
		header.Filename, detected, ext)
}

func upload(url, name, contentType string, data []byte) {
	var body bytes.Buffer
	mw := multipart.NewWriter(&body)
	// CreatePart lets us set the part's Content-Type header
	h := make(textproto.MIMEHeader)
	h.Set("Content-Disposition", multipart.FileContentDisposition("file", name))
	h.Set("Content-Type", contentType)
	pw, _ := mw.CreatePart(h)
	pw.Write(data)
	mw.Close()

	resp, err := http.Post(url, mw.FormDataContentType(), &body)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	fmt.Print(resp.StatusCode, " ")
	io.Copy(os.Stdout, resp.Body)
}

func main() {
	srv := httptest.NewServer(http.HandlerFunc(handleUpload))
	defer srv.Close()

	png := []byte("\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR")
	pdf := []byte("%PDF-1.7\n1 0 obj\n")
	html := []byte("<html><script>alert(1)</script></html>")

	upload(srv.URL, "cat.png", "image/png", png)
	upload(srv.URL, "report.pdf", "application/pdf", pdf)
	upload(srv.URL, "innocent.png", "image/png", html)
}
200 cat.png: ok, image/png, will be saved with extension .png
200 report.pdf: ok, application/pdf, will be saved with extension .pdf
415 innocent.png: type text/html; charset=utf-8 not allowed (client said image/png)

The client claimed innocent.png was a PNG, but it's an HTML page with a script. If you saved it as uploaded and later served it from your domain, a browser might run the script (stored XSS).

Rules for content checks:

Safe file names

part.FileName() and FileHeader.Filename already pass the name through filepath.Base, so ../../etc/passwd becomes passwd. But filepath.Base is platform dependent: on Linux it doesn't treat \ as a separator, so a Windows-style path survives. The name can also contain characters that are invalid on some file systems or confusing in HTML.

The safest approach is to not use the client's name for storage at all: generate a name (a random string or a content hash, as above) and keep the original name in a database for display. If you do want to keep a readable name, clean it:

package main

import (
	"fmt"
	"strings"
	"unicode"
)

// safeName turns a client-supplied file name into something that's
// safe to show and to use as a single path component.
func safeName(name string) string {
	// browsers on Windows used to send full paths like C:\Users\me\a.txt;
	// strip directories using both separators, regardless of server OS
	if i := strings.LastIndexAny(name, `/\`); i >= 0 {
		name = name[i+1:]
	}
	name = strings.Map(func(r rune) rune {
		switch {
		case unicode.IsLetter(r), unicode.IsDigit(r), r == '.', r == '-', r == '_':
			return r
		case r == ' ':
			return '_'
		}
		return -1 // drop everything else
	}, name)
	name = strings.TrimLeft(name, ".") // no hidden files, no ".."
	if name == "" {
		name = "unnamed"
	}
	return name
}

func main() {
	names := []string{
		"report.pdf",
		"../../etc/passwd",
		`C:\Users\me\My Photo.jpg`,
		"..",
		".htaccess",
		"inv<o>ice?.pdf",
		"zdjęcie łódź.png",
		"a\x00b.txt",
		"",
	}
	for _, n := range names {
		fmt.Printf("%-28q -> %q\n", n, safeName(n))
	}
}
"report.pdf"                 -> "report.pdf"
"../../etc/passwd"           -> "passwd"
"C:\\Users\\me\\My Photo.jpg" -> "My_Photo.jpg"
".."                         -> "unnamed"
".htaccess"                  -> "htaccess"
"inv<o>ice?.pdf"             -> "invoice.pdf"
"zdjęcie łódź.png"           -> "zdjęcie_łódź.png"
"a\x00b.txt"                 -> "ab.txt"
""                           -> "unnamed"

Even with a clean name, two users can upload report.pdf. os.Root.Create would silently overwrite the first one, so open with root.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644) and pick another name if it fails with fs.ErrExist. Also limit the length; most file systems allow at most 255 bytes per name.

Uploading from a Go client without buffering

The client examples so far build the whole body in a bytes.Buffer, which is fine for small files. For a large file, connect multipart.Writer to the request body with io.Pipe. One goroutine writes the multipart data into the pipe while the HTTP client reads from it and sends it:

package main

import (
	"fmt"
	"io"
	"log"
	"mime/multipart"
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"
)

// uploadFile streams a file to url without loading it into memory.
func uploadFile(url, field, path string) (*http.Response, error) {
	f, err := os.Open(path)
	if err != nil {
		return nil, err
	}

	pr, pw := io.Pipe()
	mw := multipart.NewWriter(pw)

	// the writer side runs in its own goroutine; the HTTP client
	// reads from pr as it sends the request
	go func() {
		// the goroutine owns f: Do can return before the body is fully
		// written, e.g. when the server rejects the upload early
		defer f.Close()
		fw, err := mw.CreateFormFile(field, filepath.Base(path))
		if err == nil {
			_, err = io.Copy(fw, f)
		}
		if err == nil {
			err = mw.Close()
		}
		// CloseWithError(nil) is the same as Close
		pw.CloseWithError(err)
	}()

	req, err := http.NewRequest("POST", url, pr)
	if err != nil {
		return nil, err
	}
	req.Header.Set("Content-Type", mw.FormDataContentType())
	return http.DefaultClient.Do(req)
}

func main() {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		mr, err := r.MultipartReader()
		if err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
		part, err := mr.NextPart()
		if err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
		n, err := io.Copy(io.Discard, part)
		if err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
		fmt.Fprintf(w, "received %s: %d bytes (Content-Length %d, %v)\n",
			part.FileName(), n, r.ContentLength, r.TransferEncoding)
	}))
	defer srv.Close()

	// create a 50 MB file
	path := filepath.Join(os.TempDir(), "big.bin")
	f, _ := os.Create(path)
	f.Truncate(50 << 20)
	f.Close()
	defer os.Remove(path)

	resp, err := uploadFile(srv.URL, "file", path)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()
	io.Copy(os.Stdout, resp.Body)
}
received big.bin: 52428800 bytes (Content-Length -1, [chunked])

Memory use stays small no matter how big the file is. Points to watch:

Testing upload handlers

You don't need a running server to test a handler. Build the request body with multipart.Writer, create a request with httptest.NewRequest and record the response with httptest.NewRecorder:

package upload

import (
	"fmt"
	"io"
	"net/http"
)

func HandleUpload(w http.ResponseWriter, r *http.Request) {
	r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
	file, header, err := r.FormFile("file")
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	defer file.Close()
	n, err := io.Copy(io.Discard, file)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	fmt.Fprintf(w, "%s %d", header.Filename, n)
}
package upload

import (
	"bytes"
	"mime/multipart"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
)

// newUploadRequest builds a multipart POST request with one file.
func newUploadRequest(t *testing.T, field, name string, content []byte) *http.Request {
	t.Helper()
	var body bytes.Buffer
	mw := multipart.NewWriter(&body)
	fw, err := mw.CreateFormFile(field, name)
	if err != nil {
		t.Fatal(err)
	}
	fw.Write(content)
	if err := mw.Close(); err != nil {
		t.Fatal(err)
	}
	req := httptest.NewRequest("POST", "/upload", &body)
	req.Header.Set("Content-Type", mw.FormDataContentType())
	return req
}

func TestHandleUpload(t *testing.T) {
	tests := []struct {
		name       string
		field      string
		size       int
		wantStatus int
		wantBody   string
	}{
		{"ok", "file", 1000, http.StatusOK, "a.txt 1000"},
		{"wrong field", "document", 10, http.StatusBadRequest, "no such file"},
		{"too large", "file", 2 << 20, http.StatusBadRequest, "too large"},
	}
	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			req := newUploadRequest(t, tc.field, "a.txt", make([]byte, tc.size))
			rec := httptest.NewRecorder()
			HandleUpload(rec, req)

			if rec.Code != tc.wantStatus {
				t.Errorf("status = %d, want %d", rec.Code, tc.wantStatus)
			}
			if got := rec.Body.String(); !strings.Contains(got, tc.wantBody) {
				t.Errorf("body = %q, want it to contain %q", got, tc.wantBody)
			}
		})
	}
}
$ go test -v
=== RUN   TestHandleUpload
=== RUN   TestHandleUpload/ok
=== RUN   TestHandleUpload/wrong_field
=== RUN   TestHandleUpload/too_large
--- PASS: TestHandleUpload (0.00s)
    --- PASS: TestHandleUpload/ok (0.00s)
    --- PASS: TestHandleUpload/wrong_field (0.00s)
    --- PASS: TestHandleUpload/too_large (0.00s)
PASS

The test cases use table-driven tests to cover the success path, a missing file and an oversized body. Forgetting to set the Content-Type header with the boundary is the most common reason such tests fail with request Content-Type isn't multipart/form-data.

Common mistakes

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents