Skip to content

Instantly share code, notes, and snippets.

@snewcomer
Forked from patshaughnessy/main.rs
Created February 22, 2021 02:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save snewcomer/fd43f487baec4611d9218e4b6aa33c91 to your computer and use it in GitHub Desktop.
Save snewcomer/fd43f487baec4611d9218e4b6aa33c91 to your computer and use it in GitHub Desktop.
// Code from: http://patshaughnessy.net/2020/1/20/downloading-100000-files-using-async-rust
//
// Cargo.toml:
// [dependencies]
// tokio = { version = "0.2", features = ["full"] }
// reqwest = { version = "0.10", features = ["json"] }
// futures = "0.3"
use std::io::prelude::*;
use std::fs::File;
use std::io::BufReader;
use futures::stream::StreamExt;
fn read_lines(path: &str) -> std::io::Result<Vec<String>> {
let file = File::open(path)?;
let reader = BufReader::new(file);
Ok(
reader.lines().filter_map(Result::ok).collect()
)
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let paths: Vec<String> = read_lines("urls.txt")?;
let fetches = futures::stream::iter(
paths.into_iter().map(|path| {
async move {
match reqwest::get(&path).await {
Ok(resp) => {
match resp.text().await {
Ok(text) => {
println!("RESPONSE: {} bytes from {}", text.len(), path);
}
Err(_) => println!("ERROR reading {}", path),
}
}
Err(_) => println!("ERROR downloading {}", path),
}
}
})
).buffer_unordered(100).collect::<Vec<()>>();
fetches.await;
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment