sinan 0.1.0

A Boilerplate for Rapid Axum Web Service Deployment.
Documentation
use std::any::Any;
use std::borrow::Cow;

use http::StatusCode;
use tower_http::BoxError;

pub use response::Response;

pub mod request;
mod response;

pub mod middleware;

pub type Request = request::Request<axum::extract::Request>;

pub fn response() -> Response {
    Response::default()
}

pub async fn fallback() -> axum::response::Response {
    response().code(StatusCode::NOT_FOUND).json()
}

pub async fn error(error: BoxError) -> axum::response::Response {
    let mut response = Response::default();

    if error.is::<tower::timeout::error::Elapsed>() {
        // todo 不能改成引入 error.is::<Elapsed> ?
        response.code(StatusCode::REQUEST_TIMEOUT);
    } else {
        response.code(StatusCode::INTERNAL_SERVER_ERROR);
        response.message(format!("Unhandled internal error: {error}"));
    }

    response.json()
}

pub fn panic(error: Box<dyn Any + Send + 'static>) -> axum::response::Response {
    let details = if let Some(s) = error.downcast_ref::<String>() {
        Cow::Owned(s.to_owned())
    } else if let Some(s) = error.downcast_ref::<&str>() {
        Cow::Borrowed(*s)
    } else {
        Cow::Borrowed("Unknown panic message")
    };

    response()
        .code(StatusCode::INTERNAL_SERVER_ERROR)
        .message(details)
        .json()
}