serve over http in color
This commit is contained in:
parent
ac89e02e0e
commit
6ff4105aea
3 changed files with 827 additions and 8 deletions
756
Cargo.lock
generated
756
Cargo.lock
generated
File diff suppressed because it is too large
Load diff
|
|
@ -4,5 +4,11 @@ version = "0.1.0"
|
|||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
artem = { version = "1", default-features = false }
|
||||
axum = "0.6"
|
||||
color-eyre = "0.6"
|
||||
image = "0.24"
|
||||
pretty-hex = "0.3"
|
||||
reqwest = { version = "0.11", features = ["json"] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
|
|
|
|||
73
src/main.rs
73
src/main.rs
|
|
@ -1,9 +1,74 @@
|
|||
// in `src/main.rs`
|
||||
|
||||
use axum::{
|
||||
Router,
|
||||
body::BoxBody,
|
||||
http::header,
|
||||
response::{IntoResponse, Response},
|
||||
routing::get,
|
||||
};
|
||||
use reqwest::StatusCode;
|
||||
use serde::Deserialize;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let res = reqwest::get("https://api.thecatapi.com/v1/images/search")
|
||||
let app = Router::new().route("/", get(root_get));
|
||||
|
||||
axum::Server::bind(&"0.0.0.0:5000".parse().unwrap())
|
||||
.serve(app.into_make_service())
|
||||
.await
|
||||
.unwrap();
|
||||
println!("Status: {}", res.status());
|
||||
let body = res.text().await.unwrap();
|
||||
println!("Body: {}", body);
|
||||
}
|
||||
|
||||
async fn root_get() -> Response<BoxBody> {
|
||||
match get_cat_ascii_art().await {
|
||||
Ok(art) => (
|
||||
StatusCode::OK,
|
||||
// was text/plain 👇
|
||||
[(header::CONTENT_TYPE, "text/html; charset=utf-8")],
|
||||
art,
|
||||
)
|
||||
.into_response(),
|
||||
Err(e) => {
|
||||
println!("Something went wrong: {e}");
|
||||
(StatusCode::INTERNAL_SERVER_ERROR, "Something went wrong").into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
async fn get_cat_ascii_art() -> color_eyre::Result<String> {
|
||||
#[derive(Deserialize)]
|
||||
struct CatImage {
|
||||
url: String,
|
||||
}
|
||||
|
||||
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"))?;
|
||||
|
||||
let image_bytes = client
|
||||
.get(image.url)
|
||||
.send()
|
||||
.await?
|
||||
.error_for_status()?
|
||||
.bytes()
|
||||
.await?;
|
||||
|
||||
let image = image::load_from_memory(&image_bytes)?;
|
||||
let ascii_art = artem::convert(
|
||||
image,
|
||||
artem::options::OptionBuilder::new()
|
||||
.target(artem::options::TargetType::HtmlFile(true, true))
|
||||
.build(),
|
||||
);
|
||||
|
||||
Ok(ascii_art)
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue