How can I stop the hyper HTTP web server and return an error?

和自甴很熟 提交于 2019-12-08 03:22:20

问题


The docs for the hyper crate have a simple example to start a web server:

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

I want to embed this web server in a procedure that returns an error:

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

I don't know how I can handle the error. Instead of using eprintln!() I want to return the error from the run_and_stop_web_server function.


回答1:


I believe I found a solution using the tokio runtime directly... It compiles. Please anyone tell me if I'm wrong here.

The idea is to use the tokio Runtime directly (docs have many examples):

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(())
}



回答2:


Maybe you can store the error into a local variable and return that:

let mut result = Result::Ok(());
hyper::rt::run(server.map_err(|e| { result = Result::Error (e); });
result


来源:https://stackoverflow.com/questions/51987105/how-can-i-stop-the-hyper-http-web-server-and-return-an-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!