Action

Action

If the Loader interface is for fetching application data, the Action interface is for mutating it. A Controller that implements the Action interface is able to handle incoming HTTP POST, PATCH, PUT and DELETE requests, as well as form submissions from the browser.

In Practice

A classic example of an Action implementation is a signup form. The following example uses the built-in form decoder.

How to Respond

Unlike the Loader interface, you have access to the http.ResponseWriter within an Action and can write directly to the response body. But what exactly should you write?

By default, if no error is returned from Action, a 200 OK response is written.

Reloads

Errors can happen during a form submission, but it doesn't mean that you can't handle it gracefully. For example, if a user enters the wrong password on a login form, you can simply tell torque to re-render the form with additional error context.

Calling ReloadWithError re-executes the Loader -> Renderer flow and writes the result to the response body of the Action request. During a form submission from the browser, this effectively re-renders the page.

Redirects

You can use the standard http.Redirect function to redirect a request from an Action method.

Redirect replies to the request with a redirect to url, which may be a path relative to the request path. Note that some browsers only respond to redirects when the HTTP status code is either 302 or 307.

If the Content-Type header has not been set, Redirect sets it to "text/html; charset=utf-8" and writes a small HTML body. Setting the Content-Type header to any value, including nil, disables that behavior.

Cookies

You can use the http.SetCookie method to set a response's Set-Cookie headers. The provided cookie must have a valid Name. Invalid cookies may be silently dropped.

Headers

Errors

Any errors returned from an Action method can be caught by an ErrorBoundary on that route. For detailed information, see boundaries.