Attribute Macro mendes_macros::handler
source · #[handler]
Expand description
Implement a request handler wrapper for the annotated function
The attribute takes allowed methods as its arguments:
/// This handler will immediately return a `405 Method not allowed`
/// error for all request methods other than `GET`
#[handler(GET)]
fn hello(_: &App) -> Result<Response<String>, Error> {
Ok(Response::builder()
.status(StatusCode::OK)
.body("Hello, world".into())
.unwrap())
}
The first argument of the function must be a reference to an implementer of
the Application
trait (the implementor may also be wrapped in an Arc
).
All unannotated arguments must be of types that implement the FromContext
trait for the Application
type used in the first argument. This includes
&http::request::Parts
, the Request
’s headers and any number of types
that can represent a path component from the URI:
&[u8]
for the bytes representation of the path componentCow<'_, str>
String
- Numeric types (
i8
,u8
,i16
,u16
, …,isize
,usize
,f32
,f64
) bool
andchar
- If the
hyper
feature is enabled,hyper::body::Body
(only ifApplication::RequestBody
is alsoBody
)
Each of these types can be wrapped in Option
for optional path components.
Additionally, there are two attributes that may be used on handler arguments:
#[rest]
: a&str
representing the part of the request path not yet consumed by routing#[query]
: a type that implementsDeserialize
, and will be used to deserialize the URI query
This macro will generate a module that contains a call()
function mirroring
the original function, and you may rely on this behavior (for example, for testing).
mod hello {
use super::*;
/// ... some internals hidden ...
pub(super) async fn call(_: &App) -> Result<Response<Body>, Error> {
Ok(Response::builder()
.status(StatusCode::OK)
.body("Hello, world".into())
.unwrap())
}
}