0
Fork 0
mirror of https://github.com/ninenines/cowboy.git synced 2025-07-15 20:50:24 +00:00

Convert the documentation to Asciidoc

A few small revisions were made, and Erlang.mk has been updated.
This commit is contained in:
Loïc Hoguin 2016-01-14 13:35:25 +01:00
parent b7d666cfc7
commit 4023e7f4e4
55 changed files with 5701 additions and 1889 deletions

View file

@ -0,0 +1,98 @@
= cowboy(3)
== Name
cowboy - HTTP server
== Description
The `cowboy` module provides convenience functions for
manipulating Ranch listeners.
== Types
=== fields() = [Field]
[source,erlang]
----
Field = atom()
| {atom(), cowboy_constraints:constraint() | [cowboy_constraints:constraint()]}
| {atom(), cowboy_constraints:constraint() | [cowboy_constraints:constraint()], any()}]
----
Fields for match operations. Constraint(s) and default value are optional.
=== http_headers() = [{binary(), iodata()}]
HTTP headers as a list of key/values.
=== http_status() = non_neg_integer() | binary()
HTTP status.
A binary status can be used to set a custom message.
=== http_version() = \'HTTP/1.1' | \'HTTP/1.0'
HTTP version.
=== `onresponse_fun() = fun((http_status(), http_headers(), iodata(), cowboy_req:req()) -> cowboy_req:req())`
Fun called immediately before sending the response.
It can perform any operation on the Req object, including
reading the request body or replying. If a reply is sent, it
overrides the reply initially sent. The callback will not be
called again for the new reply.
== Exports
=== start_http(Ref, NbAcceptors, TransOpts, ProtoOpts) -> {ok, pid()}
Ref = ranch:ref():: Listener name.
NbAcceptors = non_neg_integer():: Number of acceptor processes.
TransOpts = ranch_tcp:opts():: TCP transport options.
ProtoOpts = cowboy_protocol:opts():: HTTP protocol options.
Start listening for HTTP connections. Returns the pid for this
listener's supervisor.
=== start_https(Ref, NbAcceptors, TransOpts, ProtoOpts) -> {ok, pid()}
Ref = ranch:ref():: Listener name.
NbAcceptors = non_neg_integer():: Number of acceptor processes.
TransOpts = ranch_ssl:opts():: SSL transport options.
ProtoOpts = cowboy_protocol:opts():: HTTP protocol options.
Start listening for HTTPS connections. Returns the pid for this
listener's supervisor.
=== start_spdy(Ref, NbAcceptors, TransOpts, ProtoOpts) -> {ok, pid()}
Ref = ranch:ref():: Listener name.
NbAcceptors = non_neg_integer():: Number of acceptor processes.
TransOpts = ranch_ssl:opts():: SSL transport options.
ProtoOpts = cowboy_spdy:opts():: SPDY protocol options.
Start listening for SPDY connections. Returns the pid for this
listener's supervisor.
=== stop_listener(Ref) -> ok | {error, not_found}
Ref = ranch:ref():: Listener name.
Stop a previously started listener.
=== set_env(Ref, Name, Value) -> ok
Ref = ranch:ref():: Listener name.
Name = atom():: Name of environment value.
Value = any():: Environment value.
Set or update an environment value for an already running listener.
This will take effect on all subsequent connections.
== See also
The http://ninenines.eu/docs/en/ranch/HEAD/guide[Ranch guide]
provides detailed information about how listeners work.

View file

@ -1,98 +0,0 @@
::: cowboy
The `cowboy` module provides convenience functions for
manipulating Ranch listeners.
:: Types
: fields() = [atom()
| {atom(), cowboy_constraints:constraint() | [cowboy_constraints:constraint()]}
| {atom(), cowboy_constraints:constraint() | [cowboy_constraints:constraint()], any()}]
Fields for match operations. Constraint(s) and default value are optional.
: http_headers() = [{binary(), iodata()}]
HTTP headers as a list of key/values.
: http_status() = non_neg_integer() | binary()
HTTP status.
A binary status can be used to set a custom message.
: http_version() = 'HTTP/1.1' | 'HTTP/1.0'
HTTP version.
: onresponse_fun() = fun((http_status(), http_headers(),
iodata(), cowboy_req:req()) -> cowboy_req:req())
Fun called immediately before sending the response.
It can perform any operation on the Req object, including
reading the request body or replying. If a reply is sent, it
overrides the reply initially sent. The callback will not be
called again for the new reply.
:: Exports
: start_http(Ref, NbAcceptors, TransOpts, ProtoOpts) -> {ok, pid()}
Types:
* Ref = ranch:ref()
* NbAcceptors = non_neg_integer()
* TransOpts = ranch_tcp:opts()
* ProtoOpts = cowboy_protocol:opts()
Start listening for HTTP connections. Returns the pid for this
listener's supervisor.
: start_https(Ref, NbAcceptors, TransOpts, ProtoOpts) -> {ok, pid()}
Types:
* Ref = ranch:ref()
* NbAcceptors = non_neg_integer()
* TransOpts = ranch_ssl:opts()
* ProtoOpts = cowboy_protocol:opts()
Start listening for HTTPS connections. Returns the pid for this
listener's supervisor.
: start_spdy(Ref, NbAcceptors, TransOpts, ProtoOpts) -> {ok, pid()}
Types:
* Ref = ranch:ref()
* NbAcceptors = non_neg_integer()
* TransOpts = ranch_ssl:opts()
* ProtoOpts = cowboy_spdy:opts()
Start listening for SPDY connections. Returns the pid for this
listener's supervisor.
: stop_listener(Ref) -> ok | {error, not_found}
Types:
* Ref = ranch:ref()
Stop a previously started listener.
: set_env(Ref, Name, Value) -> ok
Types:
* Ref = ranch:ref()
* Name = atom()
* Value = any()
Set or update an environment value for an already running listener.
This will take effect on all subsequent connections.
:: See also
The ^"Ranch guide^http://ninenines.eu/docs/en/ranch/HEAD/guide
provides detailed information about how listeners work.

View file

@ -1,8 +1,10 @@
::: The Cowboy Application
= cowboy(7)
Small, fast, modular HTTP server.
== Name
:: Dependencies
cowboy - Small, fast, modular HTTP server.
== Dependencies
The `cowboy` application uses the Erlang applications `ranch`
for listening and accepting TCP connections, `crypto` for
@ -17,7 +19,7 @@ The `cowboy` application also uses the Erlang applications
`asn1`, `public_key` and `ssl` when listening for HTTPS connections.
These are started automatically if they weren't before.
:: Environment
== Environment
The `cowboy` application does not define any application
environment configuration parameters.

View file

@ -1,4 +1,10 @@
::: cowboy_handler
= cowboy_handler(3)
== Name
cowboy_handler - handler middleware and behaviour
== Description
The `cowboy_handler` middleware executes the handler passed
through the environment values `handler` and `handler_opts`,
@ -8,51 +14,42 @@ handled and received a response.
Environment input:
* handler = module()
* handler_opts = any()
handler = module():: Handler to be executed.
handler_opts = any():: Options to be passed to the handler.
Environment output:
* result = ok
result = ok:: Result of the request.
This module also defines the `cowboy_handler` behaviour that
defines the basic interface for handlers. All Cowboy handlers
implement at least the `init/2` callback, and may implement
the `terminate/3` callback optionally.
:: Terminate reasons
== Terminate reasons
The following values may be received as the terminate reason
in the optional `terminate/3` callback. Different handler types
may define additional terminate reasons.
: normal
normal::
The connection was closed normally.
The connection was closed normally.
{crash, Class, Reason}::
A crash occurred in the handler. `Class` and `Reason` can be
used to obtain more information about the crash. The function
`erlang:get_stacktrace/0` can also be called to obtain the
stacktrace of the process when the crash occurred.
: {crash, Class, Reason}
== Callbacks
A crash occurred in the handler. `Class` and `Reason` can be
used to obtain more information about the crash. The function
`erlang:get_stacktrace/0` can also be called to obtain the
stacktrace of the process when the crash occurred.
=== init(Req, Opts) -> {ok, Req, State} | {Module, Req, State} | {Module, Req, State, hibernate | Timeout} | {Module, Req, State, Timeout, hibernate}
:: Callbacks
: init(Req, Opts)
-> {ok, Req, State}
| {Module, Req, State}
| {Module, Req, State, hibernate}
| {Module, Req, State, Timeout}
| {Module, Req, State, Timeout, hibernate}
Types:
* Req = cowboy_req:req()
* Opts = any()
* State = any()
* Module = module()
* Timeout = timeout()
Req = cowboy_req:req():: The Req object.
Opts = any():: Handler options.
State = any():: Handler state.
Module = module():: Module of the sub-protocol to use.
Timeout = timeout():: Timeout passed to the sub-protocol, when applicable.
Process the request.
@ -68,13 +65,11 @@ A crash in this callback will result in `terminate/3` being
called if it is defined, with the `State` argument set to
the value of `Opts` originally given to the `init/2` callback.
: terminate(Reason, Req, State) -> ok
=== terminate(Reason, Req, State) -> ok
Types:
* Reason = any()
* Req = cowboy_req:req()
* State = any()
Reason = any():: Reason for termination.
Req = cowboy_req:req():: The Req object.
State = any():: Handler state.
Perform any necessary cleanup of the state.
@ -88,16 +83,14 @@ A crash in this callback or an invalid return value will
result in the closing of the connection and the termination
of the process.
:: Exports
== Exports
: terminate(Reason, Req, State, Handler) -> ok
=== terminate(Reason, Req, State, Handler) -> ok
Types:
* Reason = any()
* Req = cowboy_req:req()
* State = any()
* Handler = module()
Reason = any():: Reason for termination.
Req = cowboy_req:req():: The Req object.
State = any():: Handler state.
Handler = module():: Handler module.
Call the optional `terminate/3` callback if it exists.

View file

@ -0,0 +1,86 @@
= cowboy_loop(3)
== Name
cowboy_loop - loop handlers
== Description
The `cowboy_loop` module implements a handler interface for
long running HTTP connections. It is the recommended interface
for long polling and server-sent events, amongst others.
This module is a sub protocol that defines three callbacks to
be implemented by handlers. The `init/2` and `terminate/3`
callbacks are common to all handler types and are documented
in the manual for the link:cowboy_handler.asciidoc[cowboy_handler] module.
The `info/3` callback is specific to loop handlers and will be
called as many times as necessary until a reply is sent.
It is highly recommended to return a timeout value from the
`init/2` callback to ensure that the process is terminated
when no data has been received during that timespan. The
default timeout is `infinity`, which should only be used if
you have alternate means of ending inactive connections.
== Terminate reasons
The following values may be received as the terminate reason
in the optional `terminate/3` callback.
normal::
The connection was closed normally before switching to the
loop sub protocol. This typically happens if an `ok` tuple is
returned from the `init/2` callback.
stop::
The handler requested to close the connection by returning
a `stop` tuple.
timeout::
The connection has been closed due to inactivity. The timeout
value can be configured from `init/2`. The response sent when
this happens is a `204 No Content`.
{crash, Class, Reason}::
A crash occurred in the handler. `Class` and `Reason` can be
used to obtain more information about the crash. The function
`erlang:get_stacktrace/0` can also be called to obtain the
stacktrace of the process when the crash occurred.
{error, overflow}::
The connection is being closed and the process terminated
because the buffer Cowboy uses to keep data sent by the
client has reached its maximum. The buffer size can be
configured through the environment value `loop_max_buffer`
and defaults to 5000 bytes.
+
If the long running request comes with a body it is recommended
to process this body before switching to the loop sub protocol.
{error, closed}::
The socket has been closed brutally without a close frame being
received first.
{error, Reason}::
A socket error ocurred.
== Callbacks
=== info(Info, Req, State) -> {ok, Req, State} | {ok, Req, State, hibernate} | {stop, Req, State}
Info = any():: Message received by the process.
Req = cowboy_req:req():: The Req object.
State = any():: Handler state.
Handle the Erlang message received.
This function will be called every time an Erlang message
has been received. The message can be any Erlang term.
The `stop` return value can be used to stop the receive loop,
typically because a response has been sent.
The `hibernate` option will hibernate the process until
it receives another message.

View file

@ -1,92 +0,0 @@
::: cowboy_loop
The `cowboy_loop` module implements a handler interface for
long running HTTP connections. It is the recommended interface
for long polling and server-sent events, amongst others.
This module is a sub protocol that defines three callbacks to
be implemented by handlers. The `init/2` and `terminate/3`
callbacks are common to all handler types and are documented
in the manual for the ^cowboy_handler module.
The `info/3` callback is specific to loop handlers and will be
called as many times as necessary until a reply is sent.
It is highly recommended to return a timeout value from the
`init/2` callback to ensure that the process is terminated
when no data has been received during that timespan. The
default timeout is `infinity`, which should only be used if
you have alternate means of ending inactive connections.
:: Terminate reasons
The following values may be received as the terminate reason
in the optional `terminate/3` callback.
: normal
The connection was closed normally before switching to the
loop sub protocol. This typically happens if an `ok` tuple is
returned from the `init/2` callback.
: stop
The handler requested to close the connection by returning
a `stop` tuple.
: timeout
The connection has been closed due to inactivity. The timeout
value can be configured from `init/2`. The response sent when
this happens is a `204 No Content`.
: {crash, Class, Reason}
A crash occurred in the handler. `Class` and `Reason` can be
used to obtain more information about the crash. The function
`erlang:get_stacktrace/0` can also be called to obtain the
stacktrace of the process when the crash occurred.
: {error, overflow}
The connection is being closed and the process terminated
because the buffer Cowboy uses to keep data sent by the
client has reached its maximum. The buffer size can be
configured through the environment value `loop_max_buffer`
and defaults to 5000 bytes.
If the long running request comes with a body it is recommended
to process this body before switching to the loop sub protocol.
: {error, closed}
The socket has been closed brutally without a close frame being
received first.
: {error, Reason}
A socket error ocurred.
:: Callbacks
: info(Info, Req, State)
-> {ok, Req, State}
| {ok, Req, State, hibernate}
| {stop, Req, State}
Types:
* Info = any()
* Req = cowboy_req:req()
* State = any()
Handle the Erlang message received.
This function will be called every time an Erlang message
has been received. The message can be any Erlang term.
The `stop` return value can be used to stop the receive loop,
typically because a response has been sent.
The `hibernate` option will hibernate the process until
it receives another message.

View file

@ -1,4 +1,10 @@
::: cowboy_middleware
= cowboy_middleware(3)
== Name
cowboy_middleware - behaviour for middlewares
== Description
The `cowboy_middleware` behaviour defines the interface used
by Cowboy middleware modules.
@ -6,9 +12,9 @@ by Cowboy middleware modules.
Middlewares process the request sequentially in the order they
are configured.
:: Types
== Types
: env() = [{atom(), any()}]
=== env() = [{atom(), any()}]
The environment variable.
@ -16,20 +22,15 @@ One is created for every request. It is passed to each
middleware module executed and subsequently returned,
optionally with its contents modified.
:: Callbacks
== Callbacks
: execute(Req, Env)
-> {ok, Req, Env}
| {suspend, Module, Function, Args}
| {stop, Req}
=== execute(Req, Env) -> {ok, Req, Env} | {suspend, Module, Function, Args} | {stop, Req}
Types:
* Req = cowboy_req:req()
* Env = env()
* Module = module()
* Function = atom()
* Args = [any()]
Req = cowboy_req:req():: The Req object.
Env = env():: The request environment.
Module = module():: MFA to call when resuming the process.
Function = atom():: MFA to call when resuming the process.
Args = [any()]:: MFA to call when resuming the process.
Execute the middleware.

View file

@ -0,0 +1,75 @@
= cowboy_protocol(3)
== Name
cowboy_protocol - HTTP protocol
== Description
The `cowboy_protocol` module implements HTTP/1.1 and HTTP/1.0
as a Ranch protocol.
== Types
=== opts() = [Option]
[source,erlang]
----
Option = {compress, boolean()}
| {env, cowboy_middleware:env()}
| {max_empty_lines, non_neg_integer()}
| {max_header_name_length, non_neg_integer()}
| {max_header_value_length, non_neg_integer()}
| {max_headers, non_neg_integer()}
| {max_keepalive, non_neg_integer()}
| {max_request_line_length, non_neg_integer()}
| {middlewares, [module()]}
| {onresponse, cowboy:onresponse_fun()}
| {timeout, timeout()}
----
Configuration for the HTTP protocol handler.
This configuration is passed to Cowboy when starting listeners
using `cowboy:start_http/4` or `cowboy:start_https/4` functions.
It can be updated without restarting listeners using the
Ranch functions `ranch:get_protocol_options/1` and
`ranch:set_protocol_options/2`.
=== Option descriptions
The default value is given next to the option name.
compress (false)::
When enabled, Cowboy will attempt to compress the response body.
env ([{listener, Ref}])::
Initial middleware environment.
max_empty_lines (5)::
Maximum number of empty lines before a request.
max_header_name_length (64)::
Maximum length of header names.
max_header_value_length (4096)::
Maximum length of header values.
max_headers (100)::
Maximum number of headers allowed per request.
max_keepalive (100)::
Maximum number of requests allowed per connection.
max_request_line_length (4096)::
Maximum length of the request line.
middlewares ([cowboy_router, cowboy_handler])::
List of middlewares to execute for every requests.
onresponse (undefined)::
Fun called every time a response is sent.
timeout (5000)::
Time in ms with no requests before Cowboy closes the connection.

View file

@ -1,75 +0,0 @@
::: cowboy_protocol
The `cowboy_protocol` module implements HTTP/1.1 and HTTP/1.0
as a Ranch protocol.
:: Types
: opts() = [{compress, boolean()}
| {env, cowboy_middleware:env()}
| {max_empty_lines, non_neg_integer()}
| {max_header_name_length, non_neg_integer()}
| {max_header_value_length, non_neg_integer()}
| {max_headers, non_neg_integer()}
| {max_keepalive, non_neg_integer()}
| {max_request_line_length, non_neg_integer()}
| {middlewares, [module()]}
| {onresponse, cowboy:onresponse_fun()}
| {timeout, timeout()}]
Configuration for the HTTP protocol handler.
This configuration is passed to Cowboy when starting listeners
using `cowboy:start_http/4` or `cowboy:start_https/4` functions.
It can be updated without restarting listeners using the
Ranch functions `ranch:get_protocol_options/1` and
`ranch:set_protocol_options/2`.
:: Option descriptions
The default value is given next to the option name.
: compress (false)
When enabled, Cowboy will attempt to compress the response body.
: env ([{listener, Ref}])
Initial middleware environment.
: max_empty_lines (5)
Maximum number of empty lines before a request.
: max_header_name_length (64)
Maximum length of header names.
: max_header_value_length (4096)
Maximum length of header values.
: max_headers (100)
Maximum number of headers allowed per request.
: max_keepalive (100)
Maximum number of requests allowed per connection.
: max_request_line_length (4096)
Maximum length of the request line.
: middlewares ([cowboy_router, cowboy_handler])
List of middlewares to execute for every requests.
: onresponse (undefined)
Fun called every time a response is sent.
: timeout (5000)
Time in ms with no requests before Cowboy closes the connection.

View file

@ -1,4 +1,10 @@
::: cowboy_req
= cowboy_req(3)
== Name
cowboy_req - HTTP request and response
== Description
The `cowboy_req` module provides functions to access, manipulate
and respond to requests.
@ -24,41 +30,54 @@ It is highly discouraged to pass the Req object to another process.
Doing so and calling `cowboy_req` functions from it leads to
undefined behavior.
:: Types
== Types
: body_opts() = [{continue, boolean()}
=== body_opts() = [Option]
[source,erlang]
----
Option = {continue, boolean()}
| {length, non_neg_integer()}
| {read_length, non_neg_integer()}
| {read_timeout, timeout()}
| {transfer_decode, transfer_decode_fun(), any()}
| {content_decode, content_decode_fun()}]
| {content_decode, content_decode_fun()}
----
Request body reading options.
: cookie_opts() = [{max_age, non_neg_integer()}
| {domain, binary()} | {path, binary()}
| {secure, boolean()} | {http_only, boolean()}]
=== cookie_opts() = [Option]
[source,erlang]
----
Option = {max_age, non_neg_integer()}
| {domain, binary()}
| {path, binary()}
| {secure, boolean()}
| {http_only, boolean()}
----
Cookie options.
: req() - opaque to the user
=== req() - opaque to the user
The Req object.
All functions in this module receive a `Req` as argument,
and most of them return a new object labelled `Req2` in
and some of them return a new object labelled `Req2` in
the function descriptions below.
:: Request related exports
== Request related exports
: binding(Name, Req) -> binding(Name, Req, undefined)
: binding(Name, Req, Default) -> Value
=== binding(Name, Req) -> binding(Name, Req, undefined)
Types:
Alias of `cowboy_req:binding/3`.
* Name = atom()
* Default = any()
* Value = any() | Default
=== binding(Name, Req, Default) -> Value
Name = atom():: Binding name.
Default = any():: Default value.
Value = any() | Default:: Binding value.
Return the value for the given binding.
@ -66,12 +85,10 @@ By default the value is a binary, however constraints may change
the type of this value (for example automatically converting
numbers to integer).
: bindings(Req) -> [{Name, Value}]
=== bindings(Req) -> [{Name, Value}]
Types:
* Name = atom()
* Value = any()
Name = atom():: Binding name.
Value = any():: Binding value.
Return all bindings.
@ -79,61 +96,52 @@ By default the value is a binary, however constraints may change
the type of this value (for example automatically converting
numbers to integer).
: header(Name, Req) -> header(Name, Req, undefined)
: header(Name, Req, Default) -> Value
=== header(Name, Req) -> header(Name, Req, undefined)
Types:
Alias of `cowboy_req:header/3`.
* Name = binary()
* Default = any()
* Value = binary() | Default
=== header(Name, Req, Default) -> Value
Name = binary():: Request header name.
Default = any():: Default value.
Value = binary() | Default:: Request header value.
Return the value for the given header.
While header names are case insensitive, this function expects
the name to be a lowercase binary.
: headers(Req) -> Headers
=== headers(Req) -> Headers
Types:
* Headers = cowboy:http_headers()
Headers = cowboy:http_headers():: Request headers.
Return all headers.
: host(Req) -> Host
=== host(Req) -> Host
Types:
* Host = binary()
Host = binary():: Requested host.
Return the requested host.
: host_info(Req) -> HostInfo
=== host_info(Req) -> HostInfo
Types:
* HostInfo = cowboy_router:tokens() | undefined
HostInfo = cowboy_router:tokens() | undefined:: Extra tokens for the host.
Return the extra tokens from matching against `...` during routing.
: host_url(Req) -> HostURL
=== host_url(Req) -> HostURL
Types:
* HostURL = binary() | undefined
HostURL = binary() | undefined:: Requested URL, without the path component.
Return the requested URL excluding the path component.
This function will always return `undefined` until the
`cowboy_router` middleware has been executed.
: match_cookies(Fields, Req) -> Map
=== match_cookies(Fields, Req) -> Map
Types:
* Fields = cowboy:fields()
* Map = map()
Fields = cowboy:fields():: Cookie fields match rules.
Map = map():: Cookie fields matched.
Match cookies against the given fields.
@ -153,12 +161,10 @@ be converted through the use of constraints, making this
function able to extract, validate and convert values all
in one step.
: match_qs(Fields, Req) -> Map
=== match_qs(Fields, Req) -> Map
Types:
* Fields = cowboy:fields()
* Map = map()
Fields = cowboy:fields():: Query string fields match rules.
Map = map():: Query string fields matched.
Match the query string against the given fields.
@ -177,86 +183,88 @@ returned map will be that atom. The value may be converted
through the use of constraints, making this function able
to extract, validate and convert values all in one step.
: meta(Name, Req) -> meta(Name, Req, undefined)
: meta(Name, Req, Default) -> Value
=== meta(Name, Req) -> meta(Name, Req, undefined)
Types:
Alias for `cowboy_req:meta/3`.
* Name = atom()
* Default = any()
* Value = any()
=== meta(Name, Req, Default) -> Value
Name = atom():: Metadata name.
Default = any():: Default value.
Value = any():: Metadata value.
Return metadata about the request.
: method(Req) -> Method
=== method(Req) -> Method
Types:
* Method = binary()
Method = binary():: Request method.
Return the method.
Methods are case sensitive. Standard methods are always uppercase.
: parse_cookies(Req) -> [{Name, Value}]
=== parse_cookies(Req) -> [{Name, Value}]
Types:
* Name = binary()
* Value = binary()
Name = binary():: Cookie name.
Value = binary():: Cookie value.
Parse and return all cookies.
Cookie names are case sensitive.
: parse_header(Name, Req) -> see below
: parse_header(Name, Req, Default) -> ParsedValue | Default
=== parse_header(Name, Req) -> see below
Types:
Alias of `cowboy_req:parse_header/3`.
* Name = binary()
* Default = any()
* ParsedValue - see below
The `parse_header/2` function will call `parser_header/3` with a
different default value depending on the header being parsed. The
following table summarizes the default values used.
[cols="<,^",options="header"]
|===
| Header name | Header value
| content-length | `0`
| cookie | `[]`
| transfer-encoding | `[<<"identity">>]`
| Any other header | `undefined`
|===
=== parse_header(Name, Req, Default) -> ParsedValue | Default
Name = binary():: Request header name.
Default = any():: Default value.
ParsedValue - see below:: Parsed request header value.
Parse the given header.
While header names are case insensitive, this function expects
the name to be a lowercase binary.
The `parse_header/2` function will call `parser_header/3` with a
different default value depending on the header being parsed. The
following table summarizes the default values used.
|| Header name Default value
|
| content-length `0`
| cookie `[]`
| transfer-encoding `[<<"identity">>]`
| Any other header `undefined`
The parsed value differs depending on the header being parsed. The
following table summarizes the different types returned.
|| Header name Type
|
| accept `[{{Type, SubType, Params}, Quality, AcceptExt}]`
| accept-charset `[{Charset, Quality}]`
| accept-encoding `[{Encoding, Quality}]`
| accept-language `[{LanguageTag, Quality}]`
| authorization `{AuthType, Credentials}`
| content-length `non_neg_integer()`
| content-type `{Type, SubType, ContentTypeParams}`
| cookie `[{binary(), binary()}]`
| expect `[Expect | {Expect, ExpectValue, Params}]`
| if-match `'*' | [{weak | strong, OpaqueTag}]`
| if-modified-since `calendar:datetime()`
| if-none-match `'*' | [{weak | strong, OpaqueTag}]`
| if-unmodified-since `calendar:datetime()`
| range `{Unit, [Range]}`
| sec-websocket-protocol `[binary()]`
| transfer-encoding `[binary()]`
| upgrade `[binary()]`
| x-forwarded-for `[binary()]`
[cols="<,^",options="header"]
|===
| Header name | Type of parsed header value
| accept | `[{{Type, SubType, Params}, Quality, AcceptExt}]`
| accept-charset | `[{Charset, Quality}]`
| accept-encoding | `[{Encoding, Quality}]`
| accept-language | `[{LanguageTag, Quality}]`
| authorization | `{AuthType, Credentials}`
| content-length | `non_neg_integer()`
| content-type | `{Type, SubType, ContentTypeParams}`
| cookie | `[{binary(), binary()}]`
| expect | `[Expect \| {Expect, ExpectValue, Params}]`
| if-match | `'*' \| [{weak \| strong, OpaqueTag}]`
| if-modified-since | `calendar:datetime()`
| if-none-match | `'*' \| [{weak \| strong, OpaqueTag}]`
| if-unmodified-since | `calendar:datetime()`
| range | `{Unit, [Range]}`
| sec-websocket-protocol | `[binary()]`
| transfer-encoding | `[binary()]`
| upgrade | `[binary()]`
| x-forwarded-for | `[binary()]`
|===
Types for the above table:
@ -292,12 +300,10 @@ The range header value `Range` can take three forms:
An `undefined` tuple will be returned if Cowboy doesn't know how
to parse the requested header.
: parse_qs(Req) -> [{Name, Value}]
=== parse_qs(Req) -> [{Name, Value}]
Types:
* Name = binary()
* Value = binary() | true
Name = binary():: Query string field name.
Value = binary() | true:: Query string field value.
Return the request's query string as a list of tuples.
@ -306,35 +312,27 @@ Keys with no value are different from keys with an empty
value in that they do not have a `=` indicating the presence
of a value.
: path(Req) -> Path
=== path(Req) -> Path
Types:
* Path = binary()
Path = binary():: Requested path.
Return the requested path.
: path_info(Req) -> PathInfo
=== path_info(Req) -> PathInfo
Types:
* PathInfo = cowboy_router:tokens() | undefined
PathInfo = cowboy_router:tokens() | undefined:: Extra tokens for the path.
Return the extra tokens from matching against `...` during routing.
: peer(Req) -> Peer
=== peer(Req) -> Peer
Types:
* Peer = {inet:ip_address(), inet:port_number()}
Peer = {inet:ip_address(), inet:port_number()}:: Peer IP address and port number.
Return the client's IP address and port number.
: port(Req) -> Port
=== port(Req) -> Port
Types:
* Port = inet:port_number()
Port = inet:port_number():: Requested port number.
Return the request's port.
@ -342,54 +340,46 @@ The port returned by this function is obtained by parsing
the host header. It may be different than the actual port
the client used to connect to the Cowboy server.
: qs(Req) -> QueryString
=== qs(Req) -> QueryString
Types:
* QueryString = binary()
QueryString = binary():: Unprocessed query string.
Return the request's query string.
: set_meta(Name, Value, Req) -> Req2
=== set_meta(Name, Value, Req) -> Req2
Types:
* Name = atom()
* Value = any()
Name = atom():: Metadata name.
Value = any():: Metadata value.
Set metadata about the request.
An existing value will be overwritten.
: url(Req) -> URL
=== url(Req) -> URL
Types:
* URL = binary() | undefined
URL = binary() | undefined:: Requested URL.
Return the requested URL.
This function will always return `undefined` until the
`cowboy_router` middleware has been executed.
: version(Req) -> Version
=== version(Req) -> Version
Types:
* Version = cowboy:http_version()
Version = cowboy:http_version():: Client's advertised HTTP version.
Return the HTTP version used for this request.
:: Request body related exports
== Request body related exports
: body(Req) -> body(Req, [])
: body(Req, Opts) -> {ok, Data, Req2} | {more, Data, Req2}
=== body(Req) -> body(Req, [])
Types:
Alias of `cowboy_req:body/2`.
* Opts = [body_opt()]
* Data = binary()
* Reason = atom()
=== body(Req, Opts) -> {ok, Data, Req2} | {more, Data, Req2}
Opts = [body_opt()]:: Request body reading options.
Data = binary():: Data read from the body.
Read the request body.
@ -422,11 +412,9 @@ the content-length header if it wasn't already there.
This function can only be called once. Cowboy will not cache
the result of this call.
: body_length(Req) -> Length
=== body_length(Req) -> Length
Types:
* Length = non_neg_integer() | undefined
Length = non_neg_integer() | undefined:: Length of the request body.
Return the length of the request body.
@ -434,16 +422,15 @@ The length will only be returned if the request does not
use any transfer-encoding and if the content-length header
is present.
: body_qs(Req) -> body_qs(Req,
[{length, 64000}, {read_length, 64000}, {read_timeout, 5000}])
: body_qs(Req, Opts) -> {ok, [{Name, Value}], Req2} | {badlength, Req2}
=== body_qs(Req) -> body_qs(Req, [{length, 64000}, {read_length, 64000}, {read_timeout, 5000}])
Types:
Alias of `cowboy_req:body_qs/2`.
* Opts = [body_opt()]
* Name = binary()
* Value = binary() | true
* Reason = chunked | badlength | atom()
=== body_qs(Req, Opts) -> {ok, [{Name, Value}], Req2} | {badlength, Req2}
Opts = [body_opt()]:: Request body reading options.
Name = binary():: Field name.
Value = binary() | true:: Field value.
Return the request body as a list of tuples.
@ -459,18 +446,18 @@ body is larger then a `badlength` tuple is returned.
This function can only be called once. Cowboy will not cache
the result of this call.
: has_body(Req) -> boolean()
=== has_body(Req) -> boolean()
Return whether the request has a body.
: part(Req) -> part(Req,
[{length, 64000}, {read_length, 64000}, {read_timeout, 5000}])
: part(Req, Opts) -> {ok, Headers, Req2} | {done, Req2}
=== part(Req) -> part(Req, [{length, 64000}, {read_length, 64000}, {read_timeout, 5000}])
Types:
Alias of `cowboy_req:part/2`.
* Opts = [body_opt()]
* Headers = cow_multipart:headers()
=== part(Req, Opts) -> {ok, Headers, Req2} | {done, Req2}
Opts = [body_opt()]:: Request body reading options.
Headers = cow_multipart:headers():: Part's headers.
Read the headers for the next part of the multipart message.
@ -496,13 +483,14 @@ of 64KB with a timeout of 5s. This is tailored for reading
part headers, not for skipping the previous part's body.
You might want to consider skipping large parts manually.
: part_body(Req) -> part_body(Req, [])
: part_body(Req, Opts) -> {ok, Data, Req2} | {more, Data, Req2}
=== part_body(Req) -> part_body(Req, [])
Types:
Alias of `cowboy_req:part_body/2`.
* Opts = [body_opt()]
* Data = binary()
=== part_body(Req, Opts) -> {ok, Data, Req2} | {more, Data, Req2}
Opts = [body_opt()]:: Request body reading options.
Data = binary():: Part's body.
Read the body of the current part of the multipart message.
@ -520,14 +508,11 @@ returned inside an `ok` tuple.
Note that once the body has been read, fully or partially,
it cannot be read again.
:: Response related exports
== Response related exports
: chunk(Data, Req) -> ok
=== chunk(Data, Req) -> ok
Types:
* Data = iodata()
* Reason = atom()
Data = iodata():: Chunk data to be sent.
Send a chunk of data.
@ -540,13 +525,14 @@ If the request uses HTTP/1.0, the data is sent directly
without wrapping it in an HTTP/1.1 chunk, providing
compatibility with older clients.
: chunked_reply(StatusCode, Req) -> chunked_reply(StatusCode, [], Req)
: chunked_reply(StatusCode, Headers, Req) -> Req2
=== chunked_reply(StatusCode, Req) -> chunked_reply(StatusCode, [], Req)
Types:
Alias of `cowboy_req:chunked_reply/3`.
* StatusCode = cowboy:http_status()
* Headers = cowboy:http_headers()
=== chunked_reply(StatusCode, Headers, Req) -> Req2
StatusCode = cowboy:http_status():: Response status code.
Headers = cowboy:http_headers():: Response headers.
Send a response using chunked transfer-encoding.
@ -564,11 +550,7 @@ compatibility with older clients.
This function can only be called once, with the exception
of overriding the response in the `onresponse` hook.
: continue(Req) -> ok
Types:
* Reason = atom()
=== continue(Req) -> ok
Send a 100 Continue intermediate reply.
@ -581,44 +563,44 @@ you may want to do it manually by disabling this behavior
with the `continue` body option and then calling this
function.
: delete_resp_header(Name, Req) -> Req2
=== delete_resp_header(Name, Req) -> Req2
Types:
* Name = binary()
Name = binary():: Response header name.
Delete the given response header.
While header names are case insensitive, this function expects
the name to be a lowercase binary.
: has_resp_body(Req) -> boolean()
=== has_resp_body(Req) -> boolean()
Return whether a response body has been set.
This function will return false if a response body has
been set with a length of 0.
: has_resp_header(Name, Req) -> boolean()
=== has_resp_header(Name, Req) -> boolean()
Types:
* Name = binary()
Name = binary():: Response header name.
Return whether the given response header has been set.
While header names are case insensitive, this function expects
the name to be a lowercase binary.
: reply(StatusCode, Req) -> reply(StatusCode, [], Req)
: reply(StatusCode, Headers, Req) - see below
: reply(StatusCode, Headers, Body, Req) -> Req2
=== reply(StatusCode, Req) -> reply(StatusCode, [], Req)
Types:
Alias of `cowboy_req:reply/3`.
* StatusCode = cowboy:http_status()
* Headers = cowboy:http_headers()
* Body = iodata()
=== reply(StatusCode, Headers, Req) - see below
Alias of `cowboy_req:reply/4`, with caveats.
=== reply(StatusCode, Headers, Body, Req) -> Req2
StatusCode = cowboy:http_status():: Response status code.
Headers = cowboy:http_headers():: Response headers.
Body = iodata():: Response body.
Send a response.
@ -639,26 +621,25 @@ returns.
This function can only be called once, with the exception
of overriding the response in the `onresponse` hook.
: set_resp_body(Body, Req) -> Req2
=== set_resp_body(Body, Req) -> Req2
Types:
* Body = iodata()
Body = iodata():: Response body.
Set a response body.
This body will not be sent if `chunked_reply/{2,3}` or
`reply/4` is used, as they override it.
: set_resp_body_fun(Fun, Req) -> Req2
: set_resp_body_fun(Length, Fun, Req) -> Req2
=== set_resp_body_fun(Fun, Req) -> Req2
Types:
Alias of `cowboy_req:set_resp_body_fun/3`.
* Fun = fun((Socket, Transport) -> ok)
* Socket = inet:socket()
* Transport = module()
* Length = non_neg_integer()
=== set_resp_body_fun(Length, Fun, Req) -> Req2
Fun = fun((Socket, Transport) -> ok):: Fun that will send the response body.
Socket = inet:socket():: Socket for this connection.
Transport = module():: Transport module for this socket.
Length = non_neg_integer():: Length of the response body.
Set a fun for sending the response body.
@ -673,12 +654,10 @@ using the `reply/2` or `reply/3` function.
The fun will receive the Ranch `Socket` and `Transport` as
arguments. Only send and sendfile operations are supported.
: set_resp_body_fun(chunked, Fun, Req) -> Req2
=== set_resp_body_fun(chunked, Fun, Req) -> Req2
Types:
* Fun = fun((ChunkFun) -> ok)
* ChunkFun = fun((iodata()) -> ok)
Fun = fun((ChunkFun) -> ok):: Fun that will send the response body.
ChunkFun = fun((iodata()) -> ok):: Fun to call for every chunk to be sent.
Set a fun for sending the response body using chunked transfer-encoding.
@ -690,24 +669,20 @@ be used to send chunks in a similar way to the `chunk/2` function,
except the fun only takes one argument, the data to be sent in
the chunk.
: set_resp_cookie(Name, Value, Opts, Req) -> Req2
=== set_resp_cookie(Name, Value, Opts, Req) -> Req2
Types:
* Name = iodata()
* Value = iodata()
* Opts = cookie_opts()
Name = iodata():: Cookie name.
Value = iodata():: Cookie value.
Opts = cookie_opts():: Cookie options.
Set a cookie in the response.
Cookie names are case sensitive.
: set_resp_header(Name, Value, Req) -> Req2
=== set_resp_header(Name, Value, Req) -> Req2
Types:
* Name = binary()
* Value = iodata()
Name = binary():: Response header name.
Value = iodata():: Response header value.
Set a response header.

View file

@ -1,4 +1,10 @@
::: cowboy_rest
= cowboy_rest(3)
== Name
cowboy_rest - REST handlers
== Description
The `cowboy_rest` module implements REST semantics on top of
the HTTP protocol.
@ -6,66 +12,53 @@ the HTTP protocol.
This module is a sub protocol that defines many callbacks
be implemented by handlers. The `init/2` and `terminate/3`
callbacks are common to all handler types and are documented
in the manual for the ^cowboy_handler module.
in the manual for the link:cowboy_handler.asciidoc[cowboy_handler] module.
All other callbacks are optional, though some may become
required depending on the return value of previous callbacks.
:: Meta values
== Meta values
: charset
charset = binary()::
Negotiated charset.
+
This value may not be defined if no charset was negotiated.
Type: binary()
language = binary()::
Negotiated language.
+
This value may not be defined if no language was negotiated.
Negotiated charset.
media_type = {binary(), binary(), '*' | [{binary(), binary()}]}::
Negotiated media-type.
+
The media-type is the content-type, excluding the charset.
+
This value is always defined after the call to
`content_types_provided/2`.
This value may not be defined if no charset was negotiated.
: language
Type: binary()
Negotiated language.
This value may not be defined if no language was negotiated.
: media_type
Type: {binary(), binary(), '*' | [{binary(), binary()}]}
Negotiated media-type.
The media-type is the content-type, excluding the charset.
This value is always defined after the call to
`content_types_provided/2`.
:: Terminate reasons
== Terminate reasons
The following values may be received as the terminate reason
in the optional `terminate/3` callback.
: normal
normal::
The connection was closed normally.
The connection was closed normally.
{crash, Class, Reason}::
A crash occurred in the handler. `Class` and `Reason` can be
used to obtain more information about the crash. The function
`erlang:get_stacktrace/0` can also be called to obtain the
stacktrace of the process when the crash occurred.
: {crash, Class, Reason}
== Callbacks
A crash occurred in the handler. `Class` and `Reason` can be
used to obtain more information about the crash. The function
`erlang:get_stacktrace/0` can also be called to obtain the
stacktrace of the process when the crash occurred.
=== Callback(Req, State) -> {Value, Req, State} | {stop, Req, State}
:: Callbacks
: Callback(Req, State) -> {Value, Req, State} | {stop, Req, State}
Types:
* Callback - one of the REST callbacks described below
* Req = cowboy_req:req()
* State = any()
* Value - see the REST callbacks description below
Callback:: One of the REST callbacks described below.
Req = cowboy_req:req():: The Req object.
State = any():: Handler state.
Value:: See the REST callbacks description below.
Please see the REST callbacks description below for details
on the `Value` type, the default value if the callback is
@ -76,23 +69,23 @@ The `stop` tuple can be returned to stop REST processing.
It is up to the resource code to send a reply before that,
otherwise a `204 No Content` will be sent.
:: REST callbacks description
== REST callbacks description
: allowed_methods
=== allowed_methods
* Methods: all
* Value type: [binary()]
* Default value: [<<"GET">>, <<"HEAD">>, <<"OPTIONS">>]
Methods:: all
Value type:: [binary()]
Default value:: `[<<"GET">>, <<"HEAD">>, <<"OPTIONS">>]`
Return the list of allowed methods.
Methods are case sensitive. Standard methods are always uppercase.
: allow_missing_post
=== allow_missing_post
* Methods: POST
* Value type: boolean()
* Default value: true
Methods:: POST
Value type:: boolean()
Default value:: true
Return whether POST is allowed when the resource doesn't exist.
@ -100,11 +93,11 @@ Returning `true` here means that a new resource will be
created. The URL to the created resource should also be
returned from the `AcceptResource` callback.
: charsets_provided
=== charsets_provided
* Methods: GET, HEAD, POST, PUT, PATCH, DELETE
* Value type: [binary()]
* Skip to the next step if undefined
Methods:: GET, HEAD, POST, PUT, PATCH, DELETE
Value type:: [binary()]
Default behavior:: Skip to the next step if undefined.
Return the list of charsets the resource provides.
@ -120,14 +113,14 @@ value `charset`.
While charsets are case insensitive, this callback is expected
to return them as lowercase binary.
: content_types_accepted
=== content_types_accepted
* Methods: POST, PUT, PATCH
* No default
Methods:: POST, PUT, PATCH
Value type:: [{binary() | {Type, SubType, Params}, AcceptResource}]
Default behavior:: Crash if undefined.
Types:
With types:
* Value = [{binary() | {Type, SubType, Params}, AcceptResource}]
* Type = SubType = binary()
* Params = '*' | [{binary(), binary()}]
* AcceptResource = atom()
@ -155,8 +148,8 @@ different list for each methods.
The `AcceptResource` value is the name of the callback that will
be called if the content-type matches. It is defined as follow.
* Value type: true | {true, URL} | false
* No default
Value type:: true | {true, URL} | false
Default behavior:: Crash if undefined.
Process the request body.
@ -174,14 +167,14 @@ and language can be retrieved using the `cowboy_req:meta/{2,3}`
functions. The respective keys are `media_type`, `charset`
and `language`. The body can be set using `cowboy_req:set_resp_body/2`.
: content_types_provided
=== content_types_provided
* Methods: GET, HEAD, POST, PUT, PATCH, DELETE
* Default value: [{{<<"text">>, <<"html">>, '*'}, to_html}]
Methods:: GET, HEAD, POST, PUT, PATCH, DELETE
Value type:: [{binary() | {Type, SubType, Params}, ProvideResource}]
Default value:: `[{{<<"text">>, <<"html">>, '*'}, to_html}]`
Types:
With types:
* Value = [{binary() | {Type, SubType, Params}, ProvideResource}]
* Type = SubType = binary()
* Params = '*' | [{binary(), binary()}]
* ProvideResource = atom()
@ -205,9 +198,9 @@ be called if the content-type matches. It will only be called when
a representation of the resource needs to be returned. It is defined
as follow.
* Methods: GET, HEAD
* Value type: iodata() | {stream, Fun} | {stream, Len, Fun} | {chunked, ChunkedFun}
* No default
Methods:: GET, HEAD
Value type:: iodata() | {stream, Fun} | {stream, Len, Fun} | {chunked, ChunkedFun}
Default behavior:: Crash if undefined.
Return the response body.
@ -220,11 +213,11 @@ The call to this callback happens a good time after the call to
`content_types_provided/2`, when it is time to start rendering
the response body.
: delete_completed
=== delete_completed
* Methods: DELETE
* Value type: boolean()
* Default value: true
Methods:: DELETE
Value type:: boolean()
Default value:: true
Return whether the delete action has been completed.
@ -235,11 +228,11 @@ including from any internal cache.
When this function returns `false`, a `202 Accepted`
response will be sent instead of a `200 OK` or `204 No Content`.
: delete_resource
=== delete_resource
* Methods: DELETE
* Value type: boolean()
* Default value: false
Methods:: DELETE
Value type:: boolean()
Default value:: false
Delete the resource.
@ -247,21 +240,21 @@ The value returned indicates if the action was successful,
regardless of whether the resource is immediately deleted
from the system.
: expires
=== expires
* Methods: GET, HEAD
* Value type: calendar:datetime() | binary() | undefined
* Default value: undefined
Methods:: GET, HEAD
Value type:: calendar:datetime() | binary() | undefined
Default value:: undefined
Return the date of expiration of the resource.
This date will be sent as the value of the expires header.
: forbidden
=== forbidden
* Methods: all
* Value type: boolean()
* Default value: false
Methods:: all
Value type:: boolean()
Default value:: false
Return whether access to the resource is forbidden.
@ -270,11 +263,11 @@ function returns `true`. This status code means that
access is forbidden regardless of authentication,
and that the request shouldn't be repeated.
: generate_etag
=== generate_etag
* Methods: GET, HEAD, POST, PUT, PATCH, DELETE
* Value type: binary() | {weak | strong, binary()}
* Default value: undefined
Methods:: GET, HEAD, POST, PUT, PATCH, DELETE
Value type:: binary() | {weak | strong, binary()}
Default value:: undefined
Return the entity tag of the resource.
@ -284,13 +277,13 @@ If a binary is returned, then the value will be parsed
to the tuple form automatically. The value must be in
the same format as the etag header, including quotes.
: is_authorized
=== is_authorized
* Methods: all
* Value type: true | {false, AuthHeader}
* Default value: true
Methods:: all
Value type:: true | {false, AuthHeader}
Default value:: true
Types:
With types:
* AuthHead = iodata()
@ -304,22 +297,22 @@ If the authentication fails, the value returned will be sent
as the value for the www-authenticate header in the
`401 Unauthorized` response.
: is_conflict
=== is_conflict
* Methods: PUT
* Value type: boolean()
* Default value: false
Methods:: PUT
Value type:: boolean()
Default value:: false
Return whether the put action results in a conflict.
A `409 Conflict` response will be sent if this function
returns `true`.
: known_methods
=== known_methods
* Methods: all
* Value type: [binary()]
* Default value: [<<"GET">>, <<"HEAD">>, <<"POST">>, <<"PUT">>, <<"PATCH">>, <<"DELETE">>, <<"OPTIONS">>]
Methods:: all
Value type:: [binary()]
Default value:: `[<<"GET">>, <<"HEAD">>, <<"POST">>, <<"PUT">>, <<"PATCH">>, <<"DELETE">>, <<"OPTIONS">>]`
Return the list of known methods.
@ -331,11 +324,11 @@ implement in `cowboy_rest`.
Methods are case sensitive. Standard methods are always uppercase.
: languages_provided
=== languages_provided
* Methods: GET, HEAD, POST, PUT, PATCH, DELETE
* Value type: [binary()]
* Skip to the next step if undefined
Methods:: GET, HEAD, POST, PUT, PATCH, DELETE
Value type:: [binary()]
Default behavior:: Skip to the next step if undefined.
Return the list of languages the resource provides.
@ -351,11 +344,11 @@ value `language`.
While languages are case insensitive, this callback is expected
to return them as lowercase binary.
: last_modified
=== last_modified
* Methods: GET, HEAD, POST, PUT, PATCH, DELETE
* Value type: calendar:datetime()
* Default value: undefined
Methods:: GET, HEAD, POST, PUT, PATCH, DELETE
Value type:: calendar:datetime()
Default value:: undefined
Return the date of last modification of the resource.
@ -363,11 +356,11 @@ This date will be used to test against the if-modified-since
and if-unmodified-since headers, and sent as the last-modified
header in the response of GET and HEAD requests.
: malformed_request
=== malformed_request
* Methods: all
* Value type: boolean()
* Default value: false
Methods:: all
Value type:: boolean()
Default value:: false
Return whether the request is malformed.
@ -378,13 +371,13 @@ are expected to implement it.
The check is to be done on the request itself, not on
the request body, which is processed later.
: moved_permanently
=== moved_permanently
* Methods: GET, HEAD, POST, PUT, PATCH, DELETE
* Value type: {true, URL} | false
* Default value: false
Methods:: GET, HEAD, POST, PUT, PATCH, DELETE
Value type:: {true, URL} | false
Default value:: false
Types:
With types:
* URL = iodata()
@ -393,13 +386,13 @@ Return whether the resource was permanently moved.
If it was, its new URL is also returned and sent in the
location header in the response.
: moved_temporarily
=== moved_temporarily
* Methods: GET, HEAD, POST, PATCH, DELETE
* Value type: {true, URL} | false
* Default value: false
Methods:: GET, HEAD, POST, PATCH, DELETE
Value type:: {true, URL} | false
Default value:: false
Types:
With types:
* URL = iodata()
@ -408,11 +401,11 @@ Return whether the resource was temporarily moved.
If it was, its new URL is also returned and sent in the
location header in the response.
: multiple_choices
=== multiple_choices
* Methods: GET, HEAD, POST, PUT, PATCH, DELETE
* Value type: boolean()
* Default value: false
Methods:: GET, HEAD, POST, PUT, PATCH, DELETE
Value type:: boolean()
Default value:: false
Return whether there are multiple representations of the resource.
@ -425,11 +418,11 @@ The content-type of the response should be the one previously
negociated and that can be obtained by calling
`cowboy_req:meta(media_type, Req)`.
: options
=== options
* Methods: OPTIONS
* Value type: ok
* Default value: ok
Methods:: OPTIONS
Value type:: ok
Default value:: ok
Handle a request for information.
@ -439,19 +432,19 @@ options available for this resource.
By default, Cowboy will send a `200 OK` response with the
allow header set.
: previously_existed
=== previously_existed
* Methods: GET, HEAD, POST, PATCH, DELETE
* Value type: boolean()
* Default value: false
Methods:: GET, HEAD, POST, PATCH, DELETE
Value type:: boolean()
Default value:: false
Return whether the resource existed previously.
: resource_exists
=== resource_exists
* Methods: GET, HEAD, POST, PUT, PATCH, DELETE
* Value type: boolean()
* Default value: true
Methods:: GET, HEAD, POST, PUT, PATCH, DELETE
Value type:: boolean()
Default value:: true
Return whether the resource exists.
@ -459,11 +452,11 @@ If it exists, conditional headers will be tested before
attempting to perform the action. Otherwise, Cowboy will
check if the resource previously existed first.
: service_available
=== service_available
* Methods: all
* Value type: boolean()
* Default value: true
Methods:: all
Value type:: boolean()
Default value:: true
Return whether the service is available.
@ -473,11 +466,11 @@ systems are up and able to handle requests.
A `503 Service Unavailable` response will be sent if this
function returns `false`.
: uri_too_long
=== uri_too_long
* Methods: all
* Value type: boolean()
* Default value: false
Methods:: all
Value type:: boolean()
Default value:: false
Return whether the requested URI is too long.
@ -488,11 +481,11 @@ are expected to implement it.
A `414 Request-URI Too Long` response will be sent if this
function returns `true`.
: valid_content_headers
=== valid_content_headers
* Methods: all
* Value type: boolean()
* Default value: true
Methods:: all
Value type:: boolean()
Default value:: true
Return whether the content-* headers are valid.
@ -505,22 +498,22 @@ quickly check the headers can be parsed.
A `501 Not Implemented` response will be sent if this
function returns `false`.
: valid_entity_length
=== valid_entity_length
* Methods: all
* Value type: boolean()
* Default value: true
Methods:: all
Value type:: boolean()
Default value:: true
Return whether the request body length is within acceptable boundaries.
A `413 Request Entity Too Large` response will be sent if this
function returns `false`.
: variances
=== variances
* Methods: GET, HEAD, POST, PUT, PATCH, DELETE
* Value type: [binary()]
* Default value: []
Methods:: GET, HEAD, POST, PUT, PATCH, DELETE
Value type:: [binary()]
Default value:: []
Return the list of headers that affect the representation of the resource.

View file

@ -1,4 +1,10 @@
::: cowboy_router
= cowboy_router(3)
== Name
cowboy_router - router middleware
== Description
The `cowboy_router` middleware maps the requested host and
path to the handler to be used for processing the request.
@ -7,49 +13,44 @@ to the `compile/1` function for this purpose. It adds the
handler name and options to the environment as the values
`handler` and `handler_opts` respectively.
Environment input:
=== Environment input
* dispatch = dispatch_rules()
dispatch = dispatch_rules():: Dispatch table.
Environment output:
=== Environment output
* handler = module()
* handler_opts = any()
handler = module():: Handler module.
handler_opts = any():: Handler options.
:: Types
== Types
: bindings() = [{atom(), binary()}]
=== bindings() = [{atom(), binary()}]
List of bindings found during routing.
: dispatch_rules() - opaque to the user
=== dispatch_rules() - opaque to the user
Rules for dispatching request used by Cowboy.
: routes() = [{Host, Paths} | {Host, cowboy:fields(), Paths}]
=== routes() = [{Host, Paths} | {Host, cowboy:fields(), Paths}]
Types:
With types:
* Host = Path = '_' | iodata()
* Paths = [{Path, Handler, Opts} | {Path, cowboy:fields(), Handler, Opts}]
* Paths = [{Path, Handler, Opts} | {Path, cowboy:fields(), Handler, HandlerOpts}]
* Handler = module()
* Opts = any()
* HandlerOpts = any()
Human readable list of routes mapping hosts and paths to handlers.
The syntax for routes is defined in the user guide.
: tokens() = [binary()]
=== tokens() = [binary()]
List of host_info and path_info tokens found during routing.
:: Exports
== Exports
: compile(Routes) -> Dispatch
Types:
* Routes = routes()
* Dispatch = dispatch_rules()
=== compile(routes()) -> dispatch_rules()
Compile the routes for use by Cowboy.

View file

@ -0,0 +1,42 @@
= cowboy_spdy(3)
== Name
cowboy_spdy - SPDY protocol
== Description
The `cowboy_spdy` module implements SPDY/3 as a Ranch protocol.
== Types
=== opts() = [Option]
[source,erlang]
----
Option = {env, cowboy_middleware:env()}
| {middlewares, [module()]}
| {onresponse, cowboy:onresponse_fun()}
----
Configuration for the SPDY protocol handler.
This configuration is passed to Cowboy when starting listeners
using the `cowboy:start_spdy/4` function.
It can be updated without restarting listeners using the
Ranch functions `ranch:get_protocol_options/1` and
`ranch:set_protocol_options/2`.
== Option descriptions
The default value is given next to the option name.
env ([{listener, Ref}])::
Initial middleware environment.
middlewares ([cowboy_router, cowboy_handler])::
List of middlewares to execute for every requests.
onresponse (undefined)::
Fun called every time a response is sent.

View file

@ -1,34 +0,0 @@
::: cowboy_spdy
The `cowboy_spdy` module implements SPDY/3 as a Ranch protocol.
:: Types
: opts() = [{env, cowboy_middleware:env()}
| {middlewares, [module()]}
| {onresponse, cowboy:onresponse_fun()}]
Configuration for the SPDY protocol handler.
This configuration is passed to Cowboy when starting listeners
using the `cowboy:start_spdy/4` function.
It can be updated without restarting listeners using the
Ranch functions `ranch:get_protocol_options/1` and
`ranch:set_protocol_options/2`.
:: Option descriptions
The default value is given next to the option name.
: env ([{listener, Ref}])
Initial middleware environment.
: middlewares ([cowboy_router, cowboy_handler])
List of middlewares to execute for every requests.
: onresponse (undefined)
Fun called every time a response is sent.

View file

@ -0,0 +1,41 @@
= cowboy_static(3)
== Name
cowboy_static - static file handler
== Description
The `cowboy_static` module implements file serving capabilities
by using the REST semantics provided by `cowboy_rest`.
== Types
=== opts() = [Option]
[source,erlang]
----
Option = {priv_file, atom(), string() | binary()}
| {priv_file, atom(), string() | binary(), Extra}
| {file, string() | binary()}
| {file, string() | binary(), Extra}
| {priv_dir, atom(), string() | binary()}
| {priv_dir, atom(), string() | binary(), Extra}
| {dir, string() | binary()}
| {dir, string() | binary(), Extra}
Extra = [ETag | Mimetypes]
ETag = {etag, module(), function()} | {etag, false}
Mimetypes = {mimetypes, module(), function()}
| {mimetypes, binary() | {binary(), binary(), [{binary(), binary()}]}}
----
Configuration for the static handler.
The handler can be configured for sending either one file or
a directory (including its subdirectories).
Extra options allow you to define how the etag should be calculated
and how the mimetype of files should be detected.

View file

@ -1,32 +0,0 @@
::: cowboy_static
The `cowboy_static` module implements file serving capabilities
by using the REST semantics provided by `cowboy_rest`.
:: Types
: opts() = {priv_file, atom(), string() | binary()}
| {priv_file, atom(), string() | binary(), extra()}
| {file, string() | binary()}
| {file, string() | binary(), extra()}
| {priv_dir, atom(), string() | binary()}
| {priv_dir, atom(), string() | binary(), extra()}
| {dir, string() | binary()}
| {dir, string() | binary(), extra()}
Configuration for the static handler.
The handler can be configured for sending either one file or
a directory (including its subdirectories).
Extra options allow you to define how the etag should be calculated
and how the mimetype of files should be detected. They are defined
as follow, but do note that these types are not exported, only the
`opts/0` type is public.
: extra() = [extra_etag() | extra_mimetypes()]
: extra_etag() = {etag, module(), function()} | {etag, false}
: extra_mimetypes() = {mimetypes, module(), function()}
| {mimetypes, binary() | {binary(), binary(), [{binary(), binary()}]}}

View file

@ -0,0 +1,27 @@
= cowboy_sub_protocol(3)
== Name
cowboy_sub_protocol - sub protocol
== Description
The `cowboy_sub_protocol` behaviour defines the interface used
by modules that implement a protocol on top of HTTP.
== Callbacks
=== upgrade(Req, Env, Handler, HandlerOpts) -> {ok, Req, Env} | {suspend, Module, Function, Args} | {stop, Req}
Req = cowboy_req:req():: The Req object.
Env = env():: The request environment.
Handler = module():: Handler module.
Opts = any():: Handler options.
Module = module():: MFA to call when resuming the process.
Function = atom():: MFA to call when resuming the process.
Args = [any()]:: MFA to call when resuming the process.
Upgrade the protocol.
Please refer to the `cowboy_middleware` manual for a
description of the return values.

View file

@ -1,27 +0,0 @@
::: cowboy_sub_protocol
The `cowboy_sub_protocol` behaviour defines the interface used
by modules that implement a protocol on top of HTTP.
:: Callbacks
: upgrade(Req, Env, Handler, Opts)
-> {ok, Req, Env}
| {suspend, Module, Function, Args}
| {stop, Req}
Types:
* Req = cowboy_req:req()
* Env = env()
* Handler = module()
* Opts = any()
* Module = module()
* Function = atom()
* Args = [any()]
* StatusCode = cowboy:http_status()
Upgrade the protocol.
Please refer to the `cowboy_middleware` manual for a
description of the return values.

View file

@ -1,11 +1,17 @@
::: cowboy_websocket
= cowboy_websocket(3)
== Name
cowboy_websocket - Websocket protocol
== Description
The `cowboy_websocket` module implements the Websocket protocol.
This module is a sub protocol that defines four callbacks to
be implemented by handlers. The `init/2` and `terminate/3`
callbacks are common to all handler types and are documented
in the manual for the ^cowboy_handler module.
in the manual for the link:cowboy_handler.asciidoc[cowboy_handler] module.
The `websocket_handle/3` and `websocket_info/3` callbacks are
specific to Websocket handlers and will be called as many times
@ -22,91 +28,77 @@ Cowboy will terminate the process right after closing the
Websocket connection. This means that there is no real need to
perform any cleanup in the optional `terminate/3` callback.
:: Meta values
== Meta values
: websocket_compress
websocket_compress = boolean()::
Whether a websocket compression extension in in use.
Type: true | false
websocket_version = 7 | 8 | 13::
The version of the Websocket protocol being used.
Whether a websocket compression extension in in use.
: websocket_version
Type: 7 | 8 | 13
The version of the Websocket protocol being used.
:: Terminate reasons
== Terminate reasons
The following values may be received as the terminate reason
in the optional `terminate/3` callback.
: normal
normal::
The connection was closed normally before establishing a Websocket
connection. This typically happens if an `ok` tuple is returned
from the `init/2` callback.
The connection was closed normally before establishing a Websocket
connection. This typically happens if an `ok` tuple is returned
from the `init/2` callback.
remote::
The remote endpoint closed the connection without giving any
further details.
: remote
{remote, Code, Payload}::
The remote endpoint closed the connection with the given
`Code` and `Payload` as the reason.
The remote endpoint closed the connection without giving any
further details.
stop::
The handler requested to close the connection, either by returning
a `stop` tuple or by sending a `close` frame.
: {remote, Code, Payload}
timeout::
The connection has been closed due to inactivity. The timeout
value can be configured from `init/2`.
The remote endpoint closed the connection with the given
`Code` and `Payload` as the reason.
{crash, Class, Reason}::
A crash occurred in the handler. `Class` and `Reason` can be
used to obtain more information about the crash. The function
`erlang:get_stacktrace/0` can also be called to obtain the
stacktrace of the process when the crash occurred.
: stop
{error, badencoding}::
A text frame was sent by the client with invalid encoding. All
text frames must be valid UTF-8.
The handler requested to close the connection, either by returning
a `stop` tuple or by sending a `close` frame.
{error, badframe}::
A protocol error has been detected.
: timeout
{error, closed}::
The socket has been closed brutally without a close frame being
received first.
The connection has been closed due to inactivity. The timeout
value can be configured from `init/2`.
{error, Reason}::
A socket error ocurred.
: {crash, Class, Reason}
== Callbacks
A crash occurred in the handler. `Class` and `Reason` can be
used to obtain more information about the crash. The function
`erlang:get_stacktrace/0` can also be called to obtain the
stacktrace of the process when the crash occurred.
=== websocket_handle(InFrame, Req, State) -> Ret
: {error, badencoding}
A text frame was sent by the client with invalid encoding. All
text frames must be valid UTF-8.
: {error, badframe}
A protocol error has been detected.
: {error, closed}
The socket has been closed brutally without a close frame being
received first.
: {error, Reason}
A socket error ocurred.
:: Callbacks
: websocket_handle(InFrame, Req, State)
-> {ok, Req, State}
[source,erlang]
----
Ret = {ok, Req, State}
| {ok, Req, State, hibernate}
| {reply, OutFrame | [OutFrame], Req, State}
| {reply, OutFrame | [OutFrame], Req, State, hibernate}
| {stop, Req, State}
Types:
* InFrame = {text | binary | ping | pong, binary()}
* Req = cowboy_req:req()
* State = any()
* OutFrame = cow_ws:frame()
InFrame = {text | binary | ping | pong, binary()}
Req = cowboy_req:req()
State = any()
OutFrame = cow_ws:frame()
----
Handle the data received from the Websocket connection.
@ -121,19 +113,21 @@ The `hibernate` option will hibernate the process until
it receives new data from the Websocket connection or an
Erlang message.
: websocket_info(Info, Req, State)
-> {ok, Req, State}
=== websocket_info(Info, Req, State) -> Ret
[source,erlang]
----
Ret = {ok, Req, State}
| {ok, Req, State, hibernate}
| {reply, OutFrame | [OutFrame], Req, State}
| {reply, OutFrame | [OutFrame], Req, State, hibernate}
| {stop, Req, State}
Types:
* Info = any()
* Req = cowboy_req:req()
* State = any()
* OutFrame = cow_ws:frame()
Info = any()
Req = cowboy_req:req()
State = any()
OutFrame = cow_ws:frame()
----
Handle the Erlang message received.

View file

@ -1,61 +1,67 @@
::: HTTP status codes
= HTTP status codes(7)
== Name
HTTP status codes - status codes used by Cowboy
== Description
This chapter aims to list all HTTP status codes that Cowboy
may return, with details on the reasons why. The list given
here only includes the replies that Cowboy sends, not user
replies.
: 100 Continue
== 100 Continue
When the client sends an `expect: 100-continue` header,
Cowboy automatically sends a this status code before
trying to read the request body. This behavior can be
disabled using the appropriate body option.
: 101 Switching Protocols
== 101 Switching Protocols
This is the status code sent when switching to the
Websocket protocol.
: 200 OK
== 200 OK
This status code is sent by `cowboy_rest`.
: 201 Created
== 201 Created
This status code is sent by `cowboy_rest`.
: 202 Accepted
== 202 Accepted
This status code is sent by `cowboy_rest`.
: 204 No Content
== 204 No Content
This status code is sent when the processing of a request
ends without any reply having been sent. It may also be
sent by `cowboy_rest` under normal conditions.
: 300 Multiple Choices
== 300 Multiple Choices
This status code is sent by `cowboy_rest`.
: 301 Moved Permanently
== 301 Moved Permanently
This status code is sent by `cowboy_rest`.
: 303 See Other
== 303 See Other
This status code is sent by `cowboy_rest`.
: 304 Not Modified
== 304 Not Modified
This status code is sent by `cowboy_rest`.
: 307 Temporary Redirect
== 307 Temporary Redirect
This status code is sent by `cowboy_rest`.
: 400 Bad Request
== 400 Bad Request
Cowboy will send this status code for any of the
following reasons:
@ -73,78 +79,78 @@ following reasons:
* REST under normal conditions.
* A Websocket upgrade failed.
: 401 Unauthorized
== 401 Unauthorized
This status code is sent by `cowboy_rest`.
: 403 Forbidden
== 403 Forbidden
This status code is sent by `cowboy_rest`.
: 404 Not Found
== 404 Not Found
This status code is sent when the router successfully
resolved the host but didn't find a matching path for
the request. It may also be sent by `cowboy_rest` under
normal conditions.
: 405 Method Not Allowed
== 405 Method Not Allowed
This status code is sent by `cowboy_rest`.
: 406 Not Acceptable
== 406 Not Acceptable
This status code is sent by `cowboy_rest`.
: 408 Request Timeout
== 408 Request Timeout
Cowboy will send this status code to the client if the
client started to send a request, indicated by the
request-line being received fully, but failed to send
all headers in a reasonable time.
: 409 Conflict
== 409 Conflict
This status code is sent by `cowboy_rest`.
: 410 Gone
== 410 Gone
This status code is sent by `cowboy_rest`.
: 412 Precondition Failed
== 412 Precondition Failed
This status code is sent by `cowboy_rest`.
: 413 Request Entity Too Large
== 413 Request Entity Too Large
This status code is sent by `cowboy_rest`.
: 414 Request-URI Too Long
== 414 Request-URI Too Long
Cowboy will send this status code to the client if the
request-line is too long. It may also be sent by
`cowboy_rest` under normal conditions.
: 415 Unsupported Media Type
== 415 Unsupported Media Type
This status code is sent by `cowboy_rest`.
: 500 Internal Server Error
== 500 Internal Server Error
This status code is sent when a crash occurs in HTTP, loop
or REST handlers, or when an invalid return value is
returned. It may also be sent by `cowboy_rest` under
normal conditions.
: 501 Not Implemented
== 501 Not Implemented
This status code is sent by `cowboy_rest`.
: 503 Service Unavailable
== 503 Service Unavailable
This status code is sent by `cowboy_rest`.
: 505 HTTP Version Not Supported
== 505 HTTP Version Not Supported
Cowboy only supports the versions 1.0 and 1.1 of HTTP.
In all other cases this status code is sent back to the

View file

@ -1,18 +0,0 @@
::: Cowboy Function Reference
The function reference documents the public interface of Cowboy.
* ^"The Cowboy Application^cowboy_app
* ^cowboy
* ^cowboy_handler
* ^cowboy_loop
* ^cowboy_middleware
* ^cowboy_protocol
* ^cowboy_req
* ^cowboy_rest
* ^cowboy_router
* ^cowboy_spdy
* ^cowboy_static
* ^cowboy_sub_protocol
* ^cowboy_websocket
* ^"HTTP status codes^http_status_codes