I want to parse a YAML file and use the value inside a service for a HTTP request. Line 35 is the end of main function.
extern crate hyper;
extern crate libc;
extern crate yaml_rust;
use hyper::rt::Future;
use hyper::service::service_fn_ok;
use hyper::{Body, Response, Server};
use std::sync::Arc;
use yaml_rust::YamlLoader;
fn main() {
let content: String = String::from("response: Hello world");
let cfg = Arc::new(YamlLoader::load_from_str(content.as_str()).unwrap());
let cfg0 = (&cfg[0]).clone();
let cfg_response = (&cfg0)["response"].as_str().unwrap();
// A `Service` is needed for every connection, so this
// creates on of our `hello_world` function.
let handle = move || {
let cfg_response = cfg_response.clone();
service_fn_ok(move |_| Response::new(Body::from(String::from(cfg_response.clone()))))
};
// Serve HTTP protocol
// This is our socket address...
let addr: std::net::SocketAddr = ([127, 0, 0, 1], 3000).into();
let server = Server::bind(&addr)
.serve(handle)
.map_err(|e| eprintln!("server error: {}", e));
// Run this server for... forever!
hyper::rt::run(server);
}
Unfortunately, I encountered a nested closure leading to a strange borrow error:
error[E0597]: `cfg0` does not live long enough
--> src/main.rs:15:26
|
15 | let cfg_response = (&cfg0)["response"].as_str().unwrap();
| ^^^^ borrowed value does not live long enough
...
35 | }
| - borrowed value only lives until here
|
= note: borrowed value must be valid for the static lifetime...
I tried to
- clone it before borrow
- use
Arc
to make it counter-based, - modify assignment
all to no avail
Why does this happen? How do I solve this?