|
| 1 | +//! This is an example function that leverages the Lambda Rust runtime's HTTP support |
| 2 | +//! and the [axum](https://docs.rs/axum/latest/axum/index.html) web framework. The |
| 3 | +//! runtime HTTP support is backed by the [tower::Service](https://docs.rs/tower-service/0.3.2/tower_service/trait.Service.html) |
| 4 | +//! trait. Axum applications are also backed by the `tower::Service` trait. That means |
| 5 | +//! that it is fairly easy to build an Axum application and pass the resulting `Service` |
| 6 | +//! implementation to the Lambda runtime to run as a Lambda function. By using Axum instead |
| 7 | +//! of a basic `tower::Service` you get web framework niceties like routing, request component |
| 8 | +//! extraction, validation, etc. |
| 9 | +
|
| 10 | +use lambda_http::{ |
| 11 | + run, |
| 12 | + Error, |
| 13 | +}; |
| 14 | +use axum::{ |
| 15 | + extract::Path, |
| 16 | + response::Json, |
| 17 | + Router, |
| 18 | + routing::{get, post}, |
| 19 | +}; |
| 20 | +use serde_json::{Value, json}; |
| 21 | + |
| 22 | +async fn root() -> Json<Value> { |
| 23 | + Json(json!({ "msg": "I am GET /" })) |
| 24 | +} |
| 25 | + |
| 26 | +async fn get_foo() -> Json<Value> { |
| 27 | + Json(json!({ "msg": "I am GET /foo" })) |
| 28 | +} |
| 29 | + |
| 30 | +async fn post_foo() -> Json<Value> { |
| 31 | + Json(json!({ "msg": "I am POST /foo" })) |
| 32 | +} |
| 33 | + |
| 34 | +async fn post_foo_name(Path(name): Path<String>) -> Json<Value> { |
| 35 | + Json(json!({ "msg": format!("I am POST /foo/:name, name={name}") })) |
| 36 | +} |
| 37 | + |
| 38 | +#[tokio::main] |
| 39 | +async fn main() -> Result<(), Error> { |
| 40 | + tracing_subscriber::fmt() |
| 41 | + .with_max_level(tracing::Level::INFO) |
| 42 | + // disabling time is handy because CloudWatch will add the ingestion time. |
| 43 | + .without_time() |
| 44 | + .init(); |
| 45 | + |
| 46 | + let app = Router::new() |
| 47 | + .route("/", get(root)) |
| 48 | + .route("/foo", get(get_foo).post(post_foo)) |
| 49 | + .route("/foo/:name", post(post_foo_name)); |
| 50 | + |
| 51 | + run(app).await |
| 52 | +} |
0 commit comments