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!(
37 "encore: no URL configured for gateway {gateway:?}: the app has no gateway with that name"
38 )
39 };
40 first_origin(Some(&gw.origins)).unwrap_or_else(|| {
41 panic!(
42 "encore: no URL configured for gateway {gateway:?}: this environment provides no origins for it"
43 )
44 })
45}
46
47/// A component's URL: the first of its `origins`, without a trailing slash.
48/// `None` for no component, or one with no origins.
49pub(crate) fn first_origin(origins: Option<&[String]>) -> Option<&str> {
50 let url = origins?.first()?.trim_end_matches('/');
51 (!url.is_empty()).then_some(url)
52}
53
54#[cfg(test)]
55mod tests {
56 use super::first_origin;
57
58 fn origins(list: &[&str]) -> Vec<String> {
59 list.iter().map(|s| s.to_string()).collect()
60 }
61
62 #[test]
63 fn the_url_is_the_first_origin_without_a_trailing_slash() {
64 let list = origins(&["https://example.com/", "https://*.example.com", "*"]);
65 assert_eq!(first_origin(Some(&list)), Some("https://example.com"));
66 let list = origins(&["http://web.localhost:4000"]);
67 assert_eq!(first_origin(Some(&list)), Some("http://web.localhost:4000"));
68 }
69
70 #[test]
71 fn no_component_or_no_origins_is_no_url() {
72 assert_eq!(first_origin(None), None);
73 assert_eq!(first_origin(Some(&[])), None);
74 assert_eq!(first_origin(Some(&origins(&[""]))), None);
75 }
76}