encore/gateways.rs
1//! Resolving URLs for the application's API gateways.
2//!
3//! Call [`url`] to get a gateway's public base URL in the current environment,
4//! for example to share a webhook or API address with an external client:
5//!
6//! ```ignore
7//! use encore::gateways;
8//!
9//! let callback = format!("{}/webhooks/stripe", gateways::url("api"));
10//! ```
11//!
12//! To call another service inside the application, use [`crate::services`]
13//! rather than going through a gateway.
14//!
15//! Looking up a gateway URL records a dependency from the calling service to
16//! that gateway. Because Encore parses this dependency statically, pass the
17//! gateway's declared name as a string literal, call `gateways::url` directly
18//! (rather than through a function pointer), and make the call inside a service.
19
20/// Returns the base URL for `gateway` in the current environment, without a
21/// trailing slash (so paths can be appended directly, e.g.
22/// `{url}/webhooks/stripe`).
23///
24/// This returns the first origin listed for the gateway in
25/// [`crate::env::app_meta`]. `gateway` must match the exact name declared in
26/// `encore.gateway.json` or the hosting service (for example, `public_api` does
27/// not match `public-api`).
28///
29/// # Panics
30///
31/// Panics if no URL is configured for `gateway` — either because the app has no
32/// gateway with that name or because the environment provides no origins for it.
33pub fn url(gateway: &str) -> &'static str {
34 let meta = crate::runtime::core().app_meta();
35 let Some(gw) = meta.gateway(gateway) else {
36 panic!("encore: no URL configured for gateway {gateway:?}: the app has no gateway with that name")
37 };
38 first_origin(Some(&gw.origins)).unwrap_or_else(|| {
39 panic!(
40 "encore: no URL configured for gateway {gateway:?}: this environment provides no origins for it"
41 )
42 })
43}
44
45/// A component's URL: the first of its `origins`, without a trailing slash.
46/// `None` for no component, or one with no origins.
47pub(crate) fn first_origin(origins: Option<&[String]>) -> Option<&str> {
48 let url = origins?.first()?.trim_end_matches('/');
49 (!url.is_empty()).then_some(url)
50}
51
52#[cfg(test)]
53mod tests {
54 use super::first_origin;
55
56 fn origins(list: &[&str]) -> Vec<String> {
57 list.iter().map(|s| s.to_string()).collect()
58 }
59
60 #[test]
61 fn the_url_is_the_first_origin_without_a_trailing_slash() {
62 let list = origins(&["https://example.com/", "https://*.example.com", "*"]);
63 assert_eq!(first_origin(Some(&list)), Some("https://example.com"));
64 let list = origins(&["http://web.localhost:4000"]);
65 assert_eq!(first_origin(Some(&list)), Some("http://web.localhost:4000"));
66 }
67
68 #[test]
69 fn no_component_or_no_origins_is_no_url() {
70 assert_eq!(first_origin(None), None);
71 assert_eq!(first_origin(Some(&[])), None);
72 assert_eq!(first_origin(Some(&origins(&[""]))), None);
73 }
74}