Created
December 14, 2022 21:08
-
-
Save EONRaider/f90e00b2c01fe4bc6e53e3edfc2dbd1c to your computer and use it in GitHub Desktop.
A simple asynchronous HTTP client in Rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// [dependencies] | |
// async-std = { version = "1.7.0", features = ["unstable"]} | |
// surf = "1.0.0" | |
pub async fn many_requests(urls: &[String]) -> Vec<Result<String, surf::Exception>> { | |
let client = surf::Client::new(); | |
let mut handles = vec![]; | |
for url in urls { | |
let request = client.get(&url).recv_string(); | |
handles.push(async_std::task::spawn(request)); | |
} | |
let mut results = vec![]; | |
for handle in handles { | |
results.push(handle.await); | |
} | |
results | |
} | |
fn main() { | |
let requests = [ | |
"http://example.com".to_string(), | |
"https://www.red-bean.com".to_string(), | |
"https://en.wikipedia.org/wiki/Main_Page".to_string() | |
]; | |
let results = async_std::task::block_on(many_requests(&requests)); | |
for result in results { | |
match result { | |
Ok(response) => println!("*** {response}\n"), | |
Err(e) => eprintln!("Error: {e}\n"), | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment