Struct Url
struct Url { ... }
A parsed URL record.
Implementations
impl Url
fn parse(input: &str) -> Result<Url, crate::ParseError>Parse an absolute URL from a string.
Examples
use Url; # use ParseError; # # run.unwrap;Errors
If the function can not parse an absolute URL from the given string, a
ParseErrorvariant will be returned.fn parse_with_params<I, K, V>(input: &str, iter: I) -> Result<Url, crate::ParseError> where I: IntoIterator, <I as >::Item: Borrow<(K, V)>, K: AsRef<str>, V: AsRef<str>Parse an absolute URL from a string and add params to its query string.
Existing params are not removed.
Examples
use Url; # use ParseError; # # run.unwrap;Errors
If the function can not parse an absolute URL from the given string, a
ParseErrorvariant will be returned.fn join(self: &Self, input: &str) -> Result<Url, crate::ParseError>Parse a string as an URL, with this URL as the base URL.
The inverse of this is
make_relative.Notes
- A trailing slash is significant. Without it, the last path component is considered to be a “file” name to be removed to get at the “directory” that is used as the base.
- A scheme relative special URL as input replaces everything in the base URL after the scheme.
- An absolute URL (with a scheme) as input replaces the whole base URL (even the scheme).
Examples
use Url; # use ParseError; // Base without a trailing slash # # run.unwrap;Errors
If the function can not parse an URL from the given string with this URL as the base URL, a
ParseErrorvariant will be returned.fn make_relative(self: &Self, url: &Url) -> Option<String>Creates a relative URL if possible, with this URL as the base URL.
This is the inverse of
join.Examples
use Url; # use ParseError; # # run.unwrap;Errors
If this URL can't be a base for the given URL,
Noneis returned. This is for example the case if the scheme, host or port are not the same.fn options<'a>() -> ParseOptions<'a>Return a default
ParseOptionsthat can fully configure the URL parser.Examples
Get default
ParseOptions, then change base urluse Url; # use ParseError; # # run.unwrap;fn as_str(self: &Self) -> &strReturn the serialization of this URL.
This is fast since that serialization is already stored in the
Urlstruct.Examples
use Url; # use ParseError; # # run.unwrap;fn into_string(self: Self) -> StringReturn the serialization of this URL.
This consumes the
Urland takes ownership of theStringstored in it.Examples
use Url; # use ParseError; # # run.unwrap;fn origin(self: &Self) -> OriginReturn the origin of this URL (https://url.spec.whatwg.org/#origin)
Note: this returns an opaque origin for
file:URLs, which causesurl.origin() != url.origin().Examples
URL with
ftpscheme:use ; # use ParseError; # # run.unwrap;URL with
blobscheme:use ; # use ParseError; # # run.unwrap;URL with
filescheme:use ; # use ParseError; # # run.unwrap;URL with other scheme:
use ; # use ParseError; # # run.unwrap;fn scheme(self: &Self) -> &strReturn the scheme of this URL, lower-cased, as an ASCII string without the ':' delimiter.
Examples
use Url; # use ParseError; # # run.unwrap;fn is_special(self: &Self) -> boolReturn whether the URL is special (has a special scheme)
Examples
use Url; # use ParseError; # # run.unwrap;fn has_authority(self: &Self) -> boolReturn whether the URL has an 'authority', which can contain a username, password, host, and port number.
URLs that do not are either path-only like
unix:/run/foo.socketor cannot-be-a-base likedata:text/plain,Stuff.See also the
authoritymethod.Examples
use Url; # use ParseError; # # run.unwrap;fn authority(self: &Self) -> &strReturn the authority of this URL as an ASCII string.
Non-ASCII domains are punycode-encoded per IDNA if this is the host of a special URL, or percent encoded for non-special URLs. IPv6 addresses are given between
[and]brackets. Ports are omitted if they match the well known port of a special URL.Username and password are percent-encoded.
See also the
has_authoritymethod.Examples
use Url; # use ParseError; # # run.unwrap;fn cannot_be_a_base(self: &Self) -> boolReturn whether this URL is a cannot-be-a-base URL, meaning that parsing a relative URL string with this URL as the base will return an error.
This is the case if the scheme and
:delimiter are not followed by a/slash, as is typically the case ofdata:andmailto:URLs.Examples
use Url; # use ParseError; # # run.unwrap;fn username(self: &Self) -> &strReturn the username for this URL (typically the empty string) as a percent-encoded ASCII string.
Examples
use Url; # use ParseError; # # run.unwrap;fn password(self: &Self) -> Option<&str>Return the password for this URL, if any, as a percent-encoded ASCII string.
Examples
use Url; # use ParseError; # # run.unwrap;fn has_host(self: &Self) -> boolEquivalent to
url.host().is_some().Examples
use Url; # use ParseError; # # run.unwrap;fn host_str(self: &Self) -> Option<&str>Return the string representation of the host (domain or IP address) for this URL, if any.
Non-ASCII domains are punycode-encoded per IDNA if this is the host of a special URL, or percent encoded for non-special URLs. IPv6 addresses are given between
[and]brackets.Cannot-be-a-base URLs (typical of
data:andmailto:) and somefile:URLs don’t have a host.See also the
hostmethod.Examples
use Url; # use ParseError; # # run.unwrap;fn host(self: &Self) -> Option<Host<&str>>Return the parsed representation of the host for this URL. Non-ASCII domain labels are punycode-encoded per IDNA if this is the host of a special URL, or percent encoded for non-special URLs.
Cannot-be-a-base URLs (typical of
data:andmailto:) and somefile:URLs don’t have a host.See also the
host_strmethod.Examples
use Url; # use ParseError; # # run.unwrap;fn domain(self: &Self) -> Option<&str>If this URL has a host and it is a domain name (not an IP address), return it. Non-ASCII domains are punycode-encoded per IDNA if this is the host of a special URL, or percent encoded for non-special URLs.
Examples
use Url; # use ParseError; # # run.unwrap;fn port(self: &Self) -> Option<u16>Return the port number for this URL, if any.
Note that default port numbers are never reflected by the serialization, use the
port_or_known_default()method if you want a default port number returned.Examples
use Url; # use ParseError; # # run.unwrap;fn port_or_known_default(self: &Self) -> Option<u16>Return the port number for this URL, or the default port number if it is known.
This method only knows the default port number of the
http,https,ws,wssandftpschemes.For URLs in these schemes, this method always returns
Some(_). For other schemes, it is the same asUrl::port().Examples
use Url; # use ParseError; # # run.unwrap;fn socket_addrs<impl Fn() -> Option<u16>: Fn() -> Option<u16>>(self: &Self, default_port_number: impl Fn() -> Option<u16>) -> io::Result<alloc::vec::Vec<SocketAddr>>Resolve a URL’s host and port number to
SocketAddr.If the URL has the default port number of a scheme that is unknown to this library,
default_port_numberprovides an opportunity to provide the actual port number. In non-example code this should be implemented either simply as|| None, or by matching on the URL’s.scheme().If the host is a domain, it is resolved using the standard library’s DNS support.
Examples
let url = url::Url::parse("https://example.net/").unwrap(); let addrs = url.socket_addrs(|| None).unwrap(); std::net::TcpStream::connect(&*addrs) # ;/// With application-specific known default port numbersfn path(self: &Self) -> &strReturn the path for this URL, as a percent-encoded ASCII string. For cannot-be-a-base URLs, this is an arbitrary string that doesn’t start with '/'. For other URLs, this starts with a '/' slash and continues with slash-separated path segments.
Examples
use ; # # run.unwrap;fn path_segments(self: &Self) -> Option<str::Split<'_, char>>Unless this URL is cannot-be-a-base, return an iterator of '/' slash-separated path segments, each as a percent-encoded ASCII string.
Return
Nonefor cannot-be-a-base URLs.When
Someis returned, the iterator always contains at least one string (which may be empty).Examples
use Url; # # use Error; # # use Error; # # run.unwrap;fn query(self: &Self) -> Option<&str>Return this URL’s query string, if any, as a percent-encoded ASCII string.
Examples
use Url; # use ParseError; # run.unwrap;fn query_pairs(self: &Self) -> form_urlencoded::Parse<'_>Parse the URL’s query string, if any, as
application/x-www-form-urlencodedand return an iterator of (key, value) pairs.Examples
use Cow; use Url; # use ParseError; # # run.unwrap;fn fragment(self: &Self) -> Option<&str>Return this URL’s fragment identifier, if any.
A fragment is the part of the URL after the
#symbol. The fragment is optional and, if present, contains a fragment identifier that identifies a secondary resource, such as a section heading of a document.In HTML, the fragment identifier is usually the id attribute of a an element that is scrolled to on load. Browsers typically will not send the fragment portion of a URL to the server.
Note: the parser did not percent-encode this component, but the input may have been percent-encoded already.
Examples
use Url; # use ParseError; # # run.unwrap;fn set_fragment(self: &mut Self, fragment: Option<&str>)Change this URL’s fragment identifier.
Examples
use Url; # use ParseError; # # run.unwrap;fn set_query(self: &mut Self, query: Option<&str>)Change this URL’s query string. If
queryisNone, this URL's query string will be cleared.Examples
use Url; # use ParseError; # # run.unwrap;fn query_pairs_mut(self: &mut Self) -> form_urlencoded::Serializer<'_, UrlQuery<'_>>Manipulate this URL’s query string, viewed as a sequence of name/value pairs in
application/x-www-form-urlencodedsyntax.The return value has a method-chaining API:
# use ; # # run.unwrap;Note:
url.query_pairs_mut().clear();is equivalent tourl.set_query(Some("")), noturl.set_query(None).The state of
Urlis unspecified if this return value is leaked without being dropped.fn set_path(self: &mut Self, path: &str)Change this URL’s path.
Examples
use Url; # use ParseError; # # run.unwrap;fn path_segments_mut(self: &mut Self) -> Result<PathSegmentsMut<'_>, ()>Return an object with methods to manipulate this URL’s path segments.
Return
Err(())if this URL is cannot-be-a-base.fn set_port(self: &mut Self, port: Option<u16>) -> Result<(), ()>Change this URL’s port number.
Note that default port numbers are not reflected in the serialization.
If this URL is cannot-be-a-base, does not have a host, or has the
filescheme; do nothing and returnErr.Examples
use Url; # # use Error; # # use Error; # # run.unwrap;Known default port numbers are not reflected:
use Url; # # use Error; # # use Error; # # run.unwrap;Cannot set port for cannot-be-a-base URLs:
use Url; # use ParseError; # # run.unwrap;fn set_host(self: &mut Self, host: Option<&str>) -> Result<(), ParseError>Change this URL’s host.
Removing the host (calling this with
None) will also remove any username, password, and port number.Examples
Change host:
use Url; # use ParseError; # # run.unwrap;Remove host:
use Url; # use ParseError; # # run.unwrap;Cannot remove host for 'special' schemes (e.g.
http):use Url; # use ParseError; # # run.unwrap;Cannot change or remove host for cannot-be-a-base URLs:
use Url; # use ParseError; # # run.unwrap;Errors
If this URL is cannot-be-a-base or there is an error parsing the given
host, aParseErrorvariant will be returned.fn set_ip_host(self: &mut Self, address: IpAddr) -> Result<(), ()>Change this URL’s host to the given IP address.
If this URL is cannot-be-a-base, do nothing and return
Err.Compared to
Url::set_host, this skips the host parser.Examples
use ; # # run.unwrap;Cannot change URL's from mailto(cannot-be-base) to ip:
use ; # # run.unwrap;fn set_password(self: &mut Self, password: Option<&str>) -> Result<(), ()>Change this URL’s password.
If this URL is cannot-be-a-base or does not have a host, do nothing and return
Err.Examples
use ; # # run.unwrap;fn set_username(self: &mut Self, username: &str) -> Result<(), ()>Change this URL’s username.
If this URL is cannot-be-a-base or does not have a host, do nothing and return
Err.Examples
Cannot setup username from mailto(cannot-be-base)
use ; # # run.unwrap;Setup username to user1
use ; # # run.unwrap;fn set_scheme(self: &mut Self, scheme: &str) -> Result<(), ()>Change this URL’s scheme.
Do nothing and return
Errunder the following circumstances:- If the new scheme is not in
[a-zA-Z][a-zA-Z0-9+.-]+ - If this URL is cannot-be-a-base and the new scheme is one of
http,https,ws,wssorftp - If either the old or new scheme is
http,https,ws,wssorftpand the other is not one of these - If the new scheme is
fileand this URL includes credentials or has a non-null port - If this URL's scheme is
fileand its host is empty or null
See also the URL specification's section on legal scheme state overrides.
Examples
Change the URL’s scheme from
httpstohttp:use Url; # use ParseError; # # run.unwrap;Change the URL’s scheme from
footobar:use Url; # use ParseError; # # run.unwrap;Cannot change URL’s scheme from
httpstofoõ:use Url; # use ParseError; # # run.unwrap;Cannot change URL’s scheme from
mailto(cannot-be-a-base) tohttps:use Url; # use ParseError; # # run.unwrap;Cannot change the URL’s scheme from
footohttps:use Url; # use ParseError; # # run.unwrap;Cannot change the URL’s scheme from
httptofoo:use Url; # use ParseError; # # run.unwrap;- If the new scheme is not in
fn from_file_path<P: AsRef<std::path::Path>>(path: P) -> Result<Url, ()>Convert a file name as
std::path::Pathinto an URL in thefilescheme.This returns
Errif the given path is not absolute or, on Windows, if the prefix is not a disk prefix (e.g.C:) or a UNC prefix (\\).Examples
On Unix-like platforms:
# if cfg!This method is only available if the
stdCargo feature is enabled.fn from_directory_path<P: AsRef<std::path::Path>>(path: P) -> Result<Url, ()>Convert a directory name as
std::path::Pathinto an URL in thefilescheme.This returns
Errif the given path is not absolute or, on Windows, if the prefix is not a disk prefix (e.g.C:) or a UNC prefix (\\).Compared to
from_file_path, this ensure that URL’s the path has a trailing slash so that the entire path is considered when using this URL as a base URL.For example:
"index.html"parsed withUrl::from_directory_path(Path::new("/var/www"))as the base URL isfile:///var/www/index.html"index.html"parsed withUrl::from_file_path(Path::new("/var/www"))as the base URL isfile:///var/index.html, which might not be what was intended.
Note that
std::pathdoes not consider trailing slashes significant and usually does not include them (e.g. inPath::parent()).This method is only available if the
stdCargo feature is enabled.fn serialize_internal<S>(self: &Self, serializer: S) -> Result<<S as >::Ok, <S as >::Error> where S: serde::SerializerSerialize with Serde using the internal representation of the
Urlstruct.The corresponding
deserialize_internalmethod sacrifices some invariant-checking for speed, compared to theDeserializetrait impl.This method is only available if the
serdeCargo feature is enabled.fn deserialize_internal<'de, D>(deserializer: D) -> Result<Self, <D as >::Error> where D: serde::Deserializer<'de>Serialize with Serde using the internal representation of the
Urlstruct.The corresponding
deserialize_internalmethod sacrifices some invariant-checking for speed, compared to theDeserializetrait impl.This method is only available if the
serdeCargo feature is enabled.fn to_file_path(self: &Self) -> Result<PathBuf, ()>Assuming the URL is in the
filescheme or similar, convert its path to an absolutestd::path::Path.Note: This does not actually check the URL’s
scheme, and may give nonsensical results for other schemes. It is the user’s responsibility to check the URL’s scheme before calling this.# use Url; # let url = parse.unwrap; let path = url.to_file_path;Returns
Errif the host is neither empty nor"localhost"(except on Windows, wherefile:URLs may have a non-local host), or ifPath::new_opt()returnsNone. (That is, if the percent-decoded path contains a NUL byte or, for a Windows path, is not UTF-8.)This method is only available if the
stdCargo feature is enabled.
impl AsRef for Url
fn as_ref(self: &Self) -> &str
impl Clone for Url
fn clone(self: &Self) -> Url
impl Debug for Url
fn fmt(self: &Self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result
impl Display for Url
fn fmt(self: &Self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result
impl Eq for Url
impl Freeze for Url
impl FromStr for Url
fn from_str(input: &str) -> Result<Url, crate::ParseError>
impl Hash for Url
fn hash<H>(self: &Self, state: &mut H) where H: hash::Hasher
impl Index for crate::Url
fn index(self: &Self, range: RangeFrom<Position>) -> &str
impl Index for crate::Url
fn index(self: &Self, range: Range<Position>) -> &str
impl Index for crate::Url
fn index(self: &Self, _: RangeFull) -> &str
impl Index for crate::Url
fn index(self: &Self, range: RangeTo<Position>) -> &str
impl Ord for Url
fn cmp(self: &Self, other: &Self) -> cmp::Ordering
impl PartialEq for Url
fn eq(self: &Self, other: &Self) -> bool
impl PartialOrd for Url
fn partial_cmp(self: &Self, other: &Self) -> Option<cmp::Ordering>
impl RefUnwindSafe for Url
impl Send for Url
impl Serialize for Url
fn serialize<S>(self: &Self, serializer: S) -> Result<<S as >::Ok, <S as >::Error> where S: serde::Serializer
impl Sync for Url
impl Unpin for Url
impl UnwindSafe for Url
impl<'a> TryFrom for Url
fn try_from(s: &'a str) -> Result<Self, <Self as >::Error>
impl<'de> Deserialize for Url
fn deserialize<D>(deserializer: D) -> Result<Url, <D as >::Error> where D: serde::Deserializer<'de>
impl<T> Any for Url
fn type_id(self: &Self) -> TypeId
impl<T> Borrow for Url
fn borrow(self: &Self) -> &T
impl<T> BorrowMut for Url
fn borrow_mut(self: &mut Self) -> &mut T
impl<T> CloneToUninit for Url
unsafe fn clone_to_uninit(self: &Self, dest: *mut u8)
impl<T> DeserializeOwned for Url
impl<T> ErasedDestructor for Url
impl<T> From for Url
fn from(t: T) -> TReturns the argument unchanged.
impl<T> ToOwned for Url
fn to_owned(self: &Self) -> Tfn clone_into(self: &Self, target: &mut T)
impl<T> ToString for Url
fn to_string(self: &Self) -> String
impl<T, U> Into for Url
fn into(self: Self) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses to do.
impl<T, U> TryFrom for Url
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
impl<T, U> TryInto for Url
fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error>