feat: Image router

This commit is contained in:
Nathan McCarty 2023-07-26 04:54:32 -04:00
parent 9c25650f94
commit 6ee4ec6801
Signed by: thatonelutenist
SSH Key Fingerprint: SHA256:3elIBybO7zXuCg+/os7OlO2fwfRPXmObQjcHXBf7Hfg
6 changed files with 56 additions and 1 deletions

1
.gitattributes vendored Normal file
View File

@ -0,0 +1 @@
*.png filter=lfs diff=lfs merge=lfs -text

BIN
assets/images/logo.png (Stored with Git LFS) Normal file

Binary file not shown.

View File

@ -3,7 +3,7 @@ use std::{net::SocketAddr, sync::Arc};
use color_eyre::eyre::{Context, Result}; use color_eyre::eyre::{Context, Result};
use stranger_site::{ use stranger_site::{
routes::{index::index, sheets::sheet}, routes::{images::image, index::index, sheets::sheet},
AppState, AppState,
}; };
@ -19,6 +19,7 @@ async fn main() -> Result<()> {
.route("/index", get(index)) .route("/index", get(index))
.route("/index.html", get(index)) .route("/index.html", get(index))
.route("/sheets/:sheet", get(sheet)) .route("/sheets/:sheet", get(sheet))
.route("/images/:image", get(image))
.with_state(Arc::new(shared_state)); .with_state(Arc::new(shared_state));
// run it // run it

View File

@ -10,6 +10,7 @@ pub struct AppState {
pub title: String, pub title: String,
pub tera: Tera, pub tera: Tera,
pub sheets: HashMap<String, &'static str>, pub sheets: HashMap<String, &'static str>,
pub images: HashMap<String, &'static [u8]>,
} }
impl AppState { impl AppState {
@ -24,10 +25,17 @@ impl AppState {
)] )]
.into_iter() .into_iter()
.collect(); .collect();
let images = [(
"logo.png".to_string(),
include_bytes!("../assets/images/logo.png").as_slice(),
)]
.into_iter()
.collect();
Ok(AppState { Ok(AppState {
title, title,
tera, tera,
sheets, sheets,
images,
}) })
} }
} }

View File

@ -1,2 +1,3 @@
pub mod images;
pub mod index; pub mod index;
pub mod sheets; pub mod sheets;

41
src/routes/images.rs Normal file
View File

@ -0,0 +1,41 @@
use std::sync::Arc;
use axum::{
body::{Bytes, Full},
extract::{Path, State},
http::{header::CONTENT_TYPE, HeaderValue, Response, StatusCode},
};
use color_eyre::eyre::ContextCompat;
use crate::AppState;
/// Return the given image
async fn image_inner(
State(state): State<Arc<AppState>>,
Path(path): Path<String>,
) -> color_eyre::eyre::Result<Response<Full<Bytes>>> {
eprintln!("Returning image: {path}");
let image = state
.images
.get(&path)
.context("No image with given name found")?
.to_vec();
let mut response = Response::new(Full::new(Bytes::from(image)));
response
.headers_mut()
.insert(CONTENT_TYPE, HeaderValue::from_static("image/png"));
Ok(response)
}
pub async fn image(
path: Path<String>,
state: State<Arc<AppState>>,
) -> Result<Response<Full<Bytes>>, (StatusCode, String)> {
match image_inner(state, path).await {
Ok(x) => Ok(x),
Err(err) => {
let err = format!("{:?}", err);
Err((StatusCode::NOT_FOUND, err))
}
}
}