fix(axum): route response

This commit is contained in:
xfy
2024-10-21 10:05:00 +08:00
parent 602c7f0fde
commit 5b681d5cfc
3 changed files with 23 additions and 6 deletions

View File

@ -1,4 +1,4 @@
use std::time::Duration; use std::{fmt::Display, time::Duration};
use axum::{ use axum::{
body::Bytes, body::Bytes,
@ -69,3 +69,15 @@ pub fn logging_route(router: Router) -> Router {
router.layer(trace_layer) router.layer(trace_layer)
} }
/// Format request latency and status message
/// return a string
fn format_latency(latency: Duration, status: impl Display) -> String {
let micros = latency.as_micros();
let millis = latency.as_millis();
if micros >= 1000 {
format!("{} {}ms", status, millis)
} else {
format!("{} {}μs", status, micros)
}
}

View File

@ -1,13 +1,11 @@
use std::{borrow::Cow, collections::HashMap, time::Duration}; use std::{borrow::Cow, time::Duration};
use axum::{ use axum::{
async_trait, http::{StatusCode, Uri},
extract::{FromRequestParts, Path},
http::{request::Parts, StatusCode, Uri},
middleware, middleware,
response::{IntoResponse, Response}, response::{IntoResponse, Response},
routing::get, routing::get,
Json, RequestPartsExt, Router, Json, Router,
}; };
use serde::Serialize; use serde::Serialize;
use tower::ServiceBuilder; use tower::ServiceBuilder;
@ -21,6 +19,7 @@ use crate::{
pub mod json; pub mod json;
pub mod text; pub mod text;
pub mod user;
#[derive(Debug, Serialize)] #[derive(Debug, Serialize)]
pub struct RouteResponse<T> pub struct RouteResponse<T>
@ -72,3 +71,8 @@ pub fn routes() -> Router {
pub async fn hello() -> String { pub async fn hello() -> String {
format!("hello {}", env!("CARGO_PKG_NAME")) format!("hello {}", env!("CARGO_PKG_NAME"))
} }
pub async fn fallback(uri: Uri) -> impl IntoResponse {
info!("route {} not found", uri);
(StatusCode::NOT_FOUND, "Not found")
}

View File

@ -0,0 +1 @@