Dump hex-encoding of images.
This commit is contained in:
parent
e3946c8129
commit
95db82c430
3 changed files with 35 additions and 18 deletions
45
src/main.rs
45
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<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())
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue