feat: add body in response

This commit is contained in:
2020-11-22 15:22:15 +08:00
parent 1339f0cdf3
commit 37755d8b0d

View File

@@ -1,6 +1,8 @@
use std::convert::Infallible; use std::convert::Infallible;
use hyper::service; use hyper::service;
use hyper::{Body, Request, Response, Server}; use hyper::{Body, Request, Response, Server};
use hyper::http::Method;
use hyper::body::HttpBody;
async fn hello(request: Request<Body>) -> Result<Response<Body>, Infallible> { async fn hello(request: Request<Body>) -> Result<Response<Body>, Infallible> {
let mut buff = String::with_capacity(1024); let mut buff = String::with_capacity(1024);
@@ -10,6 +12,8 @@ async fn hello(request: Request<Body>) -> Result<Response<Body>, Infallible> {
buff.push(' '); buff.push(' ');
buff.push_str(&format!("{:?}", request.version().to_owned())); buff.push_str(&format!("{:?}", request.version().to_owned()));
buff.push('\n'); buff.push('\n');
buff.push_str(&"=".repeat(88));
buff.push('\n');
for header in request.headers() { for header in request.headers() {
buff.push_str(&header.0.to_string()); buff.push_str(&header.0.to_string());
buff.push_str(": "); buff.push_str(": ");
@@ -21,6 +25,19 @@ async fn hello(request: Request<Body>) -> Result<Response<Body>, Infallible> {
} }
buff.push('\n'); buff.push('\n');
} }
buff.push_str(&"=".repeat(88));
buff.push('\n');
if request.method() == Method::POST {
let mut request = request;
let body = request.body_mut().data().await;
match body {
None => buff.push_str("<nobody>"),
Some(Err(e)) => buff.push_str(&format!("<get body err: {}>", e)),
Some(Ok(body)) => buff.push_str(&String::from_utf8_lossy(&*body)),
}
}
buff.push_str(&"=".repeat(88));
buff.push('\n');
Ok(Response::new(Body::from(buff))) Ok(Response::new(Body::from(buff)))
} }