Skip to main content

framework_web_axum/
context.rs

1use anyhow::{Result, anyhow};
2use std::future::Future;
3use std::sync::Arc;
4
5/// Axum 服务上下文。
6#[derive(Debug, Clone)]
7pub struct AxumContext {
8    /// 绑定地址。
9    pub host: String,
10    /// 实际绑定端口,传入随机端口时用于感知真实端口。
11    pub port: u16,
12}
13
14impl AxumContext {
15    pub fn new(host: impl Into<String>, port: u16) -> Self {
16        Self {
17            host: host.into(),
18            port,
19        }
20    }
21
22    /// 服务地址,形如 `127.0.0.1:8080`。
23    pub fn address(&self) -> String {
24        format!("{}:{}", self.host, self.port)
25    }
26}
27
28tokio::task_local! {
29    static AXUM_CONTEXT: Arc<AxumContext>;
30}
31
32pub async fn scope_axum<F>(context: Arc<AxumContext>, future: F) -> F::Output
33where
34    F: Future,
35{
36    AXUM_CONTEXT.scope(context, future).await
37}
38
39pub fn use_axum() -> Result<Arc<AxumContext>> {
40    AXUM_CONTEXT
41        .try_with(Arc::clone)
42        .map_err(|error| anyhow!("当前调用不在 Axum 上下文作用域内:{error}"))
43}