diff --git a/Cargo.lock b/Cargo.lock index 1065223..b799939 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -67,6 +67,7 @@ name = "catscii" version = "0.1.0" dependencies = [ "color-eyre", + "pretty-hex", "reqwest", "serde", "tokio", @@ -639,6 +640,12 @@ version = "0.3.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "26072860ba924cbfa98ea39c8c19b4dd6a4a25423dbdf219c1eca91aa0cf6964" +[[package]] +name = "pretty-hex" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6fa0831dd7cc608c38a5e323422a0077678fa5744aa2be4ad91c4ece8eec8d5" + [[package]] name = "proc-macro2" version = "1.0.56" diff --git a/Cargo.toml b/Cargo.toml index 018e506..df1875e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,6 +6,7 @@ edition = "2018" [dependencies] color-eyre = "0.6" +pretty-hex = "0.3" reqwest = { version = "0.11", features = ["json"] } serde = { version = "1", features = ["derive"] } tokio = { version = "1", features = ["full"] } diff --git a/src/main.rs b/src/main.rs index de4c11f..56988eb 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,30 +1,39 @@ +use pretty_hex::PrettyHex; use serde::Deserialize; #[tokio::main] async fn main() { - let url = get_cat_image_url().await.unwrap(); - println!("The image is at {}", url); + let image_bytes = get_cat_image_bytes().await.unwrap(); + // only dump the first 200 bytes so our terminal survives the onslaught. This will panic if the + // image has fewer than 200 bytes. + println!("{:?}", &image_bytes[..200].hex_dump()); } -async fn get_cat_image_url() -> color_eyre::Result { - let api_url = "https://api.thecatapi.com/v1/images/search"; - let res = reqwest::get(api_url).await?; - if !res.status().is_success() { - return Err(color_eyre::eyre::eyre!( - "The Cat API returned HTTP {}", - res.status() - )); - } - +async fn get_cat_image_bytes() -> color_eyre::Result> { #[derive(Deserialize)] struct CatImage { url: String, } - let mut images: Vec = res.json().await?; - if let Some(image) = images.pop() { - Ok(image.url) - } else { - Err(color_eyre::eyre::eyre!("The Cat API returned no images")) - } + let api_url = "https://api.thecatapi.com/v1/images/search"; + let client = reqwest::Client::default(); + + let image = client + .get(api_url) + .send() + .await? + .error_for_status()? + .json::>() + .await? + .pop() + .ok_or_else(|| color_eyre::eyre::eyre!("The Cat API returned no images"))?; + + Ok(client + .get(image.url) + .send() + .await? + .error_for_status()? + .bytes() + .await? + .to_vec()) }