|
| 1 | +use std::convert::TryInto; |
| 2 | +use std::future::Future; |
| 3 | +use std::pin::Pin; |
| 4 | + |
| 5 | +use crate::http::Error; |
| 6 | +use crate::{Body, Server}; |
| 7 | + |
| 8 | +impl<State> lambda_http::Handler for Server<State> |
| 9 | +where |
| 10 | + State: Clone + Send + Sync + 'static, |
| 11 | +{ |
| 12 | + type Error = Error; |
| 13 | + type Response = lambda_http::Response<lambda_http::Body>; |
| 14 | + type Fut = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send + 'static>>; |
| 15 | + |
| 16 | + fn call(&self, event: lambda_http::Request, context: lambda_http::Context) -> Self::Fut { |
| 17 | + let server = self.clone(); |
| 18 | + Box::pin(async move { |
| 19 | + let (parts, body) = event.into_parts(); |
| 20 | + let body = match body { |
| 21 | + lambda_http::Body::Empty => Body::empty(), |
| 22 | + lambda_http::Body::Text(text) => Body::from_string(text), |
| 23 | + lambda_http::Body::Binary(bytes) => Body::from_bytes(bytes), |
| 24 | + }; |
| 25 | + let mut req: http_types::Request = http::Request::from_parts(parts, body).try_into()?; |
| 26 | + |
| 27 | + req.ext_mut().insert(context); |
| 28 | + let res: http_types::Response = server.respond(req).await?; |
| 29 | + |
| 30 | + let res: http::Response<Body> = res.try_into()?; |
| 31 | + let (parts, body) = res.into_parts(); |
| 32 | + let body = match body.is_empty() { |
| 33 | + Some(true) => lambda_http::Body::Empty, |
| 34 | + _ => lambda_http::Body::Binary(body.into_bytes().await?) |
| 35 | + }; |
| 36 | + Ok(http::Response::from_parts(parts, body)) |
| 37 | + }) |
| 38 | + } |
| 39 | +} |
0 commit comments