Skip to content

Commit

Permalink
Add IntoResponse for Vec<u8> and Bytes
Browse files Browse the repository at this point in the history
  • Loading branch information
1015bit committed Dec 4, 2018
1 parent d87cc0c commit 1ed6a44
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 9 deletions.
9 changes: 7 additions & 2 deletions examples/body_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,14 @@ async fn echo_string_lossy(msg: body::StrLossy) -> String {
format!("{}", *msg)
}

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

String::from_utf8(msg.to_vec()).unwrap()
async fn echo_bytes(msg: body::Bytes) -> body::Bytes {
println!("Bytes: {:?}", *msg);
msg
}

async fn echo_json(msg: body::Json<Message>) -> body::Json<Message> {
Expand All @@ -44,6 +48,7 @@ fn main() {
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/bytes").post(echo_bytes);
app.at("/echo/json").post(echo_json);
app.at("/echo/form").post(echo_form);

Expand Down
9 changes: 4 additions & 5 deletions src/body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,18 +21,17 @@
//! format!("{}", *msg)
//! }
//!
//! async fn echo_vec(msg: body::Bytes) -> String {
//! println!("Vec<u8>: {:?}", *msg);
//!
//! String::from_utf8(msg.to_vec()).unwrap()
//! async fn echo_bytes(msg: body::Bytes) -> body::Bytes {
//! println!("Bytes: {:?}", *msg);
//! 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/bytes").post(echo_bytes);
//!
//! # app.serve("127.0.0.1:7878");
//! # }
Expand Down
17 changes: 15 additions & 2 deletions src/response.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::body;
use crate::body::Body;

/// An HTTP response.
Expand All @@ -19,16 +20,28 @@ impl IntoResponse for () {
}
}

impl IntoResponse for String {
impl IntoResponse for Vec<u8> {
fn into_response(self) -> Response {
http::Response::builder()
.status(http::status::StatusCode::OK)
.header("Content-Type", "text/plain; charset=utf-8")
.body(Body::from(self.into_bytes()))
.body(Body::from(self))
.unwrap()
}
}

impl IntoResponse for body::Bytes {
fn into_response(self) -> Response {
self.to_vec().into_response()
}
}

impl IntoResponse for String {
fn into_response(self) -> Response {
self.into_bytes().into_response()
}
}

impl IntoResponse for &'static str {
fn into_response(self) -> Response {
self.to_string().into_response()
Expand Down

0 comments on commit 1ed6a44

Please sign in to comment.