Several requests in parallel with Rust

⚓ Rust    📅 2025-06-24    👤 surdeus    👁️ 6      

surdeus

Warning

This post was published 48 days ago. The information described in this article may have changed.

I'm trying to learn async rust by trying to do a bunch of requests at once but what I've got only works sequentially. My goal is to print the UrlStatus as it goes and do as many of them at the same time as possible.

use reqwest;
use serde::Serialize;

#[derive(Serialize)]
struct UrlStatus<'a> {
    url: &'a str,
    status: Option<u16>,
}

async fn check(url : &str) {
    match reqwest::get(url).await {
        Ok(response) => {
            let status = UrlStatus {
                url,
                status: Some(response.status().as_u16()),
            };
            println!("{}", serde_json::to_string(&status).unwrap());
        }
        Err(_) => {
            let error = UrlStatus {
                url,
                status: None,
            };
            eprintln!("{}", serde_json::to_string(&error).unwrap());
        }
    }
}


#[tokio::main]
async fn main() {
    let urls = vec!["https://httpbin.org/status/200"; 10];

    for url in urls {
        let handle = tokio::spawn(check(url));
        handle.await.unwrap();
    }
}

4 posts - 3 participants

Read full topic

🏷️ rust_feed