Skip to main content

try_get_request_cookie

Attribute Macro try_get_request_cookie 

Source
#[try_get_request_cookie]
Expand description

Extracts a specific cookie value or all cookies into a variable wrapped in Option type.

This attribute macro supports two syntaxes:

  1. cookie(key => variable_name) - Extract a specific cookie value by key, wrapped in Option
  2. cookie(variable_name) - Extract all cookies as a raw string, wrapped in Option

ยงUsage

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

#[route("/cookie")]
struct Cookie;

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

    #[response_body(&format!("Session cookie: {session_cookie1_option:?}, {session_cookie2_option:?}"))]
    #[try_get_request_cookie("test1" => session_cookie1_option, "test2" => session_cookie2_option)]
    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status { Status::Continue }
}

impl Cookie {
    #[response_body(&format!("Session cookie: {session_cookie1_option:?}, {session_cookie2_option:?}"))]
    #[try_get_request_cookie("test1" => session_cookie1_option, "test2" => session_cookie2_option)]
    async fn request_cookie_with_ref_self(&self, stream: &mut Stream, ctx: &mut Context) -> Status { Status::Continue }
}

#[response_body(&format!("Session cookie: {session_cookie1_option:?}, {session_cookie2_option:?}"))]
#[try_get_request_cookie("test1" => session_cookie1_option, "test2" => session_cookie2_option)]
async fn standalone_request_cookie_handler(stream: &mut Stream, ctx: &mut Context) -> Status { Status::Continue }

For specific cookie extraction, the variable will be available as Option<String>. For all cookies extraction, the variable will be available as String.