Skip to content

feat(lambda-http): implement http_body::Body for lambda_http::body #406

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 22, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions lambda-http/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ maintenance = { status = "actively-developed" }

[dependencies]
base64 = "0.13.0"
bytes = "1"
http = "0.2"
http-body = "0.4"
lambda_runtime = { path = "../lambda-runtime", version = "0.4.1" }
serde = { version = "^1", features = ["derive"] }
serde_json = "^1"
Expand Down
45 changes: 43 additions & 2 deletions lambda-http/src/body.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
//! Provides an ALB / API Gateway oriented request and response body entity interface

use std::{borrow::Cow, ops::Deref};

use crate::Error;
use base64::display::Base64Display;
use bytes::Bytes;
use http_body::{Body as HttpBody, SizeHint};
use serde::ser::{Error as SerError, Serialize, Serializer};
use std::{borrow::Cow, mem::take, ops::Deref, pin::Pin, task::Poll};

/// Representation of http request and response bodies as supported
/// by API Gateway and ALBs.
Expand Down Expand Up @@ -175,6 +177,45 @@ impl<'a> Serialize for Body {
}
}

impl HttpBody for Body {
type Data = Bytes;
type Error = Error;

fn poll_data(
self: Pin<&mut Self>,
_cx: &mut std::task::Context<'_>,
) -> Poll<Option<Result<Self::Data, Self::Error>>> {
let body = take(self.get_mut());
Poll::Ready(match body {
Body::Empty => None,
Body::Text(s) => Some(Ok(s.into())),
Body::Binary(b) => Some(Ok(b.into())),
})
}

fn poll_trailers(
self: Pin<&mut Self>,
_cx: &mut std::task::Context<'_>,
) -> Poll<Result<Option<http::HeaderMap>, Self::Error>> {
Poll::Ready(Ok(None))
}

fn is_end_stream(&self) -> bool {
match self {
Body::Empty => true,
_ => false,
}
}

fn size_hint(&self) -> SizeHint {
match self {
Body::Empty => SizeHint::default(),
Body::Text(ref s) => SizeHint::with_exact(s.len() as u64),
Body::Binary(ref b) => SizeHint::with_exact(b.len() as u64),
}
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down