Skip to main content

App

Struct App 

Source
pub struct App { /* private fields */ }
Expand description

App 构建器 —— 框架唯一入口,配置驱动,一行启动

无需任何泛型,全局资源单例访问。

§示例

App::new()?
    .get("/", || async { Res::ok("Hello") })
    .start()
    .await

Implementations§

Source§

impl App

Source

pub fn new() -> Result<Self>

从默认 config/ 目录加载配置并构建 App

等价于 App::from_config_dir("config")

§示例
App::new()?
    .get("/", || async { Res::ok("Hello") })
    .start()
    .await
Source

pub fn from_config() -> Result<Self>

从默认目录 config/ 加载配置,自动初始化日志、数据库、缓存

Source

pub fn from_config_dir(dir: &str) -> Result<Self>

从指定目录加载配置

Source

pub fn with_config(cfg: AppConfig) -> Result<Self>

使用给定的 AppConfig 构建(跳过文件加载)

Source

pub fn with_config_manager(cm: Arc<ConfigManager>) -> Result<Self>

使用给定的 ConfigManager 构建 App

公开方法,用于手动构建 App 的场景

Source

pub fn parse_cli(self) -> Self

解析 CLI 参数(--gen-config / --print-config

需在 start() 之前调用。

Source

pub fn get<H, T>(self, path: &str, handler: H) -> Self
where H: Handler<T, ()>, T: 'static,

注册 GET 路由,返回 Self 以支持链式调用

Source

pub fn post<H, T>(self, path: &str, handler: H) -> Self
where H: Handler<T, ()>, T: 'static,

注册 POST 路由,返回 Self 以支持链式调用

Source

pub fn put<H, T>(self, path: &str, handler: H) -> Self
where H: Handler<T, ()>, T: 'static,

注册 PUT 路由,返回 Self 以支持链式调用

Source

pub fn delete<H, T>(self, path: &str, handler: H) -> Self
where H: Handler<T, ()>, T: 'static,

注册 DELETE 路由,返回 Self 以支持链式调用

Source

pub fn route<H, T>(self, method: &str, path: &str, handler: H) -> Self
where H: Handler<T, ()>, T: 'static,

通用路由注册 —— 用字符串指定 HTTP 方法

§示例
App::new()?
    .route("PATCH", "/api/data", patch_handler)
    .start()
    .await
Source

pub fn group(self, prefix: &str, f: impl FnOnce(Self) -> Self) -> Self

路由分组 —— 将一组路由归到同一前缀下

§示例
App::new()?
    .group("/api/v2", |app| {
        app.get("/users", list_users)
           .post("/users", create_user)
    })
    .start()
    .await
Source

pub fn scan(self) -> Self

扫描 #[get]#[post]#[controller] 等宏注解,自动注册路由

编译期通过 linkme 分布式切片收集所有被宏标注的处理器。

§示例
#[alun::get("/api/hello")]
async fn hello() -> Res<String> { Res::ok("Hi!") }

App::new()?
    .scan()
    .start()
    .await
Source

pub fn merge(self, prefix: &str, sub: AlunRouter) -> Self

合并子路由(与 group 类似,但接受已构建好的 AlunRouter)

Source

pub fn with_permission<H, T>( self, method: &str, path: &str, handler: H, permission: &str, ) -> Self
where H: Handler<T, ()>, T: 'static,

注册需要特定权限的 GET 路由 —— 方法级权限拦截

对标 axum 的 get(handler).route_layer(RequirePermissionLayer)

§示例
App::new()?
    .with_permission("GET", "/api/admin/stats", admin_stats, "admin:access")
    .start()
    .await
Source

pub fn with_role<H, T>( self, method: &str, path: &str, handler: H, role: &str, ) -> Self
where H: Handler<T, ()>, T: 'static,

注册需要特定角色的 GET 路由 —— 方法级角色拦截

§示例
App::new()?
    .with_role("GET", "/api/admin/users", list_users, "admin")
    .start()
    .await
Source

pub fn plugin<P: Plugin + 'static>(self, plugin: P) -> Self

注册插件(数据库、缓存、Kafka 等)

插件在 start() 时按拓扑顺序自动启动,在 shutdown 时逆序关闭。

Source

pub fn on_startup<F, Fut>(self, hook: F) -> Self
where F: FnOnce() -> Fut + Send + 'static, Fut: Future<Output = ()> + Send + 'static,

注册自定义启动钩子

钩子在全局资源初始化之后、插件启动之前调用,可在此阶段初始化自定义全局资源。

§示例
App::new()?
    .on_startup(|| async {
        init_my_globals();
    })
    .scan()
    .start()
    .await
Source

pub fn with_middleware_hook<F>(self, hook: F) -> Self
where F: FnOnce(Router) -> Router + Send + 'static,

注册自定义中间件注入钩子

钩子在 build_middleware_chain 之后调用,可在此阶段通过 axum::middleware::from_fn 注入自定义中间件。

§示例
App::new()?
    .with_middleware_hook(|router| {
        router.layer(axum::middleware::from_fn(my_middleware))
    })
    .scan()
    .start()
    .await
Source

pub async fn start(self) -> Result<()>

启动应用——无参,端口从 config.toml 的 [server] 节读取

Source

pub async fn serve(self, addr: impl Into<String>) -> Result<()>

指定监听地址启动(用于需要自定义地址的场景)

Trait Implementations§

Source§

impl Default for App

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl Freeze for App

§

impl !RefUnwindSafe for App

§

impl Send for App

§

impl !Sync for App

§

impl Unpin for App

§

impl UnsafeUnpin for App

§

impl !UnwindSafe for App

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,