Created
August 5, 2022 19:53
-
-
Save iamalwaysuncomfortable/8b3cbb1821ec531faef291d7f48632f2 to your computer and use it in GitHub Desktop.
Rust image upload sample
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
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