Skip to content

Commit

Permalink
refactor: migrate from Extension to State
Browse files Browse the repository at this point in the history
  • Loading branch information
ttys3 committed Aug 22, 2022
1 parent dfaba1e commit 21cae16
Showing 1 changed file with 5 additions and 5 deletions.
10 changes: 5 additions & 5 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
use axum_macros::debug_handler;
use std::{net::SocketAddr, sync::Arc};
use std::net::SocketAddr;
use tower_http::trace::TraceLayer;

use crate::ResponseError::{BadRequest, FileNotFound, InternalError};
use askama::Template;

use axum::{
body::{Body, BoxBody},
extract::Extension,
extract::State,
http::{header, HeaderValue, Request, Response, StatusCode},
response::{Html, IntoResponse},
routing::get,
Expand Down Expand Up @@ -49,6 +49,7 @@ struct Opt {
port: u16,
}

#[derive(Clone)]
struct StaticServerConfig {
pub(crate) root_dir: String,
}
Expand All @@ -75,11 +76,10 @@ async fn main() {
root_dir = root_dir.trim_end_matches('/').to_string();
}

let app = Router::new()
let app = Router::with_state(StaticServerConfig { root_dir })
.route("/favicon.ico", get(favicon))
.route("/healthz", get(health_check))
.fallback(index_or_content)
.layer(Extension(Arc::new(StaticServerConfig { root_dir })))
.layer(TraceLayer::new_for_http().make_span_with(|request: &Request<Body>| {
let ConnectInfo(addr) = request.extensions().get::<ConnectInfo<SocketAddr>>().unwrap();
let empty_val = &HeaderValue::from_static("");
Expand Down Expand Up @@ -115,7 +115,7 @@ async fn favicon() -> impl IntoResponse {
// see https://docs.rs/axum/latest/axum/extract/index.html#applying-multiple-extractors
// see https://github.com/tokio-rs/axum/discussions/583#discussioncomment-1739582
#[debug_handler]
async fn index_or_content(Extension(cfg): Extension<Arc<StaticServerConfig>>, req: Request<Body>) -> impl IntoResponse {
async fn index_or_content(State(cfg): State<StaticServerConfig>, req: Request<Body>) -> impl IntoResponse {
let path = req.uri().path().to_string();
return match ServeDir::new(&cfg.root_dir).oneshot(req).await {
Ok(res) => {
Expand Down

0 comments on commit 21cae16

Please sign in to comment.