Struct RouteContext

Source
pub struct RouteContext<State, E>
where State: Clone,
{ pub path: String, pub method: String, pub params: HashMap<String, String>, pub state: Arc<State>, pub event: E, pub lambda_context: Context, pub route_pattern: String, }
Expand description

Context passed to route handlers containing request information and application state.

This struct provides access to request details, path parameters, application state, and Lambda execution context. It is passed to every route handler and provides methods for accessing OpenTelemetry span attributes.

§Examples

use aws_lambda_events::apigw::ApiGatewayV2httpRequest;
use lambda_lw_http_router_core::{RouteContext, Router};
use serde_json::Value;
use lambda_runtime::Error;
use serde_json::json;

async fn handle_user(ctx: RouteContext<(), ApiGatewayV2httpRequest>) -> Result<Value, Error> {
    // Get path parameters
    let user_id = ctx.get_param("id").unwrap_or_else(||"default".to_string());
     
    // Access request details
    let method = ctx.method();
    let path = ctx.path();
     
    // Set span attributes
    ctx.set_otel_attribute("user.id", user_id.clone());
     
    Ok(json!({ "id": user_id }))
}

Fields§

§path: String

The full request path

§method: String

The HTTP method (GET, POST, etc.)

§params: HashMap<String, String>

Path parameters extracted from the URL (e.g., {id} -> “123”)

§state: Arc<State>

Application state shared across all requests

§event: E

The original Lambda event

§lambda_context: Context

Lambda execution context

§route_pattern: String

The route template pattern (e.g., “/quote/{id}”)

Implementations§

Source§

impl<State, E> RouteContext<State, E>
where State: Clone,

Source

pub fn path(&self) -> &str

Returns the full request path of the current request.

§Examples
async fn handler(ctx: RouteContext<AppState, ApiGatewayV2httpRequest>) {
    let path = ctx.path();
    assert_eq!(path, "/users/123/profile");
}
Source

pub fn method(&self) -> &str

Returns the HTTP method of the current request (e.g., “GET”, “POST”).

§Examples
async fn handler(ctx: RouteContext<AppState, ApiGatewayV2httpRequest>) {
    let method = ctx.method();
    assert_eq!(method, "POST");
}
Source

pub fn state(&self) -> &State

Returns a reference to the shared application state.

The state is shared across all request handlers and can be used to store application-wide data like database connections or configuration.

§Examples
#[derive(Clone)]
struct AppState {
    api_key: String,
}

async fn handler(ctx: RouteContext<AppState, ApiGatewayV2httpRequest>) {
    let api_key = &ctx.state().api_key;
    // Use the API key for authentication
}
Source

pub fn event(&self) -> &E

Returns a reference to the original Lambda event.

This provides access to the raw event data from AWS Lambda, which can be useful for accessing event-specific fields not exposed through the router interface.

§Examples
async fn handler(ctx: RouteContext<AppState, ApiGatewayV2httpRequest>) {
    let raw_event = ctx.event();
    if let Some(body) = &raw_event.body {
        // Process the raw request body
    }
}
Source

pub fn lambda_context(&self) -> &Context

Returns a reference to the Lambda execution context.

The Lambda context contains metadata about the current execution environment, such as the request ID, function name, and remaining execution time.

§Examples
async fn handler(ctx: RouteContext<AppState, ApiGatewayV2httpRequest>) {
    let request_id = &ctx.lambda_context().request_id;
    let deadline = ctx.lambda_context().deadline;
}
Source

pub fn route_pattern(&self) -> &str

Returns the route pattern that matched this request.

The route pattern is the original path template with parameter placeholders, such as “/users/{id}/profile”.

§Examples
async fn handler(ctx: RouteContext<AppState, ApiGatewayV2httpRequest>) {
    let pattern = ctx.route_pattern();
    assert_eq!(pattern, "/users/{id}/profile");
}
Source

pub fn get_param(&self, name: &str) -> Option<String>

Returns a path parameter by name, if it exists.

Path parameters are extracted from the URL based on the route pattern. For example, if the route pattern is “/users/{id}” and the URL is “/users/123”, then get_param("id") will return Some("123").

§Arguments
  • name - The name of the path parameter to retrieve
§Examples
async fn get_user(ctx: RouteContext<AppState, ApiGatewayV2httpRequest>) -> serde_json::Value {
    let user_id = ctx.get_param("id").unwrap_or_default();
    json!({ "id": user_id })
}
Source

pub fn get_param_or(&self, name: &str, default: &str) -> String

Returns a path parameter by name, or a default value if it doesn’t exist.

§Examples
async fn get_user(ctx: RouteContext<AppState, ApiGatewayV2httpRequest>) -> serde_json::Value {
    let user_id = ctx.get_param_or("id", "default");
    json!({ "id": user_id })
}
Source

pub fn get_param_or_empty(&self, name: &str) -> String

Returns a path parameter by name, or an empty string if it doesn’t exist.

§Examples
async fn get_user(ctx: RouteContext<AppState, ApiGatewayV2httpRequest>) -> serde_json::Value {
    let user_id = ctx.get_param_or_empty("id");
    json!({ "id": user_id })
}
Source

pub fn params(&self) -> &HashMap<String, String>

Returns a reference to all path parameters.

This method returns a HashMap containing all path parameters extracted from the URL based on the route pattern.

§Examples
async fn handler(ctx: RouteContext<AppState, ApiGatewayV2httpRequest>) -> serde_json::Value {
    let params = ctx.params();
    json!({
        "user_id": params.get("user_id"),
        "post_id": params.get("post_id")
    })
}
Source

pub fn set_otel_attribute( &self, key: impl Into<Key>, value: impl Into<Value>, ) -> &RouteContext<State, E>

Sets a single attribute on the current OpenTelemetry span.

This method allows you to add custom attributes to the current span for better observability and tracing.

§Arguments
  • key - The attribute key
  • value - The attribute value (supports strings, numbers, and booleans)
§Returns

Returns a reference to self for method chaining

§Examples
async fn handler(ctx: RouteContext<AppState, ApiGatewayV2httpRequest>) {
    ctx.set_otel_attribute("user.id", "123")
       .set_otel_attribute("request.size", 1024)
       .set_otel_attribute("cache.hit", true);
}
Source

pub fn set_otel_span_kind(&self, kind: &str) -> &RouteContext<State, E>

Sets the OpenTelemetry span kind for the current span.

The span kind describes the relationship between the span and its parent. Common values include:

  • “SERVER” for server-side request handling
  • “CLIENT” for outbound requests
  • “PRODUCER” for message publishing
  • “CONSUMER” for message processing
  • “INTERNAL” for internal operations
§Arguments
  • kind - The span kind to set
§Returns

Returns a reference to self for method chaining

§Examples
async fn handler(ctx: RouteContext<AppState, ApiGatewayV2httpRequest>) {
    ctx.set_otel_span_kind("SERVER")
       .set_otel_attribute("request.id", "abc-123");
}

Trait Implementations§

Source§

impl<State, E> Clone for RouteContext<State, E>
where State: Clone, E: Clone,

Source§

fn clone(&self) -> RouteContext<State, E>

Returns a duplicate of the value. Read more
1.0.0 · Source§

const fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<State, E> Debug for RouteContext<State, E>
where State: Debug + Clone, E: Debug,

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<State, E> Freeze for RouteContext<State, E>
where E: Freeze,

§

impl<State, E> RefUnwindSafe for RouteContext<State, E>
where E: RefUnwindSafe, State: RefUnwindSafe,

§

impl<State, E> Send for RouteContext<State, E>
where E: Send, State: Sync + Send,

§

impl<State, E> Sync for RouteContext<State, E>
where E: Sync, State: Sync + Send,

§

impl<State, E> Unpin for RouteContext<State, E>
where E: Unpin,

§

impl<State, E> UnwindSafe for RouteContext<State, E>
where E: UnwindSafe, State: RefUnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FutureExt for T

Source§

fn with_context(self, otel_cx: Context) -> WithContext<Self>

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
Source§

fn with_current_context(self) -> WithContext<Self>

Attaches the current Context to this type, returning a WithContext wrapper. Read more
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more