From 4023e7f4e429179fd9c2cce4487c33646c6bd327 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Hoguin?= Date: Thu, 14 Jan 2016 13:35:25 +0100 Subject: Convert the documentation to Asciidoc A few small revisions were made, and Erlang.mk has been updated. --- doc/src/manual/cowboy.asciidoc | 98 ++++ doc/src/manual/cowboy.ezdoc | 98 ---- doc/src/manual/cowboy_app.asciidoc | 25 + doc/src/manual/cowboy_app.ezdoc | 23 - doc/src/manual/cowboy_handler.asciidoc | 99 ++++ doc/src/manual/cowboy_handler.ezdoc | 106 ----- doc/src/manual/cowboy_loop.asciidoc | 86 ++++ doc/src/manual/cowboy_loop.ezdoc | 92 ---- doc/src/manual/cowboy_middleware.asciidoc | 48 ++ doc/src/manual/cowboy_middleware.ezdoc | 47 -- doc/src/manual/cowboy_protocol.asciidoc | 75 +++ doc/src/manual/cowboy_protocol.ezdoc | 75 --- doc/src/manual/cowboy_req.asciidoc | 690 +++++++++++++++++++++++++++ doc/src/manual/cowboy_req.ezdoc | 715 ---------------------------- doc/src/manual/cowboy_rest.asciidoc | 529 ++++++++++++++++++++ doc/src/manual/cowboy_rest.ezdoc | 536 --------------------- doc/src/manual/cowboy_router.asciidoc | 56 +++ doc/src/manual/cowboy_router.ezdoc | 55 --- doc/src/manual/cowboy_spdy.asciidoc | 42 ++ doc/src/manual/cowboy_spdy.ezdoc | 34 -- doc/src/manual/cowboy_static.asciidoc | 41 ++ doc/src/manual/cowboy_static.ezdoc | 32 -- doc/src/manual/cowboy_sub_protocol.asciidoc | 27 ++ doc/src/manual/cowboy_sub_protocol.ezdoc | 27 -- doc/src/manual/cowboy_websocket.asciidoc | 143 ++++++ doc/src/manual/cowboy_websocket.ezdoc | 149 ------ doc/src/manual/http_status_codes.asciidoc | 157 ++++++ doc/src/manual/http_status_codes.ezdoc | 151 ------ doc/src/manual/index.ezdoc | 18 - 29 files changed, 2116 insertions(+), 2158 deletions(-) create mode 100644 doc/src/manual/cowboy.asciidoc delete mode 100644 doc/src/manual/cowboy.ezdoc create mode 100644 doc/src/manual/cowboy_app.asciidoc delete mode 100644 doc/src/manual/cowboy_app.ezdoc create mode 100644 doc/src/manual/cowboy_handler.asciidoc delete mode 100644 doc/src/manual/cowboy_handler.ezdoc create mode 100644 doc/src/manual/cowboy_loop.asciidoc delete mode 100644 doc/src/manual/cowboy_loop.ezdoc create mode 100644 doc/src/manual/cowboy_middleware.asciidoc delete mode 100644 doc/src/manual/cowboy_middleware.ezdoc create mode 100644 doc/src/manual/cowboy_protocol.asciidoc delete mode 100644 doc/src/manual/cowboy_protocol.ezdoc create mode 100644 doc/src/manual/cowboy_req.asciidoc delete mode 100644 doc/src/manual/cowboy_req.ezdoc create mode 100644 doc/src/manual/cowboy_rest.asciidoc delete mode 100644 doc/src/manual/cowboy_rest.ezdoc create mode 100644 doc/src/manual/cowboy_router.asciidoc delete mode 100644 doc/src/manual/cowboy_router.ezdoc create mode 100644 doc/src/manual/cowboy_spdy.asciidoc delete mode 100644 doc/src/manual/cowboy_spdy.ezdoc create mode 100644 doc/src/manual/cowboy_static.asciidoc delete mode 100644 doc/src/manual/cowboy_static.ezdoc create mode 100644 doc/src/manual/cowboy_sub_protocol.asciidoc delete mode 100644 doc/src/manual/cowboy_sub_protocol.ezdoc create mode 100644 doc/src/manual/cowboy_websocket.asciidoc delete mode 100644 doc/src/manual/cowboy_websocket.ezdoc create mode 100644 doc/src/manual/http_status_codes.asciidoc delete mode 100644 doc/src/manual/http_status_codes.ezdoc delete mode 100644 doc/src/manual/index.ezdoc (limited to 'doc/src/manual') diff --git a/doc/src/manual/cowboy.asciidoc b/doc/src/manual/cowboy.asciidoc new file mode 100644 index 0000000..cd83b3d --- /dev/null +++ b/doc/src/manual/cowboy.asciidoc @@ -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. diff --git a/doc/src/manual/cowboy.ezdoc b/doc/src/manual/cowboy.ezdoc deleted file mode 100644 index c26ed37..0000000 --- a/doc/src/manual/cowboy.ezdoc +++ /dev/null @@ -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. diff --git a/doc/src/manual/cowboy_app.asciidoc b/doc/src/manual/cowboy_app.asciidoc new file mode 100644 index 0000000..2213bd1 --- /dev/null +++ b/doc/src/manual/cowboy_app.asciidoc @@ -0,0 +1,25 @@ += cowboy(7) + +== Name + +cowboy - Small, fast, modular HTTP server. + +== Dependencies + +The `cowboy` application uses the Erlang applications `ranch` +for listening and accepting TCP connections, `crypto` for +establishing Websocket connections, and `cowlib` for parsing and +building messages for Web protocols. These dependencies must +be loaded for the `cowboy` application to work. In an embedded +environment this means that they need to be started with the +`application:start/{1,2}` function before the `cowboy` +application is started. + +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 + +The `cowboy` application does not define any application +environment configuration parameters. diff --git a/doc/src/manual/cowboy_app.ezdoc b/doc/src/manual/cowboy_app.ezdoc deleted file mode 100644 index 2e2b877..0000000 --- a/doc/src/manual/cowboy_app.ezdoc +++ /dev/null @@ -1,23 +0,0 @@ -::: The Cowboy Application - -Small, fast, modular HTTP server. - -:: Dependencies - -The `cowboy` application uses the Erlang applications `ranch` -for listening and accepting TCP connections, `crypto` for -establishing Websocket connections, and `cowlib` for parsing and -building messages for Web protocols. These dependencies must -be loaded for the `cowboy` application to work. In an embedded -environment this means that they need to be started with the -`application:start/{1,2}` function before the `cowboy` -application is started. - -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 - -The `cowboy` application does not define any application -environment configuration parameters. diff --git a/doc/src/manual/cowboy_handler.asciidoc b/doc/src/manual/cowboy_handler.asciidoc new file mode 100644 index 0000000..fbbe761 --- /dev/null +++ b/doc/src/manual/cowboy_handler.asciidoc @@ -0,0 +1,99 @@ += 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`, +and adds the result of this execution to the environment as +the value `result`, indicating that the request has been +handled and received a response. + +Environment input: + +handler = module():: Handler to be executed. +handler_opts = any():: Options to be passed to the handler. + +Environment output: + +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 + +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:: + 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. + +== Callbacks + +=== init(Req, Opts) -> {ok, Req, State} | {Module, Req, State} | {Module, Req, State, hibernate | Timeout} | {Module, Req, State, Timeout, hibernate} + +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. + +This function can be used to switch to an alternate handler +type by returning the name of the module to be used, along +with a few options. + +For basic handlers this is the function where the response +should be sent. If no response is sent, Cowboy will ensure +that a `204 No Content` response is sent. + +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 + +Reason = any():: Reason for termination. +Req = cowboy_req:req():: The Req object. +State = any():: Handler state. + +Perform any necessary cleanup of the state. + +This callback should release any resource currently in use, +clear any active timer and reset the process to its original +state, as it might be reused for future requests sent on the +same connection. Typical plain HTTP handlers rarely need to +use it. + +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 + +=== terminate(Reason, Req, State, Handler) -> ok + +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. + +This function should always be called at the end of the execution +of a handler, to give it a chance to clean up or perform +miscellaneous operations. diff --git a/doc/src/manual/cowboy_handler.ezdoc b/doc/src/manual/cowboy_handler.ezdoc deleted file mode 100644 index 81615c2..0000000 --- a/doc/src/manual/cowboy_handler.ezdoc +++ /dev/null @@ -1,106 +0,0 @@ -::: cowboy_handler - -The `cowboy_handler` middleware executes the handler passed -through the environment values `handler` and `handler_opts`, -and adds the result of this execution to the environment as -the value `result`, indicating that the request has been -handled and received a response. - -Environment input: - -* handler = module() -* handler_opts = any() - -Environment output: - -* result = ok - -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 - -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 - -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. - -:: 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() - -Process the request. - -This function can be used to switch to an alternate handler -type by returning the name of the module to be used, along -with a few options. - -For basic handlers this is the function where the response -should be sent. If no response is sent, Cowboy will ensure -that a `204 No Content` response is sent. - -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 - -Types: - -* Reason = any() -* Req = cowboy_req:req() -* State = any() - -Perform any necessary cleanup of the state. - -This callback should release any resource currently in use, -clear any active timer and reset the process to its original -state, as it might be reused for future requests sent on the -same connection. Typical plain HTTP handlers rarely need to -use it. - -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 - -: terminate(Reason, Req, State, Handler) -> ok - -Types: - -* Reason = any() -* Req = cowboy_req:req() -* State = any() -* Handler = module() - -Call the optional `terminate/3` callback if it exists. - -This function should always be called at the end of the execution -of a handler, to give it a chance to clean up or perform -miscellaneous operations. diff --git a/doc/src/manual/cowboy_loop.asciidoc b/doc/src/manual/cowboy_loop.asciidoc new file mode 100644 index 0000000..eb17b15 --- /dev/null +++ b/doc/src/manual/cowboy_loop.asciidoc @@ -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. diff --git a/doc/src/manual/cowboy_loop.ezdoc b/doc/src/manual/cowboy_loop.ezdoc deleted file mode 100644 index 79b96f9..0000000 --- a/doc/src/manual/cowboy_loop.ezdoc +++ /dev/null @@ -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. diff --git a/doc/src/manual/cowboy_middleware.asciidoc b/doc/src/manual/cowboy_middleware.asciidoc new file mode 100644 index 0000000..87cd5d2 --- /dev/null +++ b/doc/src/manual/cowboy_middleware.asciidoc @@ -0,0 +1,48 @@ += cowboy_middleware(3) + +== Name + +cowboy_middleware - behaviour for middlewares + +== Description + +The `cowboy_middleware` behaviour defines the interface used +by Cowboy middleware modules. + +Middlewares process the request sequentially in the order they +are configured. + +== Types + +=== env() = [{atom(), any()}] + +The environment variable. + +One is created for every request. It is passed to each +middleware module executed and subsequently returned, +optionally with its contents modified. + +== Callbacks + +=== execute(Req, Env) -> {ok, Req, Env} | {suspend, Module, Function, Args} | {stop, Req} + +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. + +The `ok` return value indicates that everything went well +and that Cowboy should continue processing the request. A +response may or may not have been sent. + +The `suspend` return value will hibernate the process until +an Erlang message is received. Note that when resuming, any +previous stacktrace information will be gone. + +The `stop` return value stops Cowboy from doing any further +processing of the request, even if there are middlewares +that haven't been executed yet. The connection may be left +open to receive more requests from the client. diff --git a/doc/src/manual/cowboy_middleware.ezdoc b/doc/src/manual/cowboy_middleware.ezdoc deleted file mode 100644 index dacaf6c..0000000 --- a/doc/src/manual/cowboy_middleware.ezdoc +++ /dev/null @@ -1,47 +0,0 @@ -::: cowboy_middleware - -The `cowboy_middleware` behaviour defines the interface used -by Cowboy middleware modules. - -Middlewares process the request sequentially in the order they -are configured. - -:: Types - -: env() = [{atom(), any()}] - -The environment variable. - -One is created for every request. It is passed to each -middleware module executed and subsequently returned, -optionally with its contents modified. - -:: Callbacks - -: 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()] - -Execute the middleware. - -The `ok` return value indicates that everything went well -and that Cowboy should continue processing the request. A -response may or may not have been sent. - -The `suspend` return value will hibernate the process until -an Erlang message is received. Note that when resuming, any -previous stacktrace information will be gone. - -The `stop` return value stops Cowboy from doing any further -processing of the request, even if there are middlewares -that haven't been executed yet. The connection may be left -open to receive more requests from the client. diff --git a/doc/src/manual/cowboy_protocol.asciidoc b/doc/src/manual/cowboy_protocol.asciidoc new file mode 100644 index 0000000..e1e7501 --- /dev/null +++ b/doc/src/manual/cowboy_protocol.asciidoc @@ -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. diff --git a/doc/src/manual/cowboy_protocol.ezdoc b/doc/src/manual/cowboy_protocol.ezdoc deleted file mode 100644 index 1d65a5c..0000000 --- a/doc/src/manual/cowboy_protocol.ezdoc +++ /dev/null @@ -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. diff --git a/doc/src/manual/cowboy_req.asciidoc b/doc/src/manual/cowboy_req.asciidoc new file mode 100644 index 0000000..558592b --- /dev/null +++ b/doc/src/manual/cowboy_req.asciidoc @@ -0,0 +1,690 @@ += cowboy_req(3) + +== Name + +cowboy_req - HTTP request and response + +== Description + +The `cowboy_req` module provides functions to access, manipulate +and respond to requests. + +The functions in this module follow patterns for their return types, +based on the kind of function. + +* access: `Value` +* action: `ok | {Result, Req} | {Result, Value, Req}` +* modification: `Req` +* question: `boolean()` + +Whenever `Req` is returned, you must use this returned value and +ignore any previous you may have had. This value contains various +values which are necessary for Cowboy to keep track of the request +and response states. + +All functions which perform an action should only be called once. +This includes reading the request body or replying. Cowboy will +throw an error on the second call when it detects suspicious behavior. + +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 + +=== 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()} +---- + +Request body reading options. + +=== 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 + +The Req object. + +All functions in this module receive a `Req` as argument, +and some of them return a new object labelled `Req2` in +the function descriptions below. + +== Request related exports + +=== binding(Name, Req) -> binding(Name, Req, undefined) + +Alias of `cowboy_req:binding/3`. + +=== 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. + +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}] + +Name = atom():: Binding name. +Value = any():: Binding value. + +Return all bindings. + +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) + +Alias of `cowboy_req:header/3`. + +=== 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 = cowboy:http_headers():: Request headers. + +Return all headers. + +=== host(Req) -> Host + +Host = binary():: Requested host. + +Return the requested host. + +=== host_info(Req) -> HostInfo + +HostInfo = cowboy_router:tokens() | undefined:: Extra tokens for the host. + +Return the extra tokens from matching against `...` during routing. + +=== host_url(Req) -> HostURL + +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 + +Fields = cowboy:fields():: Cookie fields match rules. +Map = map():: Cookie fields matched. + +Match cookies against the given fields. + +Cowboy will only return the cookie values specified in the +fields list, and ignore all others. Fields can be either +the name of the cookie requested; the name along with a +list of constraints; or the name, a list of constraints +and a default value in case the cookie is missing. + +This function will crash if the cookie is missing and no +default value is provided. This function will also crash +if a constraint fails. + +The name of the cookie must be provided as an atom. The +key of the 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. + +=== match_qs(Fields, Req) -> Map + +Fields = cowboy:fields():: Query string fields match rules. +Map = map():: Query string fields matched. + +Match the query string against the given fields. + +Cowboy will only return the query string values specified +in the fields list, and ignore all others. Fields can be +either the key requested; the key along with a list of +constraints; or the key, a list of constraints and a +default value in case the key is missing. + +This function will crash if the key is missing and no +default value is provided. This function will also crash +if a constraint fails. + +The key must be provided as an atom. The key of the +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) + +Alias for `cowboy_req:meta/3`. + +=== 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 = binary():: Request method. + +Return the method. + +Methods are case sensitive. Standard methods are always uppercase. + +=== parse_cookies(Req) -> [{Name, Value}] + +Name = binary():: Cookie name. +Value = binary():: Cookie value. + +Parse and return all cookies. + +Cookie names are case sensitive. + +=== parse_header(Name, Req) -> see below + +Alias of `cowboy_req:parse_header/3`. + +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 parsed value differs depending on the header being parsed. The +following table summarizes the different types returned. + +[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: + +* Type = SubType = Charset = Encoding = LanguageTag = binary() +* AuthType = Expect = OpaqueTag = Unit = binary() +* Params = ContentTypeParams = [{binary(), binary()}] +* Quality = 0..1000 +* AcceptExt = [{binary(), binary()} | binary()] +* Credentials - see below +* Range = {non_neg_integer(), non_neg_integer() | infinity} | neg_integer() + +The cookie names and values, the values of the sec-websocket-protocol +and x-forwarded-for headers, the values in `AcceptExt` and `Params`, +the authorization `Credentials`, the `ExpectValue` and `OpaqueTag` +are case sensitive. All values in `ContentTypeParams` are case sensitive +except the value of the charset parameter, which is case insensitive. +All other values are case insensitive and will be returned as lowercase. + +The headers accept, accept-encoding and cookie headers can return +an empty list. Some other headers are expected to have a value if provided +and may crash if the value is missing. + +The authorization header parsing code currently only supports basic +HTTP authentication. The `Credentials` type is thus `{Username, Password}` +with `Username` and `Password` being `binary()`. + +The range header value `Range` can take three forms: + +* `{From, To}`: from `From` to `To` units +* `{From, infinity}`: everything after `From` units +* `-Final`: the final `Final` units + +An `undefined` tuple will be returned if Cowboy doesn't know how +to parse the requested header. + +=== parse_qs(Req) -> [{Name, Value}] + +Name = binary():: Query string field name. +Value = binary() | true:: Query string field value. + +Return the request's query string as a list of tuples. + +The atom `true` is returned for keys which have no value. +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 = binary():: Requested path. + +Return the requested path. + +=== path_info(Req) -> PathInfo + +PathInfo = cowboy_router:tokens() | undefined:: Extra tokens for the path. + +Return the extra tokens from matching against `...` during routing. + +=== peer(Req) -> Peer + +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 = inet:port_number():: Requested port number. + +Return the request's port. + +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 + +QueryString = binary():: Unprocessed query string. + +Return the request's query string. + +=== set_meta(Name, Value, Req) -> Req2 + +Name = atom():: Metadata name. +Value = any():: Metadata value. + +Set metadata about the request. + +An existing value will be overwritten. + +=== url(Req) -> URL + +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 = cowboy:http_version():: Client's advertised HTTP version. + +Return the HTTP version used for this request. + +== Request body related exports + +=== body(Req) -> body(Req, []) + +Alias of `cowboy_req:body/2`. + +=== 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. + +This function will read a chunk of the request body. If there is +more data to be read after this function call, then a `more` tuple +is returned. Otherwise an `ok` tuple is returned. + +Cowboy will automatically send a `100 Continue` reply if +required. If this behavior is not desirable, it can be disabled +by setting the `continue` option to `false`. + +Cowboy will by default attempt to read up to 8MB of the body, +but in chunks of 1MB. It will use a timeout of 15s per chunk. +All these values can be changed using the `length`, `read_length` +and `read_timeout` options respectively. Note that the size +of the data may not be the same as requested as the decoding +functions may grow or shrink it, and Cowboy makes not attempt +at returning an exact amount. + +Cowboy will properly handle chunked transfer-encoding by +default. If any other transfer-encoding or content-encoding +has been used for the request, custom decoding functions +can be used. The `content_decode` and `transfer_decode` +options allow setting the decode functions manually. + +After the body has been streamed fully, Cowboy will remove +the transfer-encoding header from the Req object, and add +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 + +Length = non_neg_integer() | undefined:: Length of the request body. + +Return the length of the request body. + +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}]) + +Alias of `cowboy_req:body_qs/2`. + +=== 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. + +This function will parse the body assuming the content-type +application/x-www-form-urlencoded, commonly used for the +query string. + +This function calls `body/2` for reading the body, with the +same options it received. By default it will attempt to read +a body of 64KB in one chunk, with a timeout of 5s. If the +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() + +Return whether the request has a body. + +=== part(Req) -> part(Req, [{length, 64000}, {read_length, 64000}, {read_timeout, 5000}]) + +Alias of `cowboy_req:part/2`. + +=== 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. + +Cowboy will skip any data remaining until the beginning of +the next part. This includes the preamble to the multipart +message but also the body of a previous part if it hasn't +been read. Both are skipped automatically when calling this +function. + +The headers returned are MIME headers, NOT HTTP headers. +They can be parsed using the functions from the `cow_multipart` +module. In addition, the `cow_multipart:form_data/1` function +can be used to quickly figure out `multipart/form-data` messages. +It takes the list of headers and returns whether this part is +a simple form field or a file being uploaded. + +Note that once a part has been read, or skipped, it cannot +be read again. + +This function calls `body/2` for reading the body, with the +same options it received. By default it will only read chunks +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, []) + +Alias of `cowboy_req:part_body/2`. + +=== 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. + +This function calls `body/2` for reading the body, with the +same options it received. It uses the same defaults. + +If there are more data to be read from the socket for this +part, the function will return what it could read inside a +`more` tuple. Otherwise, it will return an `ok` tuple. + +Calling this function again after receiving a `more` tuple +will return another chunk of body. The last chunk will be +returned inside an `ok` tuple. + +Note that once the body has been read, fully or partially, +it cannot be read again. + +== Response related exports + +=== chunk(Data, Req) -> ok + +Data = iodata():: Chunk data to be sent. + +Send a chunk of data. + +This function should be called as many times as needed +to send data chunks after calling `chunked_reply/{2,3}`. + +When the method is HEAD, no data will actually be sent. + +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) + +Alias of `cowboy_req:chunked_reply/3`. + +=== 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. + +This function effectively sends the response status line +and headers to the client. + +This function will not send any body set previously. After +this call the handler must use the `chunk/2` function +repeatedly to send the body in as many chunks as needed. + +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. + +This function can only be called once, with the exception +of overriding the response in the `onresponse` hook. + +=== continue(Req) -> ok + +Send a 100 Continue intermediate reply. + +This reply is required before the client starts sending the +body when the request contains the `expect` header with the +`100-continue` value. + +Cowboy will send this automatically when required. However +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 + +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() + +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() + +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) + +Alias of `cowboy_req:reply/3`. + +=== 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. + +This function effectively sends the response status line, +headers and body to the client, in a single send function +call. + +The `reply/2` and `reply/3` functions will send the body +set previously, if any. The `reply/4` function overrides +any body set previously and sends `Body` instead. + +If a body function was set, and `reply/2` or `reply/3` was +used, it will be called before returning. + +No more data can be sent to the client after this function +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 + +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 + +Alias of `cowboy_req:set_resp_body_fun/3`. + +=== 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. + +If a `Length` is provided, it will be sent in the +content-length header in the response. It is recommended +to set the length if it can be known in advance. Otherwise, +the transfer-encoding header will be set to identity. + +This function will only be called if the response is sent +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 + +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. + +This function will only be called if the response is sent +using the `reply/2` or `reply/3` function. + +The fun will receive another fun as argument. This fun is to +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 + +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 + +Name = binary():: Response header name. +Value = iodata():: Response header value. + +Set a response header. + +You should use `set_resp_cookie/4` instead of this function +to set cookies. diff --git a/doc/src/manual/cowboy_req.ezdoc b/doc/src/manual/cowboy_req.ezdoc deleted file mode 100644 index 9b73886..0000000 --- a/doc/src/manual/cowboy_req.ezdoc +++ /dev/null @@ -1,715 +0,0 @@ -::: cowboy_req - -The `cowboy_req` module provides functions to access, manipulate -and respond to requests. - -The functions in this module follow patterns for their return types, -based on the kind of function. - -* access: `Value` -* action: `ok | {Result, Req} | {Result, Value, Req}` -* modification: `Req` -* question: `boolean()` - -Whenever `Req` is returned, you must use this returned value and -ignore any previous you may have had. This value contains various -values which are necessary for Cowboy to keep track of the request -and response states. - -All functions which perform an action should only be called once. -This includes reading the request body or replying. Cowboy will -throw an error on the second call when it detects suspicious behavior. - -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 - -: body_opts() = [{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()}] - -Request body reading options. - -: cookie_opts() = [{max_age, non_neg_integer()} - | {domain, binary()} | {path, binary()} - | {secure, boolean()} | {http_only, boolean()}] - -Cookie options. - -: 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 -the function descriptions below. - -:: Request related exports - -: binding(Name, Req) -> binding(Name, Req, undefined) -: binding(Name, Req, Default) -> Value - -Types: - -* Name = atom() -* Default = any() -* Value = any() | Default - -Return the value for the given binding. - -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}] - -Types: - -* Name = atom() -* Value = any() - -Return all bindings. - -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 - -Types: - -* Name = binary() -* Default = any() -* Value = binary() | Default - -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 - -Types: - -* Headers = cowboy:http_headers() - -Return all headers. - -: host(Req) -> Host - -Types: - -* Host = binary() - -Return the requested host. - -: host_info(Req) -> HostInfo - -Types: - -* HostInfo = cowboy_router:tokens() | undefined - -Return the extra tokens from matching against `...` during routing. - -: host_url(Req) -> HostURL - -Types: - -* HostURL = binary() | undefined - -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 - -Types: - -* Fields = cowboy:fields() -* Map = map() - -Match cookies against the given fields. - -Cowboy will only return the cookie values specified in the -fields list, and ignore all others. Fields can be either -the name of the cookie requested; the name along with a -list of constraints; or the name, a list of constraints -and a default value in case the cookie is missing. - -This function will crash if the cookie is missing and no -default value is provided. This function will also crash -if a constraint fails. - -The name of the cookie must be provided as an atom. The -key of the 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. - -: match_qs(Fields, Req) -> Map - -Types: - -* Fields = cowboy:fields() -* Map = map() - -Match the query string against the given fields. - -Cowboy will only return the query string values specified -in the fields list, and ignore all others. Fields can be -either the key requested; the key along with a list of -constraints; or the key, a list of constraints and a -default value in case the key is missing. - -This function will crash if the key is missing and no -default value is provided. This function will also crash -if a constraint fails. - -The key must be provided as an atom. The key of the -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 - -Types: - -* Name = atom() -* Default = any() -* Value = any() - -Return metadata about the request. - -: method(Req) -> Method - -Types: - -* Method = binary() - -Return the method. - -Methods are case sensitive. Standard methods are always uppercase. - -: parse_cookies(Req) -> [{Name, Value}] - -Types: - -* Name = binary() -* Value = binary() - -Parse and return all cookies. - -Cookie names are case sensitive. - -: parse_header(Name, Req) -> see below -: parse_header(Name, Req, Default) -> ParsedValue | Default - -Types: - -* Name = binary() -* Default = any() -* ParsedValue - see below - -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()]` - -Types for the above table: - -* Type = SubType = Charset = Encoding = LanguageTag = binary() -* AuthType = Expect = OpaqueTag = Unit = binary() -* Params = ContentTypeParams = [{binary(), binary()}] -* Quality = 0..1000 -* AcceptExt = [{binary(), binary()} | binary()] -* Credentials - see below -* Range = {non_neg_integer(), non_neg_integer() | infinity} | neg_integer() - -The cookie names and values, the values of the sec-websocket-protocol -and x-forwarded-for headers, the values in `AcceptExt` and `Params`, -the authorization `Credentials`, the `ExpectValue` and `OpaqueTag` -are case sensitive. All values in `ContentTypeParams` are case sensitive -except the value of the charset parameter, which is case insensitive. -All other values are case insensitive and will be returned as lowercase. - -The headers accept, accept-encoding and cookie headers can return -an empty list. Some other headers are expected to have a value if provided -and may crash if the value is missing. - -The authorization header parsing code currently only supports basic -HTTP authentication. The `Credentials` type is thus `{Username, Password}` -with `Username` and `Password` being `binary()`. - -The range header value `Range` can take three forms: - -* `{From, To}`: from `From` to `To` units -* `{From, infinity}`: everything after `From` units -* `-Final`: the final `Final` units - -An `undefined` tuple will be returned if Cowboy doesn't know how -to parse the requested header. - -: parse_qs(Req) -> [{Name, Value}] - -Types: - -* Name = binary() -* Value = binary() | true - -Return the request's query string as a list of tuples. - -The atom `true` is returned for keys which have no value. -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 - -Types: - -* Path = binary() - -Return the requested path. - -: path_info(Req) -> PathInfo - -Types: - -* PathInfo = cowboy_router:tokens() | undefined - -Return the extra tokens from matching against `...` during routing. - -: peer(Req) -> Peer - -Types: - -* Peer = {inet:ip_address(), inet:port_number()} - -Return the client's IP address and port number. - -: port(Req) -> Port - -Types: - -* Port = inet:port_number() - -Return the request's port. - -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 - -Types: - -* QueryString = binary() - -Return the request's query string. - -: set_meta(Name, Value, Req) -> Req2 - -Types: - -* Name = atom() -* Value = any() - -Set metadata about the request. - -An existing value will be overwritten. - -: url(Req) -> URL - -Types: - -* URL = binary() | undefined - -Return the requested URL. - -This function will always return `undefined` until the -`cowboy_router` middleware has been executed. - -: version(Req) -> Version - -Types: - -* Version = cowboy:http_version() - -Return the HTTP version used for this request. - -:: Request body related exports - -: body(Req) -> body(Req, []) -: body(Req, Opts) -> {ok, Data, Req2} | {more, Data, Req2} - -Types: - -* Opts = [body_opt()] -* Data = binary() -* Reason = atom() - -Read the request body. - -This function will read a chunk of the request body. If there is -more data to be read after this function call, then a `more` tuple -is returned. Otherwise an `ok` tuple is returned. - -Cowboy will automatically send a `100 Continue` reply if -required. If this behavior is not desirable, it can be disabled -by setting the `continue` option to `false`. - -Cowboy will by default attempt to read up to 8MB of the body, -but in chunks of 1MB. It will use a timeout of 15s per chunk. -All these values can be changed using the `length`, `read_length` -and `read_timeout` options respectively. Note that the size -of the data may not be the same as requested as the decoding -functions may grow or shrink it, and Cowboy makes not attempt -at returning an exact amount. - -Cowboy will properly handle chunked transfer-encoding by -default. If any other transfer-encoding or content-encoding -has been used for the request, custom decoding functions -can be used. The `content_decode` and `transfer_decode` -options allow setting the decode functions manually. - -After the body has been streamed fully, Cowboy will remove -the transfer-encoding header from the Req object, and add -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 - -Types: - -* Length = non_neg_integer() | undefined - -Return the length of the request body. - -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} - -Types: - -* Opts = [body_opt()] -* Name = binary() -* Value = binary() | true -* Reason = chunked | badlength | atom() - -Return the request body as a list of tuples. - -This function will parse the body assuming the content-type -application/x-www-form-urlencoded, commonly used for the -query string. - -This function calls `body/2` for reading the body, with the -same options it received. By default it will attempt to read -a body of 64KB in one chunk, with a timeout of 5s. If the -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() - -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} - -Types: - -* Opts = [body_opt()] -* Headers = cow_multipart:headers() - -Read the headers for the next part of the multipart message. - -Cowboy will skip any data remaining until the beginning of -the next part. This includes the preamble to the multipart -message but also the body of a previous part if it hasn't -been read. Both are skipped automatically when calling this -function. - -The headers returned are MIME headers, NOT HTTP headers. -They can be parsed using the functions from the `cow_multipart` -module. In addition, the `cow_multipart:form_data/1` function -can be used to quickly figure out `multipart/form-data` messages. -It takes the list of headers and returns whether this part is -a simple form field or a file being uploaded. - -Note that once a part has been read, or skipped, it cannot -be read again. - -This function calls `body/2` for reading the body, with the -same options it received. By default it will only read chunks -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} - -Types: - -* Opts = [body_opt()] -* Data = binary() - -Read the body of the current part of the multipart message. - -This function calls `body/2` for reading the body, with the -same options it received. It uses the same defaults. - -If there are more data to be read from the socket for this -part, the function will return what it could read inside a -`more` tuple. Otherwise, it will return an `ok` tuple. - -Calling this function again after receiving a `more` tuple -will return another chunk of body. The last chunk will be -returned inside an `ok` tuple. - -Note that once the body has been read, fully or partially, -it cannot be read again. - -:: Response related exports - -: chunk(Data, Req) -> ok - -Types: - -* Data = iodata() -* Reason = atom() - -Send a chunk of data. - -This function should be called as many times as needed -to send data chunks after calling `chunked_reply/{2,3}`. - -When the method is HEAD, no data will actually be sent. - -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 - -Types: - -* StatusCode = cowboy:http_status() -* Headers = cowboy:http_headers() - -Send a response using chunked transfer-encoding. - -This function effectively sends the response status line -and headers to the client. - -This function will not send any body set previously. After -this call the handler must use the `chunk/2` function -repeatedly to send the body in as many chunks as needed. - -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. - -This function can only be called once, with the exception -of overriding the response in the `onresponse` hook. - -: continue(Req) -> ok - -Types: - -* Reason = atom() - -Send a 100 Continue intermediate reply. - -This reply is required before the client starts sending the -body when the request contains the `expect` header with the -`100-continue` value. - -Cowboy will send this automatically when required. However -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 - -Types: - -* Name = binary() - -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() - -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() - -Types: - -* Name = binary() - -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 - -Types: - -* StatusCode = cowboy:http_status() -* Headers = cowboy:http_headers() -* Body = iodata() - -Send a response. - -This function effectively sends the response status line, -headers and body to the client, in a single send function -call. - -The `reply/2` and `reply/3` functions will send the body -set previously, if any. The `reply/4` function overrides -any body set previously and sends `Body` instead. - -If a body function was set, and `reply/2` or `reply/3` was -used, it will be called before returning. - -No more data can be sent to the client after this function -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 - -Types: - -* Body = iodata() - -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 - -Types: - -* Fun = fun((Socket, Transport) -> ok) -* Socket = inet:socket() -* Transport = module() -* Length = non_neg_integer() - -Set a fun for sending the response body. - -If a `Length` is provided, it will be sent in the -content-length header in the response. It is recommended -to set the length if it can be known in advance. Otherwise, -the transfer-encoding header will be set to identity. - -This function will only be called if the response is sent -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 - -Types: - -* Fun = fun((ChunkFun) -> ok) -* ChunkFun = fun((iodata()) -> ok) - -Set a fun for sending the response body using chunked transfer-encoding. - -This function will only be called if the response is sent -using the `reply/2` or `reply/3` function. - -The fun will receive another fun as argument. This fun is to -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 - -Types: - -* Name = iodata() -* Value = iodata() -* Opts = cookie_opts() - -Set a cookie in the response. - -Cookie names are case sensitive. - -: set_resp_header(Name, Value, Req) -> Req2 - -Types: - -* Name = binary() -* Value = iodata() - -Set a response header. - -You should use `set_resp_cookie/4` instead of this function -to set cookies. diff --git a/doc/src/manual/cowboy_rest.asciidoc b/doc/src/manual/cowboy_rest.asciidoc new file mode 100644 index 0000000..6380d41 --- /dev/null +++ b/doc/src/manual/cowboy_rest.asciidoc @@ -0,0 +1,529 @@ += cowboy_rest(3) + +== Name + +cowboy_rest - REST handlers + +== Description + +The `cowboy_rest` module implements REST semantics on top of +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 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 + +charset = binary():: + Negotiated charset. + + + This value may not be defined if no charset was negotiated. + +language = binary():: + Negotiated language. + + + This value may not be defined if no language was negotiated. + +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`. + +== Terminate reasons + +The following values may be received as the terminate reason +in the optional `terminate/3` callback. + +normal:: + 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. + +== Callbacks + +=== Callback(Req, State) -> {Value, Req, State} | {stop, Req, State} + +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 +not defined, and more general information on when the +callback is called and what its intended use is. + +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 + +=== allowed_methods + +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 + +Methods:: POST +Value type:: boolean() +Default value:: true + +Return whether POST is allowed when the resource doesn't exist. + +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 + +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. + +The list must be ordered in order of preference. + +If the accept-charset header was not sent, the first charset +in the list will be selected. Otherwise Cowboy will select +the most appropriate charset from the list. + +The chosen charset will be set in the `Req` object as the meta +value `charset`. + +While charsets are case insensitive, this callback is expected +to return them as lowercase binary. + +=== content_types_accepted + +Methods:: POST, PUT, PATCH +Value type:: [{binary() | {Type, SubType, Params}, AcceptResource}] +Default behavior:: Crash if undefined. + +With types: + +* Type = SubType = binary() +* Params = '*' | [{binary(), binary()}] +* AcceptResource = atom() + +Return the list of content-types the resource accepts. + +The list must be ordered in order of preference. + +Each content-type can be given either as a binary string or as +a tuple containing the type, subtype and parameters. + +Cowboy will select the most appropriate content-type from the list. +If any parameter is acceptable, then the tuple form should be used +with parameters set to `'*'`. If the parameters value is set to `[]` +only content-type values with no parameters will be accepted. All +parameter values are treated in a case sensitive manner except the +`charset` parameter, if present, which is case insensitive. + +This function will be called for POST, PUT and PATCH requests. +It is entirely possible to define different callbacks for different +methods if the handling of the request differs. Simply verify +what the method is with `cowboy_req:method/1` and return a +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 +Default behavior:: Crash if undefined. + +Process the request body. + +This function should create or update the resource with the +information contained in the request body. This information +may be full or partial depending on the request method. + +If the request body was processed successfully, `true` must +be returned. If the request method is POST, `{true, URL}` may +be returned instead, and Cowboy will redirect the client to +the location of the newly created resource. + +If a response body must be sent, the appropriate media-type, charset +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 + +Methods:: GET, HEAD, POST, PUT, PATCH, DELETE +Value type:: [{binary() | {Type, SubType, Params}, ProvideResource}] +Default value:: `[{{<<"text">>, <<"html">>, '*'}, to_html}]` + +With types: + +* Type = SubType = binary() +* Params = '*' | [{binary(), binary()}] +* ProvideResource = atom() + +Return the list of content-types the resource provides. + +The list must be ordered in order of preference. + +Each content-type can be given either as a binary string or as +a tuple containing the type, subtype and parameters. + +Cowboy will select the most appropriate content-type from the list. +If any parameter is acceptable, then the tuple form should be used +with parameters set to `'*'`. If the parameters value is set to `[]` +only content-type values with no parameters will be accepted. All +parameter values are treated in a case sensitive manner except the +`charset` parameter, if present, which is case insensitive. + +The `ProvideResource` value is the name of the callback that will +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} +Default behavior:: Crash if undefined. + +Return the response body. + +The response body may be provided directly or through a fun. +If a fun tuple is returned, the appropriate `set_resp_body_fun` +function will be called. Please refer to the documentation for +these functions for more information about the types. + +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 + +Methods:: DELETE +Value type:: boolean() +Default value:: true + +Return whether the delete action has been completed. + +This function should return `false` if there is no guarantee +that the resource gets deleted immediately from the system, +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 + +Methods:: DELETE +Value type:: boolean() +Default value:: false + +Delete the resource. + +The value returned indicates if the action was successful, +regardless of whether the resource is immediately deleted +from the system. + +=== expires + +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 + +Methods:: all +Value type:: boolean() +Default value:: false + +Return whether access to the resource is forbidden. + +A `403 Forbidden` response will be sent if this +function returns `true`. This status code means that +access is forbidden regardless of authentication, +and that the request shouldn't be repeated. + +=== generate_etag + +Methods:: GET, HEAD, POST, PUT, PATCH, DELETE +Value type:: binary() | {weak | strong, binary()} +Default value:: undefined + +Return the entity tag of the resource. + +This value will be sent as the value of the etag header. + +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 + +Methods:: all +Value type:: true | {false, AuthHeader} +Default value:: true + +With types: + +* AuthHead = iodata() + +Return whether the user is authorized to perform the action. + +This function should be used to perform any necessary +authentication of the user before attempting to perform +any action on the resource. + +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 + +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 + +Methods:: all +Value type:: [binary()] +Default value:: `[<<"GET">>, <<"HEAD">>, <<"POST">>, <<"PUT">>, <<"PATCH">>, <<"DELETE">>, <<"OPTIONS">>]` + +Return the list of known methods. + +The full list of methods known by the server should be +returned, regardless of their use in the resource. + +The default value lists the methods Cowboy knows and +implement in `cowboy_rest`. + +Methods are case sensitive. Standard methods are always uppercase. + +=== languages_provided + +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. + +The list must be ordered in order of preference. + +If the accept-language header was not sent, the first language +in the list will be selected. Otherwise Cowboy will select +the most appropriate language from the list. + +The chosen language will be set in the `Req` object as the meta +value `language`. + +While languages are case insensitive, this callback is expected +to return them as lowercase binary. + +=== last_modified + +Methods:: GET, HEAD, POST, PUT, PATCH, DELETE +Value type:: calendar:datetime() +Default value:: undefined + +Return the date of last modification of the resource. + +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 + +Methods:: all +Value type:: boolean() +Default value:: false + +Return whether the request is malformed. + +Cowboy has already performed all the necessary checks +by the time this function is called, so few resources +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 + +Methods:: GET, HEAD, POST, PUT, PATCH, DELETE +Value type:: {true, URL} | false +Default value:: false + +With types: + +* URL = iodata() + +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 + +Methods:: GET, HEAD, POST, PATCH, DELETE +Value type:: {true, URL} | false +Default value:: false + +With types: + +* URL = iodata() + +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 + +Methods:: GET, HEAD, POST, PUT, PATCH, DELETE +Value type:: boolean() +Default value:: false + +Return whether there are multiple representations of the resource. + +This function should be used to inform the client if there +are different representations of the resource, for example +different content-type. If this function returns `true`, +the response body should include information about these +different representations using `cowboy_req:set_resp_body/2`. +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 + +Methods:: OPTIONS +Value type:: ok +Default value:: ok + +Handle a request for information. + +The response should inform the client the communication +options available for this resource. + +By default, Cowboy will send a `200 OK` response with the +allow header set. + +=== previously_existed + +Methods:: GET, HEAD, POST, PATCH, DELETE +Value type:: boolean() +Default value:: false + +Return whether the resource existed previously. + +=== resource_exists + +Methods:: GET, HEAD, POST, PUT, PATCH, DELETE +Value type:: boolean() +Default value:: true + +Return whether the resource exists. + +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 + +Methods:: all +Value type:: boolean() +Default value:: true + +Return whether the service is available. + +This function can be used to test that all relevant backend +systems are up and able to handle requests. + +A `503 Service Unavailable` response will be sent if this +function returns `false`. + +=== uri_too_long + +Methods:: all +Value type:: boolean() +Default value:: false + +Return whether the requested URI is too long. + +Cowboy has already performed all the necessary checks +by the time this function is called, so few resources +are expected to implement it. + +A `414 Request-URI Too Long` response will be sent if this +function returns `true`. + +=== valid_content_headers + +Methods:: all +Value type:: boolean() +Default value:: true + +Return whether the content-* headers are valid. + +This also applies to the transfer-encoding header. This +function must return `false` for any unknown content-* +headers, or if the headers can't be understood. The +function `cowboy_req:parse_header/2` can be used to +quickly check the headers can be parsed. + +A `501 Not Implemented` response will be sent if this +function returns `false`. + +=== valid_entity_length + +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 + +Methods:: GET, HEAD, POST, PUT, PATCH, DELETE +Value type:: [binary()] +Default value:: [] + +Return the list of headers that affect the representation of the resource. + +These request headers return the same resource but with different +parameters, like another language or a different content-type. + +Cowboy will automatically add the accept, accept-language and +accept-charset headers to the list if the respective functions +were defined in the resource. + +This operation is performed right before the `resource_exists/2` +callback. All responses past that point will contain the vary +header which holds this list. diff --git a/doc/src/manual/cowboy_rest.ezdoc b/doc/src/manual/cowboy_rest.ezdoc deleted file mode 100644 index 35131c7..0000000 --- a/doc/src/manual/cowboy_rest.ezdoc +++ /dev/null @@ -1,536 +0,0 @@ -::: cowboy_rest - -The `cowboy_rest` module implements REST semantics on top of -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. - -All other callbacks are optional, though some may become -required depending on the return value of previous callbacks. - -:: Meta values - -: charset - -Type: binary() - -Negotiated charset. - -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 - -The following values may be received as the terminate reason -in the optional `terminate/3` callback. - -: normal - -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. - -:: 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 - -Please see the REST callbacks description below for details -on the `Value` type, the default value if the callback is -not defined, and more general information on when the -callback is called and what its intended use is. - -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 - -: allowed_methods - -* 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 - -* Methods: POST -* Value type: boolean() -* Default value: true - -Return whether POST is allowed when the resource doesn't exist. - -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 - -* Methods: GET, HEAD, POST, PUT, PATCH, DELETE -* Value type: [binary()] -* Skip to the next step if undefined - -Return the list of charsets the resource provides. - -The list must be ordered in order of preference. - -If the accept-charset header was not sent, the first charset -in the list will be selected. Otherwise Cowboy will select -the most appropriate charset from the list. - -The chosen charset will be set in the `Req` object as the meta -value `charset`. - -While charsets are case insensitive, this callback is expected -to return them as lowercase binary. - -: content_types_accepted - -* Methods: POST, PUT, PATCH -* No default - -Types: - -* Value = [{binary() | {Type, SubType, Params}, AcceptResource}] -* Type = SubType = binary() -* Params = '*' | [{binary(), binary()}] -* AcceptResource = atom() - -Return the list of content-types the resource accepts. - -The list must be ordered in order of preference. - -Each content-type can be given either as a binary string or as -a tuple containing the type, subtype and parameters. - -Cowboy will select the most appropriate content-type from the list. -If any parameter is acceptable, then the tuple form should be used -with parameters set to `'*'`. If the parameters value is set to `[]` -only content-type values with no parameters will be accepted. All -parameter values are treated in a case sensitive manner except the -`charset` parameter, if present, which is case insensitive. - -This function will be called for POST, PUT and PATCH requests. -It is entirely possible to define different callbacks for different -methods if the handling of the request differs. Simply verify -what the method is with `cowboy_req:method/1` and return a -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 - -Process the request body. - -This function should create or update the resource with the -information contained in the request body. This information -may be full or partial depending on the request method. - -If the request body was processed successfully, `true` must -be returned. If the request method is POST, `{true, URL}` may -be returned instead, and Cowboy will redirect the client to -the location of the newly created resource. - -If a response body must be sent, the appropriate media-type, charset -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 - -* Methods: GET, HEAD, POST, PUT, PATCH, DELETE -* Default value: [{{<<"text">>, <<"html">>, '*'}, to_html}] - -Types: - -* Value = [{binary() | {Type, SubType, Params}, ProvideResource}] -* Type = SubType = binary() -* Params = '*' | [{binary(), binary()}] -* ProvideResource = atom() - -Return the list of content-types the resource provides. - -The list must be ordered in order of preference. - -Each content-type can be given either as a binary string or as -a tuple containing the type, subtype and parameters. - -Cowboy will select the most appropriate content-type from the list. -If any parameter is acceptable, then the tuple form should be used -with parameters set to `'*'`. If the parameters value is set to `[]` -only content-type values with no parameters will be accepted. All -parameter values are treated in a case sensitive manner except the -`charset` parameter, if present, which is case insensitive. - -The `ProvideResource` value is the name of the callback that will -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 - -Return the response body. - -The response body may be provided directly or through a fun. -If a fun tuple is returned, the appropriate `set_resp_body_fun` -function will be called. Please refer to the documentation for -these functions for more information about the types. - -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 - -* Methods: DELETE -* Value type: boolean() -* Default value: true - -Return whether the delete action has been completed. - -This function should return `false` if there is no guarantee -that the resource gets deleted immediately from the system, -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 - -* Methods: DELETE -* Value type: boolean() -* Default value: false - -Delete the resource. - -The value returned indicates if the action was successful, -regardless of whether the resource is immediately deleted -from the system. - -: expires - -* 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 - -* Methods: all -* Value type: boolean() -* Default value: false - -Return whether access to the resource is forbidden. - -A `403 Forbidden` response will be sent if this -function returns `true`. This status code means that -access is forbidden regardless of authentication, -and that the request shouldn't be repeated. - -: generate_etag - -* Methods: GET, HEAD, POST, PUT, PATCH, DELETE -* Value type: binary() | {weak | strong, binary()} -* Default value: undefined - -Return the entity tag of the resource. - -This value will be sent as the value of the etag header. - -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 - -* Methods: all -* Value type: true | {false, AuthHeader} -* Default value: true - -Types: - -* AuthHead = iodata() - -Return whether the user is authorized to perform the action. - -This function should be used to perform any necessary -authentication of the user before attempting to perform -any action on the resource. - -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 - -* 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 - -* Methods: all -* Value type: [binary()] -* Default value: [<<"GET">>, <<"HEAD">>, <<"POST">>, <<"PUT">>, <<"PATCH">>, <<"DELETE">>, <<"OPTIONS">>] - -Return the list of known methods. - -The full list of methods known by the server should be -returned, regardless of their use in the resource. - -The default value lists the methods Cowboy knows and -implement in `cowboy_rest`. - -Methods are case sensitive. Standard methods are always uppercase. - -: languages_provided - -* Methods: GET, HEAD, POST, PUT, PATCH, DELETE -* Value type: [binary()] -* Skip to the next step if undefined - -Return the list of languages the resource provides. - -The list must be ordered in order of preference. - -If the accept-language header was not sent, the first language -in the list will be selected. Otherwise Cowboy will select -the most appropriate language from the list. - -The chosen language will be set in the `Req` object as the meta -value `language`. - -While languages are case insensitive, this callback is expected -to return them as lowercase binary. - -: last_modified - -* Methods: GET, HEAD, POST, PUT, PATCH, DELETE -* Value type: calendar:datetime() -* Default value: undefined - -Return the date of last modification of the resource. - -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 - -* Methods: all -* Value type: boolean() -* Default value: false - -Return whether the request is malformed. - -Cowboy has already performed all the necessary checks -by the time this function is called, so few resources -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 - -* Methods: GET, HEAD, POST, PUT, PATCH, DELETE -* Value type: {true, URL} | false -* Default value: false - -Types: - -* URL = iodata() - -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 - -* Methods: GET, HEAD, POST, PATCH, DELETE -* Value type: {true, URL} | false -* Default value: false - -Types: - -* URL = iodata() - -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 - -* Methods: GET, HEAD, POST, PUT, PATCH, DELETE -* Value type: boolean() -* Default value: false - -Return whether there are multiple representations of the resource. - -This function should be used to inform the client if there -are different representations of the resource, for example -different content-type. If this function returns `true`, -the response body should include information about these -different representations using `cowboy_req:set_resp_body/2`. -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 - -* Methods: OPTIONS -* Value type: ok -* Default value: ok - -Handle a request for information. - -The response should inform the client the communication -options available for this resource. - -By default, Cowboy will send a `200 OK` response with the -allow header set. - -: previously_existed - -* Methods: GET, HEAD, POST, PATCH, DELETE -* Value type: boolean() -* Default value: false - -Return whether the resource existed previously. - -: resource_exists - -* Methods: GET, HEAD, POST, PUT, PATCH, DELETE -* Value type: boolean() -* Default value: true - -Return whether the resource exists. - -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 - -* Methods: all -* Value type: boolean() -* Default value: true - -Return whether the service is available. - -This function can be used to test that all relevant backend -systems are up and able to handle requests. - -A `503 Service Unavailable` response will be sent if this -function returns `false`. - -: uri_too_long - -* Methods: all -* Value type: boolean() -* Default value: false - -Return whether the requested URI is too long. - -Cowboy has already performed all the necessary checks -by the time this function is called, so few resources -are expected to implement it. - -A `414 Request-URI Too Long` response will be sent if this -function returns `true`. - -: valid_content_headers - -* Methods: all -* Value type: boolean() -* Default value: true - -Return whether the content-* headers are valid. - -This also applies to the transfer-encoding header. This -function must return `false` for any unknown content-* -headers, or if the headers can't be understood. The -function `cowboy_req:parse_header/2` can be used to -quickly check the headers can be parsed. - -A `501 Not Implemented` response will be sent if this -function returns `false`. - -: valid_entity_length - -* 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 - -* Methods: GET, HEAD, POST, PUT, PATCH, DELETE -* Value type: [binary()] -* Default value: [] - -Return the list of headers that affect the representation of the resource. - -These request headers return the same resource but with different -parameters, like another language or a different content-type. - -Cowboy will automatically add the accept, accept-language and -accept-charset headers to the list if the respective functions -were defined in the resource. - -This operation is performed right before the `resource_exists/2` -callback. All responses past that point will contain the vary -header which holds this list. diff --git a/doc/src/manual/cowboy_router.asciidoc b/doc/src/manual/cowboy_router.asciidoc new file mode 100644 index 0000000..9142930 --- /dev/null +++ b/doc/src/manual/cowboy_router.asciidoc @@ -0,0 +1,56 @@ += 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. +It uses the dispatch rules compiled from the routes given +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 + +dispatch = dispatch_rules():: Dispatch table. + +=== Environment output + +handler = module():: Handler module. +handler_opts = any():: Handler options. + +== Types + +=== bindings() = [{atom(), binary()}] + +List of bindings found during routing. + +=== dispatch_rules() - opaque to the user + +Rules for dispatching request used by Cowboy. + +=== routes() = [{Host, Paths} | {Host, cowboy:fields(), Paths}] + +With types: + +* Host = Path = '_' | iodata() +* Paths = [{Path, Handler, Opts} | {Path, cowboy:fields(), Handler, HandlerOpts}] +* Handler = module() +* 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()] + +List of host_info and path_info tokens found during routing. + +== Exports + +=== compile(routes()) -> dispatch_rules() + +Compile the routes for use by Cowboy. diff --git a/doc/src/manual/cowboy_router.ezdoc b/doc/src/manual/cowboy_router.ezdoc deleted file mode 100644 index 8d45e67..0000000 --- a/doc/src/manual/cowboy_router.ezdoc +++ /dev/null @@ -1,55 +0,0 @@ -::: cowboy_router - -The `cowboy_router` middleware maps the requested host and -path to the handler to be used for processing the request. -It uses the dispatch rules compiled from the routes given -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: - -* dispatch = dispatch_rules() - -Environment output: - -* handler = module() -* handler_opts = any() - -:: Types - -: bindings() = [{atom(), binary()}] - -List of bindings found during routing. - -: dispatch_rules() - opaque to the user - -Rules for dispatching request used by Cowboy. - -: routes() = [{Host, Paths} | {Host, cowboy:fields(), Paths}] - -Types: - -* Host = Path = '_' | iodata() -* Paths = [{Path, Handler, Opts} | {Path, cowboy:fields(), Handler, Opts}] -* Handler = module() -* Opts = any() - -Human readable list of routes mapping hosts and paths to handlers. - -The syntax for routes is defined in the user guide. - -: tokens() = [binary()] - -List of host_info and path_info tokens found during routing. - -:: Exports - -: compile(Routes) -> Dispatch - -Types: - -* Routes = routes() -* Dispatch = dispatch_rules() - -Compile the routes for use by Cowboy. diff --git a/doc/src/manual/cowboy_spdy.asciidoc b/doc/src/manual/cowboy_spdy.asciidoc new file mode 100644 index 0000000..b0dcb70 --- /dev/null +++ b/doc/src/manual/cowboy_spdy.asciidoc @@ -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. diff --git a/doc/src/manual/cowboy_spdy.ezdoc b/doc/src/manual/cowboy_spdy.ezdoc deleted file mode 100644 index e88de20..0000000 --- a/doc/src/manual/cowboy_spdy.ezdoc +++ /dev/null @@ -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. diff --git a/doc/src/manual/cowboy_static.asciidoc b/doc/src/manual/cowboy_static.asciidoc new file mode 100644 index 0000000..658d93b --- /dev/null +++ b/doc/src/manual/cowboy_static.asciidoc @@ -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. diff --git a/doc/src/manual/cowboy_static.ezdoc b/doc/src/manual/cowboy_static.ezdoc deleted file mode 100644 index a827832..0000000 --- a/doc/src/manual/cowboy_static.ezdoc +++ /dev/null @@ -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()}]}} diff --git a/doc/src/manual/cowboy_sub_protocol.asciidoc b/doc/src/manual/cowboy_sub_protocol.asciidoc new file mode 100644 index 0000000..8146a44 --- /dev/null +++ b/doc/src/manual/cowboy_sub_protocol.asciidoc @@ -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. diff --git a/doc/src/manual/cowboy_sub_protocol.ezdoc b/doc/src/manual/cowboy_sub_protocol.ezdoc deleted file mode 100644 index ee57beb..0000000 --- a/doc/src/manual/cowboy_sub_protocol.ezdoc +++ /dev/null @@ -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. diff --git a/doc/src/manual/cowboy_websocket.asciidoc b/doc/src/manual/cowboy_websocket.asciidoc new file mode 100644 index 0000000..ac9016b --- /dev/null +++ b/doc/src/manual/cowboy_websocket.asciidoc @@ -0,0 +1,143 @@ += 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 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 +as necessary until the Websocket connection is closed. + +The `init/2` callback can be used to negotiate Websocket protocol +extensions with the client. It is highly recommended to return a +timeout value from this 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. + +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 + +websocket_compress = boolean():: + Whether a websocket compression extension in in use. + +websocket_version = 7 | 8 | 13:: + The version of the Websocket protocol being used. + +== 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 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, Code, Payload}:: + The remote endpoint closed the connection with the given + `Code` and `Payload` as the reason. + +stop:: + The handler requested to close the connection, either by returning + a `stop` tuple or by sending a `close` frame. + +timeout:: + The connection has been closed due to inactivity. The timeout + value can be configured from `init/2`. + +{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, 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) -> 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} + +InFrame = {text | binary | ping | pong, binary()} +Req = cowboy_req:req() +State = any() +OutFrame = cow_ws:frame() +---- + +Handle the data received from the Websocket connection. + +This function will be called every time data is received +from the Websocket connection. + +The `stop` return value can be used to close the +connection. A close reply will also result in the connection +being closed. + +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) -> 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} + +Info = any() +Req = cowboy_req:req() +State = any() +OutFrame = cow_ws:frame() +---- + +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 close the +connection. A close reply will also result in the connection +being closed. + +The `hibernate` option will hibernate the process until +it receives another message or new data from the Websocket +connection. diff --git a/doc/src/manual/cowboy_websocket.ezdoc b/doc/src/manual/cowboy_websocket.ezdoc deleted file mode 100644 index 2519dba..0000000 --- a/doc/src/manual/cowboy_websocket.ezdoc +++ /dev/null @@ -1,149 +0,0 @@ -::: cowboy_websocket - -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. - -The `websocket_handle/3` and `websocket_info/3` callbacks are -specific to Websocket handlers and will be called as many times -as necessary until the Websocket connection is closed. - -The `init/2` callback can be used to negotiate Websocket protocol -extensions with the client. It is highly recommended to return a -timeout value from this 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. - -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 - -: websocket_compress - -Type: true | false - -Whether a websocket compression extension in in use. - -: websocket_version - -Type: 7 | 8 | 13 - -The version of the Websocket protocol being used. - -:: 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 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, Code, Payload} - -The remote endpoint closed the connection with the given -`Code` and `Payload` as the reason. - -: stop - -The handler requested to close the connection, either by returning -a `stop` tuple or by sending a `close` frame. - -: timeout - -The connection has been closed due to inactivity. The timeout -value can be configured from `init/2`. - -: {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, 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} - | {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() - -Handle the data received from the Websocket connection. - -This function will be called every time data is received -from the Websocket connection. - -The `stop` return value can be used to close the -connection. A close reply will also result in the connection -being closed. - -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} - | {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() - -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 close the -connection. A close reply will also result in the connection -being closed. - -The `hibernate` option will hibernate the process until -it receives another message or new data from the Websocket -connection. diff --git a/doc/src/manual/http_status_codes.asciidoc b/doc/src/manual/http_status_codes.asciidoc new file mode 100644 index 0000000..172272a --- /dev/null +++ b/doc/src/manual/http_status_codes.asciidoc @@ -0,0 +1,157 @@ += 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 + +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 + +This is the status code sent when switching to the +Websocket protocol. + +== 200 OK + +This status code is sent by `cowboy_rest`. + +== 201 Created + +This status code is sent by `cowboy_rest`. + +== 202 Accepted + +This status code is sent by `cowboy_rest`. + +== 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 + +This status code is sent by `cowboy_rest`. + +== 301 Moved Permanently + +This status code is sent by `cowboy_rest`. + +== 303 See Other + +This status code is sent by `cowboy_rest`. + +== 304 Not Modified + +This status code is sent by `cowboy_rest`. + +== 307 Temporary Redirect + +This status code is sent by `cowboy_rest`. + +== 400 Bad Request + +Cowboy will send this status code for any of the +following reasons: + +* Too many empty lines were sent before the request. +* The request-line could not be parsed. +* Too many headers were sent. +* A header name was too long. +* A header value was too long. +* The host header was missing from an HTTP/1.1 request. +* The host header could not be parsed. +* The requested host was not found. +* The requested path could not be parsed. +* The accept header could not be parsed when using REST. +* REST under normal conditions. +* A Websocket upgrade failed. + +== 401 Unauthorized + +This status code is sent by `cowboy_rest`. + +== 403 Forbidden + +This status code is sent by `cowboy_rest`. + +== 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 + +This status code is sent by `cowboy_rest`. + +== 406 Not Acceptable + +This status code is sent by `cowboy_rest`. + +== 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 + +This status code is sent by `cowboy_rest`. + +== 410 Gone + +This status code is sent by `cowboy_rest`. + +== 412 Precondition Failed + +This status code is sent by `cowboy_rest`. + +== 413 Request Entity Too Large + +This status code is sent by `cowboy_rest`. + +== 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 + +This status code is sent by `cowboy_rest`. + +== 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 + +This status code is sent by `cowboy_rest`. + +== 503 Service Unavailable + +This status code is sent by `cowboy_rest`. + +== 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 +client and the connection is closed. diff --git a/doc/src/manual/http_status_codes.ezdoc b/doc/src/manual/http_status_codes.ezdoc deleted file mode 100644 index 4d24b20..0000000 --- a/doc/src/manual/http_status_codes.ezdoc +++ /dev/null @@ -1,151 +0,0 @@ -::: HTTP status codes - -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 - -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 - -This is the status code sent when switching to the -Websocket protocol. - -: 200 OK - -This status code is sent by `cowboy_rest`. - -: 201 Created - -This status code is sent by `cowboy_rest`. - -: 202 Accepted - -This status code is sent by `cowboy_rest`. - -: 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 - -This status code is sent by `cowboy_rest`. - -: 301 Moved Permanently - -This status code is sent by `cowboy_rest`. - -: 303 See Other - -This status code is sent by `cowboy_rest`. - -: 304 Not Modified - -This status code is sent by `cowboy_rest`. - -: 307 Temporary Redirect - -This status code is sent by `cowboy_rest`. - -: 400 Bad Request - -Cowboy will send this status code for any of the -following reasons: - -* Too many empty lines were sent before the request. -* The request-line could not be parsed. -* Too many headers were sent. -* A header name was too long. -* A header value was too long. -* The host header was missing from an HTTP/1.1 request. -* The host header could not be parsed. -* The requested host was not found. -* The requested path could not be parsed. -* The accept header could not be parsed when using REST. -* REST under normal conditions. -* A Websocket upgrade failed. - -: 401 Unauthorized - -This status code is sent by `cowboy_rest`. - -: 403 Forbidden - -This status code is sent by `cowboy_rest`. - -: 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 - -This status code is sent by `cowboy_rest`. - -: 406 Not Acceptable - -This status code is sent by `cowboy_rest`. - -: 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 - -This status code is sent by `cowboy_rest`. - -: 410 Gone - -This status code is sent by `cowboy_rest`. - -: 412 Precondition Failed - -This status code is sent by `cowboy_rest`. - -: 413 Request Entity Too Large - -This status code is sent by `cowboy_rest`. - -: 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 - -This status code is sent by `cowboy_rest`. - -: 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 - -This status code is sent by `cowboy_rest`. - -: 503 Service Unavailable - -This status code is sent by `cowboy_rest`. - -: 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 -client and the connection is closed. diff --git a/doc/src/manual/index.ezdoc b/doc/src/manual/index.ezdoc deleted file mode 100644 index 133a341..0000000 --- a/doc/src/manual/index.ezdoc +++ /dev/null @@ -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 -- cgit v1.2.3