Skip to content
Download

Results

Controller actions return results that determine the HTTP response sent to the client.

Mach represents an action result using mach::Reply<T>, where T is the type of the response body.

Controllers derive from mach::ControllerBase, which provides helpers for creating common HTTP responses.

For example:

mach::Reply<std::string> getUser() {
return ok(std::string{"Alice"});
}

ok() creates a 200 OK reply containing the provided response body.

The action’s Reply<T> type must match the type of the body it returns:

mach::Reply<int> getUserId() {
return ok(42);
}

For replies without a response body, use mach::Reply<>:

mach::Reply<> deleteUser() {
return noContent();
}

ControllerBase provides helpers for common HTTP responses, allowing actions to express their result directly.

For example:

mach::Reply<> createUser() {
return created();
}
mach::Reply<> deleteUser() {
return noContent();
}
mach::Reply<> rejectRequest() {
return badRequest();
}

These helpers create replies with the corresponding HTTP status code.

Many result helpers can also return a response body. When a body is returned, the action’s Reply<T> type must use the matching type.

A result helper can include data in the response:

struct User {
int id;
std::string name;
};
MACH_DEFINE_JSON(User, id, name)
mach::Reply<User> getUser() {
User user{
.id = 42,
.name = "Alice"
};
return ok(user);
}

Here, ok() creates a Reply<User>. Mach serializes the response body when producing the HTTP response.

Types used as JSON response bodies can be mapped using MACH_DEFINE_JSON.

Choose a result that represents the outcome of the request.

For example, an action that successfully deletes a resource might return:

return noContent();

while an action that cannot find the requested resource might return:

return notFound();

Using the appropriate result communicates the outcome through the HTTP status code and keeps controller actions concise.

mach::Reply is strongly typed.

An action that returns:

mach::Reply<User>

must return a reply containing a User. An action with no response body can return:

mach::Reply<>

For the complete set of available response helpers and their overloads, see the ControllerBase API reference.


Next, you’ll learn how to provide dependencies to controllers using Mach’s dependency injection system.