Skip to content

Commit 4096b9d

Browse files
committed
nostr: add RelayUrl::domain method
Adds a method to retrieve the domain from a `RelayUrl` when applicable. Pull-Request: #914 Signed-off-by: Yuki Kishimoto <[email protected]>
1 parent 67f446c commit 4096b9d

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@
4343

4444
- nostr: add NIP-88 support ([Yuki Kishimoto] at https://github.com/rust-nostr/nostr/pull/892)
4545
- nostr: add `Nip11GetOptions` ([Yuki Kishimoto] at https://github.com/rust-nostr/nostr/pull/913)
46+
- nostr: add `RelayUrl::domain` method ([Yuki Kishimoto] at https://github.com/rust-nostr/nostr/pull/914)
4647

4748
### Fixed
4849

crates/nostr/src/types/url.rs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,26 @@ impl RelayUrl {
146146
.is_some_and(|host| host.ends_with(".onion"))
147147
}
148148

149+
/// If this URL has a host, and it is a domain name (not an IP address), return it.
150+
/// Non-ASCII domains are punycode-encoded per IDNA if this is the host
151+
/// of a special URL, or percent encoded for non-special URLs.
152+
///
153+
/// # Examples
154+
///
155+
/// ```
156+
/// use nostr::types::url::{Error, RelayUrl};
157+
///
158+
/// let url = RelayUrl::parse("wss://127.0.0.1:7777").unwrap();
159+
/// assert_eq!(url.domain(), None);
160+
///
161+
/// let url = RelayUrl::parse("wss://relay.example.com").unwrap();
162+
/// assert_eq!(url.domain(), Some("relay.example.com"));
163+
/// ```
164+
#[inline]
165+
pub fn domain(&self) -> Option<&str> {
166+
self.url.domain()
167+
}
168+
149169
/// Return the serialization of this relay URL without the trailing slash.
150170
///
151171
/// This method will always remove the trailing slash.
@@ -387,4 +407,19 @@ mod tests {
387407
let non_onion_url = RelayUrl::parse("ws://127.0.0.1:7777").unwrap();
388408
assert!(!non_onion_url.is_onion());
389409
}
410+
411+
#[test]
412+
fn test_domain() {
413+
let url = RelayUrl::parse("wss://example.com").unwrap();
414+
assert_eq!(url.domain(), Some("example.com"));
415+
416+
let url = RelayUrl::parse("wss://relay.example.com/").unwrap();
417+
assert_eq!(url.domain(), Some("relay.example.com"));
418+
419+
let url = RelayUrl::parse("wss://example.com/path/to/resource").unwrap();
420+
assert_eq!(url.domain(), Some("example.com"));
421+
422+
let url = RelayUrl::parse("wss://127.0.0.1:7777").unwrap();
423+
assert_eq!(url.domain(), None);
424+
}
390425
}

0 commit comments

Comments
 (0)