-
Notifications
You must be signed in to change notification settings - Fork 5
Controller Functions
This page describes all the callback functions of a controller.
All Cowmachine controller functions are of the signature:
f(Request) -> {Result, Request}
The Request
argument and return value is one of:
- A map, then it is assumed to be a
cowboy_req:req()
request map - A tuple, then the 2nd field must be the
cowboy_req:req()
request map
Example of such a tuple definition:
-record(context, { req :: cowboy_req:req(), ... }.
After the req
you can add any fields for your application.
The Request
is passed between the various functions of your controller.
Cowmachine can modify the cowboy request in your request state.
The rest of this document is about the effects produced by different
values in the Result
term from different controller functions.
In the function list below if a function has a result type including
halt()
, it also has the option of returning either of the two
following special values for Result
:
Result | Effect |
---|---|
{error, Err::term()} |
Immediately end processing of this request, returning a
500 Internal Server Error response. The response body
will contain the Err term. |
{halt, 200..599} |
Immediately end processing of this request, returning response
code Code . It is the responsibility of the controller to
ensure that all necessary response header and body elements are filled
in Request in order to make that response code
valid. |
There are over 30 controller functions you can define, but any of them
can be omitted as they have reasonable defaults. Each function is
described below, showing the default and allowed values that may be in
the Result
term. The default will be used if a controller does not
export the function.
Any function which has no description is optional and the effect of its return value should be evident from examining the Diagram. The following types are used in the descriptions below:
%% The Request data record
-type request() :: cowboy_req:req() | tuple().
%% Used in callbacks that can halt or error. See "Halting Controllers" above.
-type halt() :: {error, term()} | {halt, 200..599}.
%% The body given by streaming responses.
-type streambody() :: {iodata(), fun(() -> streambody()) | done}.
The below are all of the supported predefined controller functions. In
addition to whichever of these a controller wishes to use, it also must
export all of the functions named in the return values of the
content_types_provided
and content_types_accepted
functions, with
behavior as described in the last two controller functions below.
-spec service_available(request()) -> {boolean() | halt(), request()}.
This is the first function called, if needed you can perform any initialization here.
Returning non-true values will result in 503 Service Unavailable
.
Default : true
-spec resource_exists(request()) -> {boolean() | halt(), request()}.
Returning non-true values will result in 404 Not Found
.
Default : true
-spec is_authorized(request()) -> {true | binary() | halt(), request()}.
If this returns anything other than true
, the response will be 401 Unauthorized
. The binary()
return value will be used as the value
in the WWW-Authenticate
header, for example Basic realm="Foobar"
.
Default : true
-spec forbidden(request()) -> {boolean() | halt(), request()}.
Returning true will result in 403 Forbidden
.
Default : false
-spec allow_missing_post(request()) -> {boolean() | halt(), request()}.
If the controller accepts POST requests to nonexistent resources, then
this should return true
.
Default : false
-spec malformed_request(request()) -> {boolean() | halt(), request()}.
Returning true will result in 400 Bad Request
.
Default : false
-spec uri_too_long(request()) -> {boolean() | halt(), request()}.
Returning true will result in 414 Request-URI Too Long
.
Default : false
-spec known_content_type(request()) -> {boolean() | halt(), request()}.
Returning false will result in 415 Unsupported Media Type
.
Default : true
-spec valid_content_headers(request()) -> {boolean() | halt(), request()}.
Returning false will result in 501 Not Implemented
.
Default : true
-spec valid_entity_length(request()) -> {boolean() | halt(), request()}.
Returning false will result in 413 Request Entity Too Large
.
Default : false
-spec options(request()) -> {[{binary(), binary()}], request()}.
If the OPTIONS method is supported and is used, the return value of this function is expected to be a list of pairs representing header names and values that should appear in the response.
-spec allowed_methods(request()) -> {[Method], request()}
when Method :: <<"GET">> | <<"HEAD">> | <<"PUT">> | <<"POST">> |
<<"DELETE">> | <<"TRACE">> | <<"CONNECT">> |
<<"OPTIONS">>.
If a Method
not in this list is requested, then a 405 Method Not Allowed
will be sent. Note that these are all-caps and are atoms.
(single-quoted)
Default : [ <<"GET">>, <<"HEAD">> ]
-spec delete_resource(request()) -> {boolean() | halt(), request()}.
This is called when a DELETE request should be enacted, and should
return true
if the deletion succeeded.
-spec delete_resource(request()) -> {boolean() | halt(), request()}.
This is only called after a successful delete_resource
call, and
should return false
if the deletion was accepted but cannot yet be
guaranteed to have finished.
-spec post_is_create(request()) -> {boolean(), request()}.
If POST requests should be treated as a request to put content into a
(potentially new) resource as opposed to being a generic submission
for processing, then this function should return true
. If it does
return true
, then create_path
will be called and the rest of the
request will be treated much like a PUT to the Path
entry returned
by that call.
Default : false
-spec create_path(request()) -> {Path::binary(), request()}.
This will be called on a POST request if post_is_create
returns
true
. It is an error for this function not to produce a Path
if
post_is_create
returns true
. The Path
returned should be a valid
URI part following the dispatcher prefix. That Path
will replace the
previous one in the return value of cowmachine_req:disp_path(Request)
for all
subsequent controller function calls in the course of this request.
-spec process_post(request()) -> {boolean() | halt(), request()}.
If post_is_create
returns false
, then this will be called to
process any POST requests. If it succeeds, it should return true
.
-spec content_types_provided(request()) -> {[{MediaType::binary(), Handler::atom()}], request()}.
This should return a list of pairs where each pair is of the form
{MediaType, Handler}
where MediaType
is a string of content-type
format and the Handler
is an atom naming the function which can
provide a resource representation in that media type. Content
negotiation is driven by this return value. For example, if a client
request includes an Accept
header with a value that does not appear
as a first element in any of the return tuples, then a 406 Not Acceptable
will be sent.
Default : [{ <<"text/html">>, to_html}]
-spec content_types_accepted(request()) -> {[{MediaType::binary(), Handler::atom()}], request()}.
This is used similarly to content_types_provided
, except that it is
for incoming resource representations -- for example, PUT requests.
Handler functions usually want to use cowmachine_req:req_body(Request)
to
access the incoming request body.
Default : []
-spec charsets_provided(request()) -> {no_charset | [ Charset::binary() ], request()}
If this is anything other than the atom no_charset
, then it must be a
list of binaries representing character sets.
The controller is responsible for returning the body in the selected character set.
Example: [ <<"iso-8859-1">>, <<"utf-8">> ]
Default : no_charset
-spec content_encodings_provided(request()) -> {[ Encoding::binary() ], request()}
This must be a list of strings naming valid content encodings. The controller is responsible for the encoding of the returned body using the selected content encoding.
Example:
[ <<"identity">>, <<"gzip">> ]
Default : [ <<"identity">> ]
-spec transfer_encodings_provided(request()) -> {[{Encoding::binary(), Encoder}], request()}
when Encoder :: fun((iodata()) -> iodata()).
How the content is transferred, this is handy for auto-gzip of GET-only resources.
identity
and chunked
are always available to HTTP/1.1 clients.
This must be a list of pairs where in each pair Encoding
is a string
naming a valid transfer encoding and Encoder
is a callable function
in the controller which will be called on the produced body in a GET and
ensure that it is so encoded. One possible setting is to have the
function check on method, and on GET requests return:
[{<<"identity">>, fun(X) -> X end},
{<<"gzip">>, fun(X) -> zlib:gzip(X) end}]
as this is all that is needed to support gzip transfer encoding.
Default : [ {<<"identity">>, fun(X) -> X end} ]
-spec variances(request()) -> {[HeaderName::binary()], request()}.
If this function is implemented, it should return a list of strings
with header names that should be included in a given response's Vary
header. The standard conneg headers (Accept
, Accept-Encoding
,
Accept-Charset
, Accept-Language
) do not need to be specified here
as Webmachine will add the correct elements of those automatically
depending on controller behavior.
Default : []
-spec is_conflict(request()) -> {boolean(), request()}.
If this returns true
, the client will receive a 409 Conflict
.
Default : false
-spec multiple_choices(request()) -> {boolean() | halt(), request()}.
If this returns true
, then it is assumed that multiple
representations of the response are possible and a single one cannot
be automatically chosen, so a 300 Multiple Choices
will be sent
instead of a 200 OK
.
Default : false
-spec previously_existed(request()) -> {boolean() | halt(), request()}.
If this returns true
, the moved_permanently
and
moved_temporarily
callbacks will be invoked to determine whether the
response should be 301 Moved Permanently
, 307 Temporary Redirect
,
or 410 Gone
.
Default : false
-spec moved_permanently(request()) -> {{true, URI::binary()} | false | halt(), request()}.
If this returns {true, URI}
, the client will receive a 301 Moved Permanently
with URI
in the Location
header.
Default : false
-spec moved_temporarily(request()) -> {{true, URI::binary()} | false | halt(), request()}.
If this returns {true, URI}
, the client will receive a 307 Temporary Redirect
with URI
in the Location
header.
Default : false
-spec last_modified(request()) -> {calendar:datetime() | undefined, request()}.
If this returns a datetime()
, it will be used for the
Last-Modified
header and for comparison in conditional requests.
Default : undefined
-spec generate_etag(request()) -> {binary() | undefined, request()}.
If this returns a binary()
, it will be used for the ETag
header
and for comparison in conditional requests.
Default : undefined
-spec finish_request(request()) -> {Result::any(), request()}.
This function, if exported, is called just before the final response
is constructed and sent. The Result
is ignored, so any effect of
this function must be by returning a modified ReqData
.
-spec Handler(request()) -> {iodata() | {stream, streambody()} | halt(), request()}.
This function must be named as a Handler
by
content_types_provided
. The Body
should be either an iodata()
or
{stream,streambody()}
.
-spec Handler(request()) -> {true | halt(), request()}.
This function must be named as a Handler
by content_types_accepted
and will be called when the request is PUT or when the request is POST
and post_is_create
returns true
.