Skip to main content

try_get_attribute

Attribute Macro try_get_attribute 

Source
#[try_get_attribute]
Expand description

Extracts a specific attribute value into a variable wrapped in Option type.

This attribute macro retrieves a specific attribute by key and makes it available as a typed Option variable from the request context. The extracted value is wrapped in an Option type to safely handle cases where the attribute may not exist.

§Usage

use hyperlane::*;
use hyperlane_macros::*;
use serde::{Deserialize, Serialize};

const TEST_ATTRIBUTE_KEY: &str = "test_attribute_key";

#[derive(Clone, Debug, Deserialize, Serialize)]
struct TestData {
    name: String,
    age: u32,
}

#[route("/try_get_attribute")]
struct Attribute;

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

    #[response_body(&format!("request attribute: {request_try_get_attribute:?}"))]
    #[try_get_attribute(TEST_ATTRIBUTE_KEY => request_try_get_attribute: TestData)]
    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status { Status::Continue }
}

impl Attribute {
    #[try_get_attribute(TEST_ATTRIBUTE_KEY => request_try_get_attribute: TestData)]
    async fn attribute_with_ref_self(&self, stream: &mut Stream, ctx: &mut Context) -> Status { Status::Continue }
}

#[try_get_attribute(TEST_ATTRIBUTE_KEY => request_try_get_attribute: TestData)]
async fn standalone_attribute_handler(stream: &mut Stream, ctx: &mut Context) -> Status { Status::Continue }

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

§Multi-Parameter Usage

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

#[route("/try_get_attribute")]
struct MultiAttr;

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

    #[response_body(&format!("attrs: {attr1:?}, {attr2:?}"))]
    #[try_get_attribute("key1" => attr1: String, "key2" => attr2: i32)]
    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status { Status::Continue }
}

The macro accepts multiple key => variable_name: Type tuples separated by commas.