gpt4 book ai didi

rust - 如何阅读基于 Tokio 的 Hyper 请求的整个主体?

转载 作者:行者123 更新时间:2023-11-29 08:20:25 28 4
gpt4 key购买 nike

我想使用 Hyper 的当前主分支编写一个服务器,它保存一条由 POST 请求传递的消息,并将该消息发送到每个传入的 GET 请求。

我有这个,大部分是从 Hyper 示例目录复制的:

extern crate futures;
extern crate hyper;
extern crate pretty_env_logger;

use futures::future::FutureResult;

use hyper::{Get, Post, StatusCode};
use hyper::header::{ContentLength};
use hyper::server::{Http, Service, Request, Response};
use futures::Stream;

struct Echo {
data: Vec<u8>,
}

impl Echo {
fn new() -> Self {
Echo {
data: "text".into(),
}
}
}

impl Service for Echo {
type Request = Request;
type Response = Response;
type Error = hyper::Error;
type Future = FutureResult<Response, hyper::Error>;

fn call(&self, req: Self::Request) -> Self::Future {
let resp = match (req.method(), req.path()) {
(&Get, "/") | (&Get, "/echo") => {
Response::new()
.with_header(ContentLength(self.data.len() as u64))
.with_body(self.data.clone())
},
(&Post, "/") => {
//self.data.clear(); // argh. &self is not mutable :(
// even if it was mutable... how to put the entire body into it?
//req.body().fold(...) ?
let mut res = Response::new();
if let Some(len) = req.headers().get::<ContentLength>() {
res.headers_mut().set(ContentLength(0));
}
res.with_body(req.body())
},
_ => {
Response::new()
.with_status(StatusCode::NotFound)
}
};
futures::future::ok(resp)
}

}


fn main() {
pretty_env_logger::init().unwrap();
let addr = "127.0.0.1:12346".parse().unwrap();

let server = Http::new().bind(&addr, || Ok(Echo::new())).unwrap();
println!("Listening on http://{} with 1 thread.", server.local_addr().unwrap());
server.run().unwrap();
}

我如何打开 req.body() (这似乎是 StreamChunks )变成了 Vec<u8> ?我想我必须以某种方式返回 Future消耗了 Stream并将其变成一个 Vec<u8> , 也许与 fold() .但我不知道该怎么做。

最佳答案

Hyper 0.13 提供了一个 body::to_bytes function为此目的。

use hyper::body;
use hyper::{Body, Response};

pub async fn read_response_body(res: Response<Body>) -> Result<String, hyper::Error> {
let bytes = body::to_bytes(res.into_body()).await?;
Ok(String::from_utf8(bytes.to_vec()).expect("response was not valid utf-8"))
}

关于rust - 如何阅读基于 Tokio 的 Hyper 请求的整个主体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52608883/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com