Skip to main content

try_get_route_param

Attribute Macro try_get_route_param 

Source
#[try_get_route_param]
Expand description

Extracts a specific route parameter into a variable wrapped in Option type.

This attribute macro retrieves a specific route parameter by key and makes it available as an Option variable. Route parameters are extracted from the URL path segments and wrapped in an Option type to safely handle cases where the parameter may not exist.

§Usage

use hyperlane::*;
use hyperlane_macros::*;

#[route("/try_get_route_param/:test")]
struct RouteParam;

impl ServerHook for RouteParam {
    async fn new(_: &mut Stream, _: &mut Context) -> Self {
        Self
    }

    #[response_body(&format!("route param: {request_route_param:?}"))]
    #[try_get_route_param("test" => request_route_param)]
    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status { Status::Continue }
}

impl RouteParam {
    #[try_get_route_param("test" => request_route_param)]
    async fn route_param_with_ref_self(&self, stream: &mut Stream, ctx: &mut Context) -> Status { Status::Continue }
}

#[try_get_route_param("test" => request_route_param)]
async fn standalone_route_param_handler(stream: &mut Stream, ctx: &mut Context) -> Status { Status::Continue }

The macro accepts a key-to-variable mapping in the format "key" => variable_name. The variable will be available as an Option<String> in the function scope.

§Multi-Parameter Usage

use hyperlane::*;
use hyperlane_macros::*;

#[route("/multi_param/:id/:name")]
struct MultiParam;

impl ServerHook for MultiParam {
    async fn new(_: &mut Stream, _: &mut Context) -> Self {
        Self
    }

    #[response_body(&format!("id: {id:?}, name: {name:?}"))]
    #[try_get_route_param("id" => id, "name" => name)]
    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status { Status::Continue }
}

The macro accepts multiple "key" => variable_name pairs separated by commas.