1

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函数返回错误。

4

2 回答 2

1

我相信我找到了直接使用 tokio 运行时的解决方案......它可以编译。如果我在这里错了,请任何人告诉我。

这个想法是直接使用 tokio Runtime(文档有很多例子):

use tokio::runtime::Runtime;

// 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))
    });

    let mut rt = Runtime::new()?;
    rt.block_on(server)?;
    rt.shutdown_now();

    Result::Ok(())
}
于 2018-08-30T20:02:36.853 回答
-1

也许您可以将错误存储到局部变量中并返回:

let mut result = Result::Ok(());
hyper::rt::run(server.map_err(|e| { result = Result::Error (e); });
result
于 2018-08-24T06:35:41.080 回答