Hi, everybody.
I'm trying to figure out what I'm doing with a code, which is coping headers in the future that applied one per a user, connected via WebSockets. Those headers will be used after for a checking a token and validate it (probably for another kind stuff later, for example, checking permissions). In this case headers should outlive not also in future that initialize headers
variable, but should stay alive until user (or a server) won't close the established connection.
Can anybody help me with it and, if it possible, explain why the compiler is noticing me, that doing something wrong? And what will be the best solution for this particular case? Swapping the lines, like it was mention as error-index page, leads to the error with the "context" with a variable (or that headers isn't found in this scope).
So, this is code were I'm getting an error:
pub fn run(&self, address: SocketAddr) {
let mut core = Core::new().unwrap();
let handle = core.handle();
let socket = TcpListener::bind(&address, &handle).unwrap();
println!("Listening on: {}", address);
let server = socket.incoming().for_each(|(stream, addr)| {
let engine_inner = self.engine.clone();
let connections_inner = self.connections.clone();
let auth_middleware_inner = self.auth_middleware.clone();
let handle_inner = handle.clone();
let mut headers: HashMap<String, Box<[u8]>> = HashMap::new();
let copy_headers_callback = |request: &Request| {
for &(ref name, ref value) in request.headers.iter() {
headers.insert(name.to_string(), value.clone());
}
Ok(None)
};
accept_hdr_async(stream, copy_headers_callback)
// Process the messages
.and_then(move |ws_stream| {
// ...
});
// Run the server
core.run(server).unwrap();
}
And the output that was generated by the compiler:
error[E0597]: `headers` does not live long enough
--> src/proxy.rs:60:21
|
58 | let copy_headers_callback = |request: &Request| {
| ------------------- capture occurs here
59 | for &(ref name, ref value) in request.headers.iter() {
60 | headers.insert(name.to_string(), value.clone());
| ^^^^^^^ does not live long enough
...
111 | });
| - borrowed value only lives until here
...
115 | }
| - borrowed value needs to live until here