我正在尝试使用 Hyper 在 Rust 中创建一个简单的 Web 服务器,但在尝试将其转换request.body()
Stream
为String
.
我每晚运行 rustc 1.21.0
到目前为止,我有这个:
extern crate futures;
extern crate hyper;
extern crate unicase;
use hyper::server::{Http, Request, Response, Service};
use hyper::Body;
use hyper::Chunk;
use futures::Stream;
use futures::future::*;
use futures::stream::Map;
use std::ascii::AsciiExt;
use unicase::Ascii;
struct WebService;
impl Service for WebService {
type Request = Request;
type Response = Response;
type Error = hyper::Error;
type Future = Box<futures::Future<Item = Self::Response, Error = Self::Error>>;
fn call(&self, req: Request) -> Self::Future {
let mut response = Response::new();
let body = req.body()
.fold(Vec::new(), |mut acc, chunk| {
acc.extend_from_slice(&*chunk);
futures::future::ok::<_, Self::Error>(acc)
})
.and_then(|v| String::from_utf8(v));
println!("Body: \n{}", body.wait().unwrap());
let future = futures::future::ok(response);
Box::new(future)
}
}
fn main() {
let addr = "0.0.0.0:3000".parse().unwrap();
let server = Http::new().bind(&addr, || Ok(WebService)).unwrap();
server.run().unwrap();
}
这会导致以下错误消息:
error[E0271]: type mismatch resolving `<std::result::Result<std::string::String, std::string::FromUtf8Error> as futures::IntoFuture>::Error == hyper::Error`
--> src/main.rs:30:14
|
30 | .and_then(|v| String::from_utf8(v));
| ^^^^^^^^ expected struct `std::string::FromUtf8Error`, found enum `hyper::Error`
|
= note: expected type `std::string::FromUtf8Error`
found type `hyper::Error`
error[E0599]: no method named `wait` found for type `futures::AndThen<futures::stream::Fold<hyper::Body, [closure@src/main.rs:26:31: 29:14], futures::FutureResult<std::vec::Vec<u8>, hyper::Error>, std::vec::Vec<u8>>, std::result::Result<std::string::String, std::string::FromUtf8Error>, [closure@src/main.rs:30:23: 30:47]>` in the current scope
--> src/main.rs:31:37
|
31 | println!("Body: \n{}", body.wait().unwrap());
| ^^^^
|
= note: the method `wait` exists but the following trait bounds were not satisfied:
`futures::AndThen<futures::stream::Fold<hyper::Body, [closure@src/main.rs:26:31: 29:14], futures::FutureResult<std::vec::Vec<u8>, hyper::Error>, std::vec::Vec<u8>>, std::result::Result<std::string::String, std::string::FromUtf8Error>, [closure@src/main.rs:30:23: 30:47]> : futures::Stream`
`futures::AndThen<futures::stream::Fold<hyper::Body, [closure@src/main.rs:26:31: 29:14], futures::FutureResult<std::vec::Vec<u8>, hyper::Error>, std::vec::Vec<u8>>, std::result::Result<std::string::String, std::string::FromUtf8Error>, [closure@src/main.rs:30:23: 30:47]> : futures::Future`
我认为我正在从该fold
方法返回一个未来,其结果被输送到该and_then
方法中,我希望该方法将一个String
版本分配request.body
给该body
变量。
我对 Rust 很陌生,但对我来说,错误似乎表明and_then
连接器只接收Error
未来的价值,而不是Ok
价值......
这是一个正确的解释吗?我将如何解决此错误?