Skip to content

Commit e1797cc

Browse files
authored
feat(lambda-http): add example with tower_http crate (#425)
* feat(lambda-runtime): add all features for tower re-export * feat(lambda-http): add CORS layer example * revert(lambda-http): revert changes to LambdaRequest and Body types
1 parent d9cf7e8 commit e1797cc

File tree

4 files changed

+32
-1
lines changed

4 files changed

+32
-1
lines changed

lambda-http/Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -30,3 +30,4 @@ serde_urlencoded = "0.7.0"
3030
log = "^0.4"
3131
maplit = "1.0"
3232
tokio = { version = "1.0", features = ["macros"] }
33+
tower-http = { version = "0.2", features = ["cors"] }

lambda-http/examples/hello-cors.rs

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
use http::Method;
2+
use lambda_http::{service_fn, tower::ServiceBuilder, Body, Error, IntoResponse, Request, RequestExt, Response};
3+
use tower_http::cors::{Any, CorsLayer};
4+
5+
#[tokio::main]
6+
async fn main() -> Result<(), Error> {
7+
// Define a layer to inject CORS headers
8+
let cors_layer = CorsLayer::new()
9+
.allow_methods(vec![Method::GET, Method::POST])
10+
.allow_origin(Any);
11+
12+
let handler = ServiceBuilder::new()
13+
// Add the CORS layer to the service
14+
.layer(cors_layer)
15+
.service(service_fn(func));
16+
17+
lambda_http::run(handler).await?;
18+
Ok(())
19+
}
20+
21+
async fn func(event: Request) -> Result<Response<Body>, Error> {
22+
Ok(match event.query_string_parameters().get("first_name") {
23+
Some(first_name) => format!("Hello, {}!", first_name).into_response(),
24+
_ => Response::builder()
25+
.status(400)
26+
.body("Empty first name".into())
27+
.expect("failed to render response"),
28+
})
29+
}

lambda-integration-tests/src/bin/logs-trait.rs

+1
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ impl MyLogsProcessor {
3434
impl Service<Vec<LambdaLog>> for MyLogsProcessor {
3535
type Response = ();
3636
type Error = Error;
37+
#[allow(clippy::type_complexity)]
3738
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
3839

3940
fn poll_ready(&mut self, _cx: &mut core::task::Context<'_>) -> core::task::Poll<Result<(), Self::Error>> {

lambda-runtime/Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ bytes = "1.0"
2323
http = "0.2"
2424
async-stream = "0.3"
2525
tracing = { version = "0.1", features = ["log"] }
26-
tower = { version = "0.4", features = ["util"] }
26+
tower = { version = "0.4", features = ["full"] }
2727
tokio-stream = "0.1.2"
2828
lambda_runtime_api_client = { version = "0.5", path = "../lambda-runtime-api-client" }
2929

0 commit comments

Comments
 (0)