提取器

request hander中可以获取的数据类型实例,类似其他面向对象语言web框架控制器中获取注入的对象

// Path<T>就是框架默认的提取器
pub fn test(Path(id):Path<i32>){ ... }

自定义提取器例子

#[async_trait]
impl<S> FromRequestParts<S> for DatabaseConnection
    where
        ConnectionPool: FromRef<S>,
        S: Send + Sync,
{
    type Rejection = (StatusCode, String);

    async fn from_request_parts(_parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
        let pool = ConnectionPool::from_ref(state);

        let conn = pool.get_owned().await.map_err(internal_error)?;

        Ok(Self(conn))
    }
}

rust熟练工也很容易在提取器上出错,编译器无法给出详细的出错信息很难定位,官方专门提供了debug扩展

文档地址:https://docs.rs/axum/0.6.0/axum/extract/index.html#the-order-of-extractors

如何调试:https://docs.rs/axum-macros/latest/axum_macros/attr.debug_handler.html

// 安装扩展包axum-macros, 如果提取器出错,会提示详细错误信息
use axum_macros::debug_handler;
#[debug_handler]
pub async fn myhander(State(state):State<Appstate>){ ... }