1
0
Fork 0

cargo fix & cargo fmt

This commit is contained in:
Adrian Hedqvist 2023-03-29 18:20:51 +02:00
parent 6be5525bae
commit 0808fc8099
3 changed files with 49 additions and 47 deletions

View file

@ -1,10 +1,14 @@
use axum::{ use axum::{
body,
extract::State,
middleware::Next,
response::{Html, IntoResponse, Response}, response::{Html, IntoResponse, Response},
Router, routing::get, extract::State, middleware::Next, body, routing::get,
Router,
}; };
use hyper::{StatusCode, Request, header::CONTENT_TYPE}; use hyper::{header::CONTENT_TYPE, Request, StatusCode};
use lazy_static::lazy_static; use lazy_static::lazy_static;
use prometheus::{opts, IntCounterVec, TextEncoder, Encoder}; use prometheus::{opts, Encoder, IntCounterVec, TextEncoder};
use std::sync::Arc; use std::sync::Arc;
use tracing::{instrument, log::*}; use tracing::{instrument, log::*};
@ -14,7 +18,10 @@ pub mod posts;
lazy_static! { lazy_static! {
pub static ref HIT_COUNTER: IntCounterVec = prometheus::register_int_counter_vec!( pub static ref HIT_COUNTER: IntCounterVec = prometheus::register_int_counter_vec!(
opts!("http_requests_total", "Total amount of http requests received"), opts!(
"http_requests_total",
"Total amount of http requests received"
),
&["route", "method", "status"] &["route", "method", "status"]
) )
.unwrap(); .unwrap();
@ -43,7 +50,6 @@ pub async fn index(
Ok(Html(res)) Ok(Html(res))
} }
async fn healthcheck() -> &'static str { async fn healthcheck() -> &'static str {
"OK" "OK"
} }
@ -69,7 +75,9 @@ pub async fn metrics_middleware<B>(request: Request<B>, next: Next<B>) -> Respon
let path = request.uri().path().to_string(); let path = request.uri().path().to_string();
let method = request.method().to_string(); let method = request.method().to_string();
let response = next.run(request).await; let response = next.run(request).await;
HIT_COUNTER.with_label_values(&[&path, &method, response.status().as_str()]).inc(); HIT_COUNTER
.with_label_values(&[&path, &method, response.status().as_str()])
.inc();
response response
} }

View file

@ -1,6 +1,11 @@
use std::sync::Arc; use std::sync::Arc;
use axum::{extract::{Path, State}, response::{Html, Redirect}, routing::get, Extension, Router}; use axum::{
extract::{Path, State},
response::{Html, Redirect},
routing::get,
Router,
};
use serde_derive::Serialize; use serde_derive::Serialize;
use tracing::{instrument, log::*}; use tracing::{instrument, log::*};
@ -17,16 +22,19 @@ pub fn router() -> Router<Arc<AppState>> {
.fallback_service(tower_http::services::ServeDir::new("./posts")) .fallback_service(tower_http::services::ServeDir::new("./posts"))
} }
pub fn alias_router<'a>(posts: impl IntoIterator<Item=&'a Post>) -> Router<Arc<AppState>> { pub fn alias_router<'a>(posts: impl IntoIterator<Item = &'a Post>) -> Router<Arc<AppState>> {
let mut router = Router::new(); let mut router = Router::new();
for post in posts { for post in posts {
for alias in &post.aliases { for alias in &post.aliases {
let path = post.absolute_path.to_owned(); let path = post.absolute_path.to_owned();
router = router.route(alias, get(move || async { router = router.route(
alias,
get(move || async {
let path = path; let path = path;
Redirect::permanent(&path) Redirect::permanent(&path)
})); }),
);
} }
} }
router router
@ -39,25 +47,18 @@ struct PageContext<'a> {
#[instrument(skip(state))] #[instrument(skip(state))]
pub async fn index(State(state): State<Arc<AppState>>) -> Result<Html<String>, WebsiteError> { pub async fn index(State(state): State<Arc<AppState>>) -> Result<Html<String>, WebsiteError> {
let mut posts: Vec<&Post> = state let mut posts: Vec<&Post> = state.posts.values().filter(|p| p.is_published()).collect();
.posts
.values()
.filter(|p| p.is_published())
.collect();
posts.sort_by_key(|p| &p.date); posts.sort_by_key(|p| &p.date);
posts.reverse(); posts.reverse();
let ctx = PageContext { let ctx = PageContext { title: "Posts" };
title: "Posts",
};
let mut c = tera::Context::new(); let mut c = tera::Context::new();
c.insert("page", &ctx); c.insert("page", &ctx);
c.insert("posts", &posts); c.insert("posts", &posts);
let res = state.tera let res = state.tera.render("posts_index.html", &c)?;
.render("posts_index.html", &c)?;
Ok(Html(res)) Ok(Html(res))
} }
@ -88,7 +89,8 @@ mod tests {
#[test] #[test]
fn render_index() { fn render_index() {
let posts = vec![Post { let posts = vec![
Post {
title: "test".into(), title: "test".into(),
slug: "test".into(), slug: "test".into(),
date: Some(DateTime::parse_from_rfc3339("2023-03-26T13:04:01+02:00").unwrap()), date: Some(DateTime::parse_from_rfc3339("2023-03-26T13:04:01+02:00").unwrap()),
@ -99,20 +101,14 @@ mod tests {
slug: "test2".into(), slug: "test2".into(),
date: None, date: None,
..Default::default() ..Default::default()
}]; },
let page = PageContext { ];
title: "Posts", let page = PageContext { title: "Posts" };
};
let mut ctx = tera::Context::new(); let mut ctx = tera::Context::new();
ctx.insert("page", &page); ctx.insert("page", &page);
ctx.insert("posts", &posts); ctx.insert("posts", &posts);
let tera = tera::Tera::new("templates/**/*").unwrap(); let tera = tera::Tera::new("templates/**/*").unwrap();
let _res = tera let _res = tera.render("posts_index.html", &ctx).unwrap();
.render(
"posts_index.html",
&ctx,
)
.unwrap();
} }
} }

View file

@ -1,10 +1,9 @@
use std::{collections::HashMap, sync::Arc}; use std::{collections::HashMap, sync::Arc};
use axum::{body, response::Response, routing::get, Extension, Router, extract::State};
use color_eyre::eyre::{Error, Result}; use color_eyre::eyre::{Error, Result};
use hyper::header::CONTENT_TYPE;
use post::Post; use post::Post;
use prometheus::{Encoder, TextEncoder};
use tera::Tera; use tera::Tera;
use tower_http::{compression::CompressionLayer, trace::TraceLayer}; use tower_http::{compression::CompressionLayer, trace::TraceLayer};
use tracing::log::*; use tracing::log::*;
@ -27,7 +26,6 @@ async fn main() -> Result<()> {
let posts = post::load_all().await?; let posts = post::load_all().await?;
let state = Arc::new(AppState { tera, posts }); let state = Arc::new(AppState { tera, posts });
let app = handlers::routes(&state) let app = handlers::routes(&state)
.layer(TraceLayer::new_for_http()) .layer(TraceLayer::new_for_http())
.layer(CompressionLayer::new()) .layer(CompressionLayer::new())