I would like to download a file on a separate thread:
use http::StatusCode; // 0.2.1
use std::{fs::File, io::Write, path::Path, thread, time};
use reqwest; // 0.10.8
fn write_file(to_file: &str, response: reqwest::blocking::Response) -> std::io::Result<()> {
let content = response.bytes().unwrap();
let target_with_extension = Path::new(to_file);
File::create(&target_with_extension)
.expect("Unable to create file")
.write_all(&content)?;
Ok(())
}
pub struct Downloader;
impl Downloader {
fn get(&self, from_url: &str, to_file: &str) -> std::io::Result<()> {
let total_size: u64 = 1 * 1024 * 1024;
let download_thread = std::thread::spawn(|| {
let response = reqwest::blocking::get(from_url).unwrap();
assert!(response.status() == StatusCode::OK);
write_file(to_file, response).unwrap();
});
let fs = 0;
while fs < total_size {
let fs = std::fs::metadata("dua-v2.10.2-x86_64-unknown-linux-musl.tar.gz")?.len();
println!("Downloaded {}", fs);
thread::sleep(time::Duration::from_millis(500));
}
download_thread
.join()
.expect("The downloader thread panicked!");
Ok(())
}
}
fn main() {
Downloader{}.get("https://github.com/Byron/dua-cli/releases/download/v2.10.2/dua-v2.10.2-x86_64-unknown-linux-musl.tar.gz", "dua-v2.10.2-x86_64-unknown-linux-musl.tar.gz");
}
I get the following error when trying to compile, I do not know the exact syntax to circumvent it. What could be done here?
error[E0621]: explicit lifetime required in the type of `from_url`
--> src/main.rs:20:31
|
17 | fn get(&self, from_url: &str, to_file: &str) -> std::io::Result<()> {
| ---- help: add explicit lifetime `'static` to the type of `from_url`: `&'static str`
...
20 | let download_thread = std::thread::spawn(|| {
| ^^^^^^^^^^^^^^^^^^ lifetime `'static` required
error[E0621]: explicit lifetime required in the type of `to_file`
--> src/main.rs:20:31
|
17 | fn get(&self, from_url: &str, to_file: &str) -> std::io::Result<()> {
| ---- help: add explicit lifetime `'static` to the type of `to_file`: `&'static str`
...
20 | let download_thread = std::thread::spawn(|| {
| ^^^^^^^^^^^^^^^^^^ lifetime `'static` required