@@ -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