Skip to content

Commit 2aa9da4

Browse files
authored
ADD: axum middleware example (#785)
1 parent 355627e commit 2aa9da4

File tree

3 files changed

+72
-0
lines changed

3 files changed

+72
-0
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
[package]
2+
name = "http-axum-middleware"
3+
version = "0.1.0"
4+
edition = "2021"
5+
6+
[dependencies]
7+
axum = "0.7"
8+
lambda_http = { path = "../../lambda-http", default-features = false, features = [
9+
"apigw_rest",
10+
] }
11+
lambda_runtime = { path = "../../lambda-runtime" }
12+
serde_json = "1.0"
13+
tokio = { version = "1", features = ["macros"] }
14+
tracing = { version = "0.1", features = ["log"] }
15+
tracing-subscriber = { version = "0.3", default-features = false, features = [
16+
"fmt",
17+
] }
18+
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# AWS Lambda Function example
2+
3+
## Build & Deploy
4+
5+
1. Install [cargo-lambda](https://github.com/cargo-lambda/cargo-lambda#installation)
6+
2. Build the function with `cargo lambda build --release`
7+
3. Deploy the function to AWS Lambda with `cargo lambda deploy --iam-role YOUR_ROLE`
8+
9+
## Build for ARM 64
10+
11+
Build the function with `cargo lambda build --release --arm64`
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
//! This example demonstrates how [axum middleware](https://docs.rs/axum/latest/axum/middleware/index.html)
2+
//! can be implemented.
3+
//!
4+
//! To test this:
5+
//! ```sh
6+
//! # start the local server
7+
//! cargo lambda watch
8+
//! # Then send through an example request
9+
//! cargo lambda invoke --data-example apigw-request
10+
//! ```
11+
12+
use axum::{response::Json, routing::post, Router};
13+
use lambda_http::request::RequestContext::ApiGatewayV1;
14+
use lambda_http::{run, Error};
15+
use serde_json::{json, Value};
16+
17+
// Sample middleware that logs the request id
18+
async fn mw_sample(req: axum::extract::Request, next: axum::middleware::Next) -> impl axum::response::IntoResponse {
19+
let context = req.extensions().get::<lambda_http::request::RequestContext>();
20+
if let Some(ApiGatewayV1(ctx)) = context {
21+
tracing::info!("RequestId = {:?}", ctx.request_id);
22+
}
23+
next.run(req).await
24+
}
25+
26+
async fn handler_sample(body: Json<Value>) -> Json<Value> {
27+
Json(json!({ "echo": *body }))
28+
}
29+
30+
#[tokio::main]
31+
async fn main() -> Result<(), Error> {
32+
tracing_subscriber::fmt()
33+
.with_max_level(tracing::Level::INFO)
34+
.with_target(false)
35+
.without_time()
36+
.init();
37+
38+
let app = Router::new()
39+
.route("/testStage/hello/world", post(handler_sample))
40+
.route_layer(axum::middleware::from_fn(mw_sample));
41+
42+
run(app).await
43+
}

0 commit comments

Comments
 (0)