Skip to main content

try_get_request_header

Attribute Macro try_get_request_header 

Source
#[try_get_request_header]
Expand description

Extracts a specific HTTP request header into a variable wrapped in Option type.

This attribute macro retrieves a specific HTTP request header by name and makes it available as an Option variable. Header values are extracted from the request request headers collection and wrapped in an Option type to safely handle cases where the header may not exist.

ยงUsage

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

#[route("/try_get_request_header")]
struct RequestHeader;

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

    #[prologue_macros(
        try_get_request_header(HOST => try_get_request_header),
        response_body(&format!("request header: {try_get_request_header:?}")),
        send
    )]
    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status { Status::Continue }
}

impl RequestHeader {
    #[try_get_request_header(HOST => try_get_request_header)]
    async fn request_header_with_ref_self(&self, stream: &mut Stream, ctx: &mut Context) -> Status { Status::Continue }
}

#[try_get_request_header(HOST => try_get_request_header)]
async fn standalone_request_header_handler(stream: &mut Stream, ctx: &mut Context) -> Status { Status::Continue }

The macro accepts a request header name-to-variable mapping in the format HEADER_NAME => variable_name or "Header-Name" => variable_name. The variable will be available as an Option<RequestHeadersValueItem>.