feat: Add sheets route

This commit is contained in:
Nathan McCarty 2023-07-26 04:06:31 -04:00
parent 11bd5897bf
commit 9c25650f94
Signed by: thatonelutenist
SSH Key Fingerprint: SHA256:3elIBybO7zXuCg+/os7OlO2fwfRPXmObQjcHXBf7Hfg
5 changed files with 61 additions and 2 deletions

1
assets/sheets/index.css Normal file
View File

@ -0,0 +1 @@
/* uwu */

View File

@ -2,7 +2,10 @@ use axum::{routing::get, Router};
use std::{net::SocketAddr, sync::Arc};
use color_eyre::eyre::{Context, Result};
use stranger_site::{routes::index::index, AppState};
use stranger_site::{
routes::{index::index, sheets::sheet},
AppState,
};
#[tokio::main]
async fn main() -> Result<()> {
@ -15,6 +18,7 @@ async fn main() -> Result<()> {
.route("/", get(index))
.route("/index", get(index))
.route("/index.html", get(index))
.route("/sheets/:sheet", get(sheet))
.with_state(Arc::new(shared_state));
// run it

View File

@ -1,3 +1,5 @@
use std::collections::HashMap;
use color_eyre::eyre::{Context, Result};
use tera::Tera;
@ -7,6 +9,7 @@ pub mod routes;
pub struct AppState {
pub title: String,
pub tera: Tera,
pub sheets: HashMap<String, &'static str>,
}
impl AppState {
@ -15,6 +18,16 @@ impl AppState {
let mut tera = Tera::default();
tera.add_raw_template("index.html", include_str!("../assets/templates/index.html"))
.context("Failed to load built in template for index.html")?;
Ok(AppState { title, tera })
let sheets = [(
"index.css".to_string(),
include_str!("../assets/sheets/index.css"),
)]
.into_iter()
.collect();
Ok(AppState {
title,
tera,
sheets,
})
}
}

View File

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

40
src/routes/sheets.rs Normal file
View File

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