Struct url::Url [] [src]

pub struct Url {
    // some fields omitted
}

A parsed URL record.

Methods

impl Url

fn parse(input: &str) -> Result<Url, ParseError>

Parse an absolute URL from a string.

fn join(&self, input: &str) -> Result<Url, ParseError>

Parse a string as an URL, with this URL as the base URL.

fn options<'a>() -> ParseOptions<'a>

Return a default ParseOptions that can fully configure the URL parser.

fn as_str(&self) -> &str

Return the serialization of this URL.

This is fast since that serialization is already stored in the Url struct.

fn into_string(self) -> String

Return the serialization of this URL.

This consumes the Url and takes ownership of the String stored in it.

fn origin(&self) -> Origin

Return the origin of this URL (https://url.spec.whatwg.org/#origin)

Note: this return an opaque origin for file: URLs, which causes url.origin() != url.origin().

fn scheme(&self) -> &str

Return the scheme of this URL, lower-cased, as an ASCII string without the ':' delimiter.

fn has_authority(&self) -> bool

Return 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.socket or cannot-be-a-base like data:text/plain,Stuff.

fn cannot_be_a_base(&self) -> bool

Return 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 of data: and mailto: URLs.

fn username(&self) -> &str

Return the username for this URL (typically the empty string) as a percent-encoded ASCII string.

fn password(&self) -> Option<&str>

Return the password for this URL, if any, as a percent-encoded ASCII string.

fn has_host(&self) -> bool

Equivalent to url.host().is_some().

fn host_str(&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. IPv6 addresses are given between [ and ] brackets.

Cannot-be-a-base URLs (typical of data: and mailto:) and some file: URLs don’t have a host.

See also the host method.

fn host(&self) -> Option<Host<&str>>

Return the parsed representation of the host for this URL. Non-ASCII domain labels are punycode-encoded per IDNA.

Cannot-be-a-base URLs (typical of data: and mailto:) and some file: URLs don’t have a host.

See also the host_str method.

fn domain(&self) -> Option<&str>

If this URL has a host and it is a domain name (not an IP address), return it.

fn port(&self) -> Option<u16>

Return the port number for this URL, if any.

fn port_or_known_default(&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, wss, ftp, and gopher schemes.

For URLs in these schemes, this method always returns Some(_). For other schemes, it is the same as Url::port().

fn with_default_port<F>(&self, f: F) -> Result<HostAndPort<&str>> where F: FnOnce(&Url) -> Result<u16, ()>

If the URL has a host, return something that implements ToSocketAddrs.

If the URL has no port number and the scheme’s default port number is not known (see Url::port_or_known_default), the closure is called to obtain a port number. Typically, this closure can match on the result Url::scheme to have per-scheme default port numbers, and panic for schemes it’s not prepared to handle. For example:


fn connect(url: &Url) -> io::Result<TcpStream> {
    TcpStream::connect(try!(url.with_default_port(default_port)))
}

fn default_port(url: &Url) -> Result<u16, ()> {
    match url.scheme() {
        "git" => Ok(9418),
        "git+ssh" => Ok(22),
        "git+https" => Ok(443),
        "git+http" => Ok(80),
        _ => Err(()),
    }
}

fn path(&self) -> &str

Return 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.

fn path_segments(&self) -> Option<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 None for cannot-be-a-base URLs.

When Some is returned, the iterator always contains at least one string (which may be empty).

fn query(&self) -> Option<&str>

Return this URL’s query string, if any, as a percent-encoded ASCII string.

fn query_pairs(&self) -> Parse

Parse the URL’s query string, if any, as application/x-www-form-urlencoded and return an iterator of (key, value) pairs.

fn fragment(&self) -> Option<&str>

Return this URL’s fragment identifier, if any.

Note: the parser did not percent-encode this component, but the input may have been percent-encoded already.

fn set_fragment(&mut self, fragment: Option<&str>)

Change this URL’s fragment identifier.

fn set_query(&mut self, query: Option<&str>)

Change this URL’s query string.

fn query_pairs_mut(&mut self) -> Serializer<UrlQuery>

Manipulate this URL’s query string, viewed as a sequence of name/value pairs in application/x-www-form-urlencoded syntax.

The return value has a method-chaining API:

let mut url = Url::parse("https://example.net?lang=fr#nav").unwrap();
assert_eq!(url.query(), Some("lang=fr"));

url.query_pairs_mut().append_pair("foo", "bar");
assert_eq!(url.query(), Some("lang=fr&foo=bar"));
assert_eq!(url.as_str(), "https://example.net/?lang=fr&foo=bar#nav");

url.query_pairs_mut()
    .clear()
    .append_pair("foo", "bar & baz")
    .append_pair("saisons", "Été+hiver");
assert_eq!(url.query(), Some("foo=bar+%26+baz&saisons=%C3%89t%C3%A9%2Bhiver"));
assert_eq!(url.as_str(),
           "https://example.net/?foo=bar+%26+baz&saisons=%C3%89t%C3%A9%2Bhiver#nav");

Note: url.query_pairs_mut().clear(); is equivalent to url.set_query(Some("")), not url.set_query(None).

The state of Url is unspecified if this return value is leaked without being dropped.

fn set_path(&mut self, path: &str)

Change this URL’s path.

fn path_segments_mut(&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(&mut self, port: Option<u16>) -> Result<(), ()>

Change this URL’s port number.

If this URL is cannot-be-a-base, does not have a host, or has the file scheme; do nothing and return Err.

fn set_host(&mut self, host: Option<&str>) -> Result<(), ParseError>

Change this URL’s host.

If this URL is cannot-be-a-base or there is an error parsing the given host, do nothing and return Err.

Removing the host (calling this with None) will also remove any username, password, and port number.

fn set_ip_host(&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.

fn set_password(&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.

fn set_username(&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.

fn set_scheme(&mut self, scheme: &str) -> Result<(), ()>

Change this URL’s scheme.

Do nothing and return Err if: * The new scheme is not in [a-zA-Z][a-zA-Z0-9+.-]+ * This URL is cannot-be-a-base and the new scheme is one of http, https, ws, wss, ftp, or gopher

fn from_file_path<P: AsRef<Path>>(path: P) -> Result<Url, ()>

Convert a file name as std::path::Path into an URL in the file scheme.

This returns Err if the given path is not absolute or, on Windows, if the prefix is not a disk prefix (e.g. C:).

fn from_directory_path<P: AsRef<Path>>(path: P) -> Result<Url, ()>

Convert a directory name as std::path::Path into an URL in the file scheme.

This returns Err if the given path is not absolute or, on Windows, if the prefix is not a disk prefix (e.g. C:).

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 with Url::from_directory_path(Path::new("/var/www")) as the base URL is file:///var/www/index.html
  • "index.html" parsed with Url::from_file_path(Path::new("/var/www")) as the base URL is file:///var/index.html, which might not be what was intended.

Note that std::path does not consider trailing slashes significant and usually does not include them (e.g. in Path::parent()).

fn to_file_path(&self) -> Result<PathBuf, ()>

Assuming the URL is in the file scheme or similar, convert its path to an absolute std::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.

let path = url.to_file_path();

Returns Err if the host is neither empty nor "localhost", or if Path::new_opt() returns None. (That is, if the percent-decoded path contains a NUL byte or, for a Windows path, is not UTF-8.)

Trait Implementations

impl Index<RangeFull> for Url

type Output = str

fn index(&self, _: RangeFull) -> &str

impl Index<RangeFrom<Position>> for Url

type Output = str

fn index(&self, range: RangeFrom<Position>) -> &str

impl Index<RangeTo<Position>> for Url

type Output = str

fn index(&self, range: RangeTo<Position>) -> &str

impl Index<Range<Position>> for Url

type Output = str

fn index(&self, range: Range<Position>) -> &str

impl ToSocketAddrs for Url

Return an error if Url::host or Url::port_or_known_default return None.

type Iter = SocketAddrs

fn to_socket_addrs(&self) -> Result<Self::Iter>

impl FromStr for Url

Parse a string as an URL, without a base URL or encoding override.

type Err = ParseError

fn from_str(input: &str) -> Result<Url, ParseError>

impl Display for Url

Display the serialization of this URL.

fn fmt(&self, formatter: &mut Formatter) -> Result

impl Debug for Url

Debug the serialization of this URL.

fn fmt(&self, formatter: &mut Formatter) -> Result

impl Eq for Url

URLs compare like their serialization.

impl PartialEq for Url

URLs compare like their serialization.

fn eq(&self, other: &Self) -> bool

1.0.0fn ne(&self, other: &Rhs) -> bool

impl Ord for Url

URLs compare like their serialization.

fn cmp(&self, other: &Self) -> Ordering

impl PartialOrd for Url

URLs compare like their serialization.

fn partial_cmp(&self, other: &Self) -> Option<Ordering>

1.0.0fn lt(&self, other: &Rhs) -> bool

1.0.0fn le(&self, other: &Rhs) -> bool

1.0.0fn gt(&self, other: &Rhs) -> bool

1.0.0fn ge(&self, other: &Rhs) -> bool

impl Hash for Url

URLs hash like their serialization.

fn hash<H>(&self, state: &mut H) where H: Hasher

1.3.0fn hash_slice<H>(data: &[Self], state: &mut H) where H: Hasher

impl AsRef<str> for Url

Return the serialization of this URL.

fn as_ref(&self) -> &str

Derived Implementations

impl Clone for Url

fn clone(&self) -> Url

1.0.0fn clone_from(&mut self, source: &Self)