The following code gets some variables in closures and returns a struct containing that data.
I can't return the struct with that data even when I box the struct and clone the variables; they are impossible to take out of this scope. I thought about using a callback closure but I don't really want to do that. Is there any way to take those out without having a callback?
pub fn get(addr: &str) -> std::io::Result<Box<Response>> {
use std::sync::{Arc, Mutex};
let mut crl = curl::easy::Easy::new();
crl.url(format!("{}{}", API_ADDR, addr).as_str()).unwrap();
// extract headers
let headers: Vec<String> = Vec::with_capacity(10);
let headers = Arc::new(Mutex::new(headers));
{
let headers = headers.clone();
crl.header_function(move |h| {
let mut headers = headers.lock().unwrap();
(*headers).push(String::from_utf8_lossy(h).into_owned());
true
})
.unwrap();
}
// extract body
let body = Arc::new(Mutex::new(String::with_capacity(1024)));
{
let body = body.clone();
crl.write_function(move |b| {
let mut body = body.lock().unwrap();
body.push_str(std::str::from_utf8(b).unwrap());
Ok(b.len())
})
.unwrap();
}
crl.perform().unwrap();
Ok(Box::new(Response {
resp: body.lock().unwrap().clone(),
headers: headers.lock().unwrap().clone(),
}))
}