apitest
Requests

Forms and file uploads

Send URL encoded forms, multipart forms and file uploads.

URL encoded forms

FormData sends an application/x-www-form-urlencoded body and sets the content type. It takes one or more values for a key, and can be called repeatedly:

apitest.Handler(handler).
	Post("/signup").
	FormData("name", "jan").
	FormData("colors", "red", "blue").
	Expect(t).
	Status(http.StatusOK).
	End()

The body in this example is colors=red&colors=blue&name=jan.

Multipart forms

MultipartFormData adds fields to a multipart/form-data body, and MultipartFile adds files. The content type, including the boundary, is set for you.

apitest.Handler(handler).
	Post("/upload").
	MultipartFormData("description", "monthly reports").
	MultipartFile("file", "testdata/users.csv", "testdata/summary.txt").
	Expect(t).
	Status(http.StatusOK).
	End()

MultipartFile takes a field name and one or more file paths. Each file is sent with its base name as the file name, so the handler sees users.csv and summary.txt.

Choose one form style

FormData and the multipart builders cannot be combined in one request. Doing so fails the test.

Files from memory

Files are read from the operating system by default. UseFS replaces the file system with any fs.FS, such as an in-memory fstest.MapFS or an embed.FS:

files := fstest.MapFS{
	"audio.wav": &fstest.MapFile{Data: []byte{19, 2, 123, 12, 35, 1}},
}

apitest.Handler(handler).
	UseFS(files).
	Post("/upload").
	MultipartFile("file", "audio.wav").
	Expect(t).
	Status(http.StatusOK).
	End()

This keeps binary fixtures out of the repository and makes it easy to generate uploads in the test.

On this page