Struct url::Url [] [src]

pub struct Url { /* fields omitted */ }

A parsed URL record.

Methods

impl Url
[src]

Parse an absolute URL from a string.

Examples

use url::Url;

let url = Url::parse("https://example.net").unwrap();

Parse an absolute URL from a string and add params to its query string.

Existing params are not removed.

Examples

use url::Url;

let url = Url::parse_with_params("https://example.net?dont=clobberme",
                                 &[("lang", "rust"), ("browser", "servo")]);

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

Examples

use url::Url;

let url = Url::parse("https://example.net").unwrap();
let url = url.join("foo").unwrap();
assert_eq!(url.as_str(), "https://example.net/foo");

Trailing slashes are not preserved:

use url::Url;

let url = Url::parse("https://example.net/foo/").unwrap();
let url = url.join("bar").unwrap();
assert_eq!(url.as_str(), "https://example.net/foo/bar");

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

Return the serialization of this URL.

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

Examples

use url::Url;

let url_str = "https://example.net/";
let url = Url::parse(url_str).unwrap();
assert_eq!(url.as_str(), url_str);

Return the serialization of this URL.

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

Examples

use url::Url;

let url_str = "https://example.net/";
let url = Url::parse(url_str).unwrap();
assert_eq!(url.into_string(), url_str);

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

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

Examples

URL with ftp scheme:

use url::{Host, Origin, Url};

let url = Url::parse("ftp://example.com/foo").unwrap();
assert_eq!(url.origin(),
           Origin::Tuple("ftp".into(),
                         Host::Domain("example.com".into()),
                         21));

URL with blob scheme:

use url::{Host, Origin, Url};

let url = Url::parse("blob:https://example.com/foo").unwrap();
assert_eq!(url.origin(),
           Origin::Tuple("https".into(),
                         Host::Domain("example.com".into()),
                         443));

URL with file scheme:

use url::{Host, Origin, Url};

let url = Url::parse("file:///tmp/foo").unwrap();
assert!(!url.origin().is_tuple());

let other_url = Url::parse("file:///tmp/foo").unwrap();
assert!(url.origin() != other_url.origin());

URL with other scheme:

use url::{Host, Origin, Url};

let url = Url::parse("foo:bar").unwrap();
assert!(!url.origin().is_tuple());

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

Examples

use url::Url;

let url = Url::parse("file:///tmp/foo").unwrap();
assert_eq!(url.scheme(), "file");

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.

Examples

use url::Url;

let url = Url::parse("ftp://rms@example.com").unwrap();
assert!(url.has_authority());

let url = Url::parse("unix:/run/foo.socket").unwrap();
assert!(!url.has_authority());

let url = Url::parse("data:text/plain,Stuff").unwrap();
assert!(!url.has_authority());

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.

Examples

use url::Url;

let url = Url::parse("ftp://rms@example.com").unwrap();
assert!(!url.cannot_be_a_base());

let url = Url::parse("unix:/run/foo.socket").unwrap();
assert!(!url.cannot_be_a_base());

let url = Url::parse("data:text/plain,Stuff").unwrap();
assert!(url.cannot_be_a_base());

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

Examples

use url::Url;

let url = Url::parse("ftp://rms@example.com").unwrap();
assert_eq!(url.username(), "rms");

let url = Url::parse("ftp://:secret123@example.com").unwrap();
assert_eq!(url.username(), "");

let url = Url::parse("https://example.com").unwrap();
assert_eq!(url.username(), "");

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

Examples

use url::Url;

let url = Url::parse("ftp://rms:secret123@example.com").unwrap();
assert_eq!(url.password(), Some("secret123"));

let url = Url::parse("ftp://:secret123@example.com").unwrap();
assert_eq!(url.password(), Some("secret123"));

let url = Url::parse("ftp://rms@example.com").unwrap();
assert_eq!(url.password(), None);

let url = Url::parse("https://example.com").unwrap();
assert_eq!(url.password(), None);

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

Examples

use url::Url;

let url = Url::parse("ftp://rms@example.com").unwrap();
assert!(url.has_host());

let url = Url::parse("unix:/run/foo.socket").unwrap();
assert!(!url.has_host());

let url = Url::parse("data:text/plain,Stuff").unwrap();
assert!(!url.has_host());

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.

Examples

use url::Url;

let url = Url::parse("https://127.0.0.1/index.html").unwrap();
assert_eq!(url.host_str(), Some("127.0.0.1"));

let url = Url::parse("ftp://rms@example.com").unwrap();
assert_eq!(url.host_str(), Some("example.com"));

let url = Url::parse("unix:/run/foo.socket").unwrap();
assert_eq!(url.host_str(), None);

let url = Url::parse("data:text/plain,Stuff").unwrap();
assert_eq!(url.host_str(), None);

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.

Examples

use url::Url;

let url = Url::parse("https://127.0.0.1/index.html").unwrap();
assert!(url.host().is_some());

let url = Url::parse("ftp://rms@example.com").unwrap();
assert!(url.host().is_some());

let url = Url::parse("unix:/run/foo.socket").unwrap();
assert!(url.host().is_none());

let url = Url::parse("data:text/plain,Stuff").unwrap();
assert!(url.host().is_none());

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

Examples

use url::Url;

let url = Url::parse("https://127.0.0.1/").unwrap();
assert_eq!(url.domain(), None);

let url = Url::parse("mailto:rms@example.net").unwrap();
assert_eq!(url.domain(), None);

let url = Url::parse("https://example.com/").unwrap();
assert_eq!(url.domain(), Some("example.com"));

Return the port number for this URL, if any.

Examples

use url::Url;

let url = Url::parse("https://example.com").unwrap();
assert_eq!(url.port(), None);

let url = Url::parse("ssh://example.com:22").unwrap();
assert_eq!(url.port(), Some(22));

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().

Examples

use url::Url;

let url = Url::parse("foo://example.com").unwrap();
assert_eq!(url.port_or_known_default(), None);

let url = Url::parse("foo://example.com:1456").unwrap();
assert_eq!(url.port_or_known_default(), Some(1456));

let url = Url::parse("https://example.com").unwrap();
assert_eq!(url.port_or_known_default(), Some(443));

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(()),
    }
}

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.

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

Examples

use url::Url;

let url = Url::parse("https://example.com/foo/bar").unwrap();
let mut path_segments = url.path_segments().unwrap();
assert_eq!(path_segments.next(), Some("foo"));
assert_eq!(path_segments.next(), Some("bar"));
assert_eq!(path_segments.next(), None);

let url = Url::parse("https://example.com").unwrap();
let mut path_segments = url.path_segments().unwrap();
assert_eq!(path_segments.next(), Some(""));
assert_eq!(path_segments.next(), None);

let url = Url::parse("data:text/plain,HelloWorld").unwrap();
assert!(url.path_segments().is_none());

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

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

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.

Change this URL’s fragment identifier.

Change this URL’s query string.

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", "\u{00C9}t\u{00E9}+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.

Change this URL’s path.

Return an object with methods to manipulate this URL’s path segments.

Return Err(()) if this URL is cannot-be-a-base.

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.

Examples

use url::Url;

let mut url = Url::parse("ssh://example.net:2048/").unwrap();

url.set_port(Some(4096)).unwrap();
assert_eq!(url.as_str(), "ssh://example.net:4096/");

url.set_port(None).unwrap();
assert_eq!(url.as_str(), "ssh://example.net/");

Cannot set port for cannot-be-a-base URLs:

use url::Url;

let mut url = Url::parse("mailto:rms@example.net").unwrap();

let result = url.set_port(Some(80));
assert!(result.is_err());

let result = url.set_port(None);
assert!(result.is_err());

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.

Examples

Change host:

use url::Url;

let mut url = Url::parse("https://example.net").unwrap();
let result = url.set_host(Some("rust-lang.org"));
assert!(result.is_ok());
assert_eq!(url.as_str(), "https://rust-lang.org/");

Remove host:

use url::Url;

let mut url = Url::parse("foo://example.net").unwrap();
let result = url.set_host(None);
assert!(result.is_ok());
assert_eq!(url.as_str(), "foo:/");

Cannot remove host for 'special' schemes (e.g. http):

use url::Url;

let mut url = Url::parse("https://example.net").unwrap();
let result = url.set_host(None);
assert!(result.is_err());
assert_eq!(url.as_str(), "https://example.net/");

Cannot change or remove host for cannot-be-a-base URLs:

use url::Url;

let mut url = Url::parse("mailto:rms@example.net").unwrap();

let result = url.set_host(Some("rust-lang.org"));
assert!(result.is_err());
assert_eq!(url.as_str(), "mailto:rms@example.net");

let result = url.set_host(None);
assert!(result.is_err());
assert_eq!(url.as_str(), "mailto:rms@example.net");

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.

Change this URL’s password.

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

Change this URL’s username.

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

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

Examples

Change the URL’s scheme from https to foo:

use url::Url;

let mut url = Url::parse("https://example.net").unwrap();
let result = url.set_scheme("foo");
assert_eq!(url.as_str(), "foo://example.net/");
assert!(result.is_ok());

Cannot change URL’s scheme from https to foõ:

use url::Url;

let mut url = Url::parse("https://example.net").unwrap();
let result = url.set_scheme("foõ");
assert_eq!(url.as_str(), "https://example.net/");
assert!(result.is_err());

Cannot change URL’s scheme from mailto (cannot-be-a-base) to https:

use url::Url;

let mut url = Url::parse("mailto:rms@example.net").unwrap();
let result = url.set_scheme("https");
assert_eq!(url.as_str(), "mailto:rms@example.net");
assert!(result.is_err());

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:).

Examples

On Unix-like platforms:

use url::Url;

let url = Url::from_file_path("/tmp/foo.txt").unwrap();
assert_eq!(url.as_str(), "file:///tmp/foo.txt");

let url = Url::from_file_path("../foo.txt");
assert!(url.is_err());

let url = Url::from_file_path("https://google.com/");
assert!(url.is_err());

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()).

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
[src]

The returned type after indexing

The method for the indexing (container[index]) operation

impl Index<RangeFrom<Position>> for Url
[src]

The returned type after indexing

The method for the indexing (container[index]) operation

impl Index<RangeTo<Position>> for Url
[src]

The returned type after indexing

The method for the indexing (container[index]) operation

impl Index<Range<Position>> for Url
[src]

The returned type after indexing

The method for the indexing (container[index]) operation

impl Clone for Url
[src]

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

impl ToSocketAddrs for Url
[src]

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

Returned iterator over socket addresses which this type may correspond to. Read more

Converts this object to an iterator of resolved SocketAddrs. Read more

impl FromStr for Url
[src]

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

The associated error which can be returned from parsing.

Parses a string s to return a value of this type. Read more

impl Display for Url
[src]

Display the serialization of this URL.

Formats the value using the given formatter.

impl Debug for Url
[src]

Debug the serialization of this URL.

Formats the value using the given formatter.

impl Eq for Url
[src]

URLs compare like their serialization.

impl PartialEq for Url
[src]

URLs compare like their serialization.

This method tests for self and other values to be equal, and is used by ==. Read more

This method tests for !=.

impl Ord for Url
[src]

URLs compare like their serialization.

This method returns an Ordering between self and other. Read more

impl PartialOrd for Url
[src]

URLs compare like their serialization.

This method returns an ordering between self and other values if one exists. Read more

This method tests less than (for self and other) and is used by the < operator. Read more

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more

This method tests greater than (for self and other) and is used by the > operator. Read more

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more

impl Hash for Url
[src]

URLs hash like their serialization.

Feeds this value into the state given, updating the hasher as necessary.

Feeds a slice of this type into the state provided.

impl AsRef<str> for Url
[src]

Return the serialization of this URL.

Performs the conversion.