Dump hex-encoding of images.

This commit is contained in:
Lyle Mantooth 2023-05-14 10:34:23 -04:00
parent e3946c8129
commit 95db82c430
Signed by: IslandUsurper
GPG key ID: 6DB52EAE123A5789
3 changed files with 35 additions and 18 deletions

7
Cargo.lock generated
View file

@ -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"

View file

@ -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"] }

View file

@ -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<String> {
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<Vec<u8>> {
#[derive(Deserialize)]
struct CatImage {
url: String,
}
let mut images: Vec<CatImage> = 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::<Vec<CatImage>>()
.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())
}