feat: generate OpenAPI server URL from SITE_DOMAIN at startup

This commit is contained in:
NetworkCats
2026-03-04 05:12:45 +08:00
parent ea291f3d30
commit b67edf5a32
4 changed files with 25 additions and 15 deletions
+1 -10
View File
@@ -8,16 +8,7 @@
"name": "MIT"
}
},
"servers": [
{
"url": "https://{domain}",
"variables": {
"domain": {
"default": "localhost:3000"
}
}
}
],
"servers": [],
"paths": {
"/json": {
"get": {
+14 -2
View File
@@ -24,6 +24,7 @@ pub struct AppState {
pub db: SharedDb,
pub site_domain: Arc<str>,
pub dev_mode: bool,
pub openapi_json: Arc<str>,
}
#[derive(Template)]
@@ -329,14 +330,25 @@ pub async fn tor_handler(
Ok(format!("{}\n", proxy.is_tor))
}
pub async fn openapi_json() -> Response {
pub async fn openapi_json(State(state): State<AppState>) -> Response {
(
[(header::CONTENT_TYPE, "application/json; charset=utf-8")],
include_str!("../openapi.json"),
String::from(state.openapi_json.as_ref()),
)
.into_response()
}
pub fn build_openapi_json(site_domain: &str) -> Arc<str> {
let mut spec: serde_json::Value =
serde_json::from_str(include_str!("../openapi.json")).expect("openapi.json must be valid");
let server_url = format!("https://{site_domain}");
spec["servers"] = serde_json::json!([{ "url": server_url }]);
let json = serde_json::to_string_pretty(&spec).expect("serialization cannot fail");
Arc::from(json)
}
pub async fn robots_txt(State(state): State<AppState>) -> Response {
let body = format!(
"User-agent: *\n\
+5 -1
View File
@@ -43,10 +43,14 @@ async fn main() {
cancel.clone(),
);
let site_domain: std::sync::Arc<str> = config.site_domain.into();
let openapi_json = handlers::build_openapi_json(&site_domain);
let state = handlers::AppState {
db: shared_db,
site_domain: config.site_domain.into(),
site_domain,
dev_mode: config.dev_mode,
openapi_json,
};
let app = routes::build_router(state);
+5 -2
View File
@@ -5,7 +5,7 @@ use http_body_util::BodyExt;
use tower::ServiceExt;
use rustyip::db;
use rustyip::handlers::AppState;
use rustyip::handlers::{AppState, build_openapi_json};
use rustyip::routes::build_router;
fn test_db_path() -> String {
@@ -24,10 +24,13 @@ fn build_test_app() -> axum::Router {
fn build_test_app_with_dev_mode(dev_mode: bool) -> axum::Router {
let reader = db::load_db(Path::new(&test_db_path())).expect("failed to load test DB");
let shared_db = db::new_shared(reader);
let site_domain: std::sync::Arc<str> = "test.example.com".into();
let openapi_json = build_openapi_json(&site_domain);
let state = AppState {
db: shared_db,
site_domain: "test.example.com".into(),
site_domain,
dev_mode,
openapi_json,
};
build_router(state)
}