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