Attribute Macro route

Source
#[route]
Expand description

Defines a route handler for Lambda HTTP events.

This attribute macro registers a function as a route handler in the router registry. The function will be called when an incoming request matches the specified path and method. Route handlers are registered at compile time, ensuring zero runtime overhead for route setup.

§Arguments

  • path - The URL path to match (required). Supports path parameters like {param_name}
  • method - The HTTP method to match (optional, defaults to “GET”)
  • module - The router module name (optional, defaults to internal name)

§Function Signature

The handler function must have exactly one parameter of type RouteContext:

#[route(path = "/hello")]
async fn handle_hello(ctx: RouteContext) -> Result<Value, Error> {
    Ok(json!({ "message": "Hello, World!" }))
}

§Path Parameters

Path parameters are defined using curly braces and are available in the RouteContext.params:

  • /users/{id} - Matches /users/123 and provides id = "123"
  • /posts/{category}/{slug} - Matches /posts/tech/my-post

§Examples

Route with path parameters and custom method:

use lambda_lw_http_router::{route, define_router};
use aws_lambda_events::apigw::ApiGatewayV2httpRequest;
use serde_json::{json, Value};
use lambda_runtime::Error;

#[derive(Clone)]
struct AppState {
    // your state fields here
}

define_router!(event = ApiGatewayV2httpRequest, state = AppState);

#[route(path = "/users/{id}", method = "POST", state = AppState)]
async fn create_user(ctx: RouteContext) -> Result<Value, Error> {
    let user_id = ctx.params.get("id").unwrap();
    Ok(json!({ "created": user_id }))
}