Skip to content

Commit

Permalink
infer app base strictly as documented
Browse files Browse the repository at this point in the history
  • Loading branch information
shouya committed Sep 28, 2024
1 parent 2d5f858 commit 7f36b4d
Showing 1 changed file with 33 additions and 1 deletion.
34 changes: 33 additions & 1 deletion src/server/endpoint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,10 +188,21 @@ impl EndpointParam {
}

fn get_base(req: &Parts) -> Option<Url> {
if let Some(url) = Self::base_from_env().as_ref() {
return Some(url.clone());
}

if let Some(url) = Self::base_from_reverse_proxy(req) {
return Some(url);
}

Self::base_from_host(req)
}

fn base_from_reverse_proxy(req: &Parts) -> Option<Url> {
let host = req
.headers
.get("X-Forwarded-Host")
.or_else(|| req.headers.get(HOST))
.and_then(|x| x.to_str().ok())?;

let proto = req
Expand All @@ -204,6 +215,27 @@ impl EndpointParam {
let base = base.parse().ok()?;
Some(base)
}

fn base_from_host(req: &Parts) -> Option<Url> {
let host = req.headers.get(HOST)?.to_str().ok()?;
let base = format!("http://{}/", host);
let base = base.parse().ok()?;
Some(base)
}

fn base_from_env() -> &'static Option<Url> {
use std::env;
use std::sync::OnceLock;

static APP_BASE_URL: OnceLock<Option<Url>> = OnceLock::new();
APP_BASE_URL.get_or_init(|| {
let var = env::var("RSS_FUNNEL_APP_BASE").ok();
var.map(|v| {
v.parse()
.expect("Invalid base url specified in RSS_FUNNEL_APP_BASE")
})
})
}
}

impl Service<Request> for EndpointService {
Expand Down

0 comments on commit 7f36b4d

Please sign in to comment.