Skip to content

Adding String and Vec Body Types #33

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 9 commits into from
Nov 11, 2018
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
42 changes: 42 additions & 0 deletions examples/body_types.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#![feature(async_await, futures_api)]

#[macro_use]
extern crate serde_derive;
use tide::body;

#[derive(Serialize, Deserialize, Clone, Debug)]
struct Message {
author: Option<String>,
contents: String,
}

async fn echo_string(msg: body::Str) -> String {
println!("String: {}", msg.0);
format!("{}", msg.0)
}

async fn echo_string_lossy(msg: body::StrLossy) -> String {
println!("String: {}", msg.0);
format!("{}", msg.0)
}

async fn echo_vec(msg: body::Bytes) -> String {
println!("Vec<u8>: {:?}", msg.0);

String::from_utf8(msg.0).unwrap()
}

async fn echo_json(msg: body::Json<Message>) -> body::Json<Message> {
println!("JSON: {:?}", msg.0);

msg
}

fn main() {
let mut app = tide::App::new(());
app.at("/echo/string").post(echo_string);
app.at("/echo/string_lossy").post(echo_string_lossy);
app.at("/echo/vec").post(echo_vec);
app.at("/echo/json").post(echo_json);
app.serve("127.0.0.1:8000");
}
1 change: 1 addition & 0 deletions rustfmt.toml
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
edition = "2018"
tab_spaces = 4
61 changes: 58 additions & 3 deletions src/body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,11 @@ impl Into<hyper::Body> for Body {
}
}

// Small utility function to return a stamped error when we cannot parse a request body
fn mk_err<T>(_: T) -> Response {
StatusCode::BAD_REQUEST.into_response()
}

/// A wrapper for json (de)serialization of bodies.
///
/// This type is usable both as an extractor (argument to an endpoint) and as a response
Expand All @@ -126,9 +131,6 @@ impl<T: Send + serde::de::DeserializeOwned + 'static, S: 'static> Extract<S> for
let mut body = std::mem::replace(req.body_mut(), Body::empty());
FutureObj::new(Box::new(
async move {
fn mk_err<T>(_: T) -> Response {
StatusCode::BAD_REQUEST.into_response()
}
let body = await!(body.read_to_vec()).map_err(mk_err)?;
let json: T = serde_json::from_slice(&body).map_err(mk_err)?;
Ok(Json(json))
Expand All @@ -147,3 +149,56 @@ impl<T: 'static + Send + serde::Serialize> IntoResponse for Json<T> {
.unwrap()
}
}

pub struct Str(pub String);

impl<S: 'static> Extract<S> for Str {
type Fut = FutureObj<'static, Result<Self, Response>>;

fn extract(data: &mut S, req: &mut Request, params: &RouteMatch<'_>) -> Self::Fut {
let mut body = std::mem::replace(req.body_mut(), Body::empty());

FutureObj::new(Box::new(
async move {
let body = await!(body.read_to_vec().map_err(mk_err))?;
let string = String::from_utf8(body).map_err(mk_err)?;
Ok(Str(string))
},
))
}
}

pub struct StrLossy(pub String);

impl<S: 'static> Extract<S> for StrLossy {
type Fut = FutureObj<'static, Result<Self, Response>>;

fn extract(data: &mut S, req: &mut Request, params: &RouteMatch<'_>) -> Self::Fut {
let mut body = std::mem::replace(req.body_mut(), Body::empty());

FutureObj::new(Box::new(
async move {
let body = await!(body.read_to_vec().map_err(mk_err))?;
let string = String::from_utf8_lossy(&body).to_string();
Ok(StrLossy(string))
},
))
}
}

pub struct Bytes(pub Vec<u8>);

impl<S: 'static> Extract<S> for Bytes {
type Fut = FutureObj<'static, Result<Self, Response>>;

fn extract(data: &mut S, req: &mut Request, params: &RouteMatch<'_>) -> Self::Fut {
let mut body = std::mem::replace(req.body_mut(), Body::empty());

FutureObj::new(Box::new(
async move {
let body = await!(body.read_to_vec().map_err(mk_err))?;
Ok(Bytes(body))
},
))
}
}