How to share immutable configuration data with hyper request handlers?

前端 未结 1 932
离开以前
离开以前 2021-01-23 02:33

I am trying to develop a hyper based server application in Rust. There is an INI file holding configuration like binding IP, database and so on.

I don\'t want to parse

1条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-23 03:02

    The two levels of closures in serve are to be observed with care. The closure at the second level (which is passed to service_fn_ok), defined with move, will attempt to move the only instance cfg into it, even before any call to clone() is made. This move cannot be done multiple times without cloning, and therefore the closure will only implement FnOnce. This is a case of double move: the second closure wants to receive a resource in an environment that only allows it to do that once.

    To solve this problem, we want the first closure to receive cfg, and clone it each time there.

    fn main() {
        let cfg = read_ini("demo.ini");
        let addr = "127.0.0.1:3000".parse().unwrap();
    
        let server = Server::bind(&addr)
            .serve(move || {
                let cfg = cfg.clone();
                service_fn_ok(move |req| request_handler(req, &cfg))
            })
            .map_err(|e| println!("server error: {}", e));
    
        rt::run(server);
    }
    

    0 讨论(0)
提交回复
热议问题