perseus/utils/
path_prefix.rs

1/// Gets the path prefix to apply on the server. This uses the
2/// `PERSEUS_BASE_PATH` environment variable, which avoids hardcoding
3/// something as changeable as this into the final binary. Hence however, that
4/// variable must be the same as what's set in `<base>` (done automatically).
5/// Trailing forward slashes will be trimmed automatically.
6#[cfg(engine)]
7pub fn get_path_prefix_server() -> String {
8    use std::env;
9
10    let base_path = env::var("PERSEUS_BASE_PATH").unwrap_or_else(|_| "".to_string());
11    base_path
12        .strip_suffix('/')
13        .unwrap_or(&base_path)
14        .to_string()
15}
16
17/// Gets the path prefix to apply in the browser. This uses the HTML `<base>`
18/// element, which would be required anyway to make Sycamore's router co-operate
19/// with a relative path hosting.
20#[cfg(any(client, doc))]
21pub fn get_path_prefix_client() -> String {
22    use wasm_bindgen::JsCast;
23    use web_sys::{HtmlBaseElement, Url};
24
25    let base_path = match web_sys::window()
26        .unwrap()
27        .document()
28        .unwrap()
29        .query_selector("base[href]")
30    {
31        Ok(Some(base)) => {
32            let base = base.unchecked_into::<HtmlBaseElement>().href();
33
34            let url = Url::new(&base).unwrap();
35            url.pathname()
36        }
37        _ => "".to_string(),
38    };
39    // Strip any trailing slashes, a `//` makes the browser query `https://.perseus/...`
40    base_path
41        .strip_suffix('/')
42        .unwrap_or(&base_path)
43        .to_string()
44}