2

So I have the following code that sends multithreaded requests to a list of domains. So far I am able to grab individual data from the response, such as the bytes, or the url, or the status code, etc. but not all of them together. I would like to store all of these values into vectors so it can be written to a file. I know this is probably a super dumb question, but i've been working on it for days and can't figure it out. Any help is appreciated!

#[tokio::main]
async fn get_request(urls: Vec<&str>, paths: Vec<&str>) {
    let client = Client::new();
    for path in paths {
        let urls = urls.clone();
        let bodies = stream::iter(urls)
            .map(|url| {
                let client = &client;
                async move {
                    let mut full_url = String::new();
                    full_url.push_str(url);
                    full_url.push_str(path);
                    let resp = client
                        .get(&full_url)
                        .timeout(Duration::from_secs(3))
                        .send()
                        .await;
                    resp
                }
            })
            .buffer_unordered(PARALLEL_REQUESTS);

        bodies
            .for_each(|b| async {
                match b {
                    Ok(b) => {
                        let mut body_test = &b.bytes().await;
                        match body_test {
                            Ok(body_test) => {
                                let mut stringed_bytes = str::from_utf8(&body_test);
                                match stringed_bytes {
                                    Ok(stringed_bytes) => {
                                        println!("stringed bytes: {}", stringed_bytes);
                                    }
                                    Err(e) => println!("Stringified Error: {}", e),
                                }
                            }
                            Err(e) => println!("body Error: {}", e),
                        }
                    }
                    Err(e) => println!("Got an error: {}", e),
                }
            })
            .await;
    }
}
RandomUser
  • 77
  • 6

1 Answers1

0

I would try creating a struct that would store your desired outputs that you would like to acquire from the body or the hyper::Response. For example:

struct DesiredContent {
   code: Option<u16>,
   body: Json 
   ... 
}

And then implementing impl TryFrom<hyper::Response> for DesiredContent (This assumes you might have cases that should fail like - 404 errors)

finnkauski
  • 169
  • 4