request_body_json

Attribute Macro request_body_json 

Source
#[request_body_json]
Expand description

Parses the request body as JSON into a specified variable and type with panic on parsing failure.

This attribute macro extracts and deserializes the request body content as JSON into a variable with the specified type. The body content is parsed as JSON using serde. If the request body does not exist or JSON parsing fails, the function will panic with an error message.

§Usage

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

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

#[route("/request_body_json")]
struct RequestBodyJson;

impl ServerHook for RequestBodyJson {
    async fn new(_ctx: &Context) -> Self {
        Self
    }

    #[response_body(&format!("request data: {request_data_result:?}"))]
    #[request_body_json(request_data_result: TestData)]
    async fn handle(self, ctx: &Context) {}
}

impl RequestBodyJson {
    #[request_body_json(request_data_result: TestData)]
    async fn request_body_json_with_ref_self(&self, ctx: &Context) {}
}

#[request_body_json(request_data_result: TestData)]
async fn standalone_request_body_json_handler(ctx: &Context) {}

§Multi-Parameter Usage

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

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

#[derive(Debug, Serialize, Deserialize, Clone)]
struct Config {
    debug: bool,
}

#[route("/request_body_json")]
struct TestData;

impl ServerHook for TestData {
    async fn new(_ctx: &Context) -> Self {
        Self
    }

    #[response_body(&format!("user: {user:?}, config: {config:?}"))]
    #[request_body_json(user: User, config: Config)]
    async fn handle(self, ctx: &Context) {}
}

The macro accepts one or more variable_name: Type pairs separated by commas. Each variable will be available in the function scope as a Result<Type, serde_json::Error>.

§Panics

This macro will panic if the request body does not exist or JSON parsing fails.