Skip to content

Instantly share code, notes, and snippets.

@iamalwaysuncomfortable
Created August 5, 2022 19:53
Show Gist options
  • Save iamalwaysuncomfortable/8b3cbb1821ec531faef291d7f48632f2 to your computer and use it in GitHub Desktop.
Save iamalwaysuncomfortable/8b3cbb1821ec531faef291d7f48632f2 to your computer and use it in GitHub Desktop.
Rust image upload sample
use anyhow::Result;
use futures::{stream::{FuturesUnordered}, StreamExt};
use reqwest::Client;
use std::time::Instant;
use tokio;
const PARALLEL_REQUESTS: usize = 30;
const IMOGE_BYTES: &'static [u8] = include_bytes!("/home/imoge.jpeg");
async fn post(client: &Client, url: String, bearer: &str) -> reqwest::Result<bytes::Bytes> {
let resp = client
.put(url)
.bearer_auth(bearer)
.body(IMOGE_BYTES)
.send()
.await?;
resp.bytes().await
}
#[tokio::main]
async fn main() -> Result<()>{
let base_url ="https://example.com";
let client = Client::new();
let tasks = FuturesUnordered::new();
let bearer = "Bearer 1212wHOaREyOU";
for i in 0..PARALLEL_REQUESTS {
let url = format!("{}{}.png", base_url, i);
tasks.push(Box::pin(post(&client, url, bearer)));
}
let start = Instant::now();
tasks.for_each_concurrent(PARALLEL_REQUESTS, |b| async {
match b {
_ => {},
Err(e) => eprintln!("Got a reqwest::Error: {}", e),
}
})
.await;
let ms = start.elapsed().as_millis();
println!("uploading {} imoges took {} ms", PARALLEL_REQUESTS, ms);
println!("average upload speed: {} bytes/ms", (IMOGE_BYTES.len() as u128 / ms ));
println!("average image upload time: {} ms", (ms / PARALLEL_REQUESTS as u128));
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment