framework_web_axum/
context.rs1use anyhow::{Result, anyhow};
2use std::future::Future;
3use std::sync::Arc;
4
5#[derive(Debug, Clone)]
7pub struct AxumContext {
8 pub host: String,
10 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 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}