route

Attribute Macro route 

Source
#[route]
Expand description

Convert the provided route into a struct that implements Route.

The macro should get an endpoint that the route will handle. This can have variables which can be passed to the route function.

The route function will need a parameter named request and can optionally have parameters specified by the endpoint. Internally, the route function is async, so it does not matter whether the route function is marked async.

The endpoint can contain four kinds of segments:

  • segments: these are of the format /a/b.
  • params: these are of the format /a/:b.
  • named wildcards: these are of the format /a/*b.
  • unnamed wildcards: these are of the format /a/*.

Only params and named wildcards can be passed to the route function. By default, a parameter is of type &str. You can however specify any type that impls FromStr. The param will be parsed, and if it fails, a 51 File not found will be sent.

Note that currently, it is not possible to have mutliple routes with the same endpoint, but different parameter types.

ยงExamples

use gemfra::{
    response::Response,
    request::Request,
    error::AnyError,
};
use gemfra_codegen::route;

#[route("/foo/bar")]
async fn no_params(_request: Request) -> Result<Response, AnyError> {
    Ok(Response::success("text/gemini", "# Hello World!"))
}

#[route("/foo/:my_var")]
async fn default_param(_request: Request, my_var: &str) -> Result<Response, AnyError> {
    Ok(Response::success("text/gemini", format!("# Hello {my_var}")))
}

#[route("/foo/:year")]
async fn typed_param(_request: Request, year: i32) -> Result<Response, AnyError> {
    // Any non i32 value for year will result in a `51 File not found`
    Ok(Response::success("text/gemini", format!("# The year is {year}")))
}