Body and JSON
Send a raw body, a formatted body, JSON from a value, or a body read from a file.
Raw body
Body sends a string as the request body. Set the content type separately:
apitest.Handler(handler).
Post("/message").
Body("<p>hello</p>").
ContentType("text/html").
Expect(t).
Status(http.StatusOK).
End()Bodyf formats the body with fmt.Sprintf:
apitest.Handler(formatted).
Post("/user").
Bodyf(`{"id": "%s"}`, id).
Expect(t).
Status(http.StatusOK).
End()JSON
JSON sets the body and the Content-Type: application/json header. It accepts a string or a []byte, which are sent unchanged:
apitest.Handler(handler).
Post("/user").
JSON(`{"name": "jan"}`).
Expect(t).
Status(http.StatusOK).
End()Any other value is marshalled with encoding/json, so structs, maps and slices all work:
type CreateUser struct {
Name string `json:"name"`
Age int `json:"age"`
}
apitest.Handler(handler).
Post("/user").
JSON(CreateUser{Name: "jan", Age: 32}).
Expect(t).
Status(http.StatusOK).
End()
apitest.Handler(handler).
Post("/user").
JSON(map[string]any{"name": "jan", "age": 32}).
Expect(t).
Status(http.StatusOK).
End()If marshalling fails, the test fails when Expect is called.
Bodies from files
Large or shared payloads are easier to keep in files. JSONFromFile reads the body and sets the JSON content type, and BodyFromFile reads the body only:
apitest.Handler(handler).
Post("/user").
JSONFromFile("testdata/create-user.json").
Expect(t).
Status(http.StatusOK).
End()apitest.Handler(raw).
Post("/import").
BodyFromFile("testdata/users.csv").
ContentType("text/csv").
Expect(t).
Status(http.StatusOK).
End()Paths are relative to the package directory, which is the working directory when go test runs. A testdata directory is the usual place for these files, because the Go tool ignores it when building.
Other content types
For XML, HTML, CSV, protobuf or anything else, combine Body with ContentType or Header("Content-Type", ...). For form and multipart bodies, use the dedicated form builders.