diff --git a/crates/bili_sync/src/config/default.rs b/crates/bili_sync/src/config/default.rs index 4a6c513..92aaf28 100644 --- a/crates/bili_sync/src/config/default.rs +++ b/crates/bili_sync/src/config/default.rs @@ -13,6 +13,6 @@ pub(super) fn default_auth_token() -> String { .collect() } -pub(super) fn default_bind_address() -> String { +pub(crate) fn default_bind_address() -> String { "0.0.0.0:12345".to_string() } diff --git a/crates/bili_sync/src/config/mod.rs b/crates/bili_sync/src/config/mod.rs index 16b372b..f0f43fc 100644 --- a/crates/bili_sync/src/config/mod.rs +++ b/crates/bili_sync/src/config/mod.rs @@ -8,6 +8,7 @@ mod versioned_config; pub use crate::config::args::{ARGS, version}; pub use crate::config::current::{CONFIG_DIR, Config}; +pub(crate) use crate::config::default::default_bind_address; pub use crate::config::handlebar::TEMPLATE; pub use crate::config::item::{ConcurrentDownloadLimit, NFOTimeType, PathSafeTemplate, RateLimit, Trigger}; pub use crate::config::versioned_cache::VersionedCache; diff --git a/crates/bili_sync/src/task/http_server.rs b/crates/bili_sync/src/task/http_server.rs index 48091be..0339123 100644 --- a/crates/bili_sync/src/task/http_server.rs +++ b/crates/bili_sync/src/task/http_server.rs @@ -13,7 +13,7 @@ use sea_orm::DatabaseConnection; use crate::api::{LogHelper, router}; use crate::bilibili::BiliClient; -use crate::config::VersionedConfig; +use crate::config::{VersionedConfig, default_bind_address}; #[derive(RustEmbed)] #[preserve_source = false] @@ -30,10 +30,29 @@ pub async fn http_server( .layer(Extension(database_connection)) .layer(Extension(bili_client)) .layer(Extension(log_writer)); - let bind_address = VersionedConfig::get().read().bind_address.to_owned(); - let listener = tokio::net::TcpListener::bind(&bind_address) - .await - .context("bind address failed")?; + let (bind_address, listener) = { + let bind_address = VersionedConfig::get().read().bind_address.to_owned(); + let listen_res = tokio::net::TcpListener::bind(&bind_address) + .await + .context("bind address failed"); + match listen_res { + Ok(listener) => (bind_address, listener), + Err(e) => { + let default_bind_address = default_bind_address(); + if default_bind_address == bind_address { + return Err(e); + } + warn!( + "绑定到地址 {} 失败:{:#},尝试绑定到默认地址 {}", + bind_address, e, default_bind_address + ); + let listener = tokio::net::TcpListener::bind(&default_bind_address) + .await + .context("bind default address failed")?; + (default_bind_address, listener) + } + } + }; info!("开始运行管理页:http://{}", bind_address); Ok(axum::serve(listener, ServiceExt::::into_make_service(app)).await?) }