hyper crate的文档有一个启动 Web 服务器的简单示例:
extern crate hyper;
use hyper::service::service_fn_ok;
use hyper::{Body, Response, Server};
fn main() {
// Construct our SocketAddr to listen on...
let addr = ([127, 0, 0, 1], 3000).into();
// And a NewService to handle each connection...
let new_service = || service_fn_ok(|_req| Response::new(Body::from("Hello World")));
// Then bind and serve...
let server = Server::bind(&addr).serve(new_service);
// Finally, spawn `server` onto an Executor...
hyper::rt::run(server.map_err(|e| {
eprintln!("server error: {}", e);
}));
}
我想将此 Web 服务器嵌入到返回错误的过程中:
// Executes a web server. Returns a result object with an error object
// if the server stopped unexpectedly
fn run_and_stop_web_server(addr: std::net::SocketAddr) -> Result<(), Error> {
let server_builder = Server::try_bind(&addr)?;
let server = server_builder.serve(move || {
let handler: Handler = Handler::new();
hyper::service::service_fn(move |req| handler.serve(req))
});
// Run the server
// HERE: I don't know how to handle the error so I can return it from
// the run_and_stop_web_server() function
hyper::rt::run(server.map_err(|e| eprintln!("Ignored Server error: {}", e)));
Result::Ok(())
}
我不知道如何处理错误。而不是使用eprintln!()
我想从run_and_stop_web_server
函数返回错误。