### Custom UrlRelative Policy Example Source: https://docs.rs/ammonia/4.1.2/ammonia/enum.UrlRelative.html Demonstrates how to implement a custom policy for relative URLs. This example rewrites absolute paths by prepending '/root'. Use this when specific URL manipulation logic is required. ```rust use std::borrow::Cow; fn is_absolute_path(url: &str) -> bool { let u = url.as_bytes(); // `//a/b/c` is "protocol-relative", meaning "a" is a hostname // `/a/b/c` is an absolute path, and what we want to do stuff to. u.get(0) == Some(&b'/') && u.get(1) != Some(&b'/') } fn evaluate(url: &str) -> Option> { if is_absolute_path(url) { Some(Cow::Owned(String::from("/root") + url)) } else { Some(Cow::Borrowed(url)) } } fn main() { let a = ammonia::Builder::new() .url_relative(ammonia::UrlRelative::Custom(Box::new(evaluate))) .clean("fixedpassedskipped") .to_string(); assert_eq!(a, "fixedpassedskipped"); } ``` -------------------------------- ### Builder::new Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Builder.html Constructs a Builder instance with default options. This is the starting point for configuring sanitization rules. ```APIDOC ## Builder::new ### Description Constructs a `Builder` instance configured with the default options. ### Method ```rust pub fn new() -> Self ``` ### Examples ```rust use ammonia::{Builder, Url, UrlRelative}; let input = "This is an Ammonia example using the new() function."; let output = "This is an Ammonia example using the new() function."; let result = Builder::new() .url_relative(UrlRelative::RewriteWithBase(Url::parse("https://docs.rs/ammonia/1.0/ammonia/")?)) .clean(input) .to_string(); assert_eq!(result, output); ``` ``` -------------------------------- ### Builder::default() Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Builder.html Creates a new Builder with default settings. This is the starting point for configuring the HTML sanitizer. ```APIDOC ## Builder::default() ### Description Creates a new Builder with default settings. This is the starting point for configuring the HTML sanitizer. ### Method `Builder::default()` ### Example ```rust use ammonia::Builder; let sanitizer = Builder::default(); ``` ``` -------------------------------- ### Get URL Origin (File) Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Url.html Demonstrates the origin behavior for file URLs. File URLs have an opaque origin and comparing two identical file URLs may result in inequality. ```rust use url::{Host, Origin, Url}; let url = Url::parse("file:///tmp/foo")?; assert!(!url.origin().is_tuple()); let other_url = Url::parse("file:///tmp/foo")?; assert!(url.origin() != other_url.origin()); ``` -------------------------------- ### path() Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Url.html Returns 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. ```APIDOC ## path() ### Description Returns the path for this URL as a percent-encoded ASCII string. ### Returns - `&str`: The percent-encoded path of the URL. ``` -------------------------------- ### Get Hostname String Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Url.html Retrieves the hostname as a string slice. Handles domain names, IP addresses, and cases where no host is present. ```rust use url::Url; let url = Url::parse("https://127.0.0.1/index.html")?; assert_eq!(url.host_str(), Some("127.0.0.1")); let url = Url::parse("https://subdomain.example.com")?; assert_eq!(url.host_str(), Some("subdomain.example.com")); let url = Url::parse("ftp://rms@example.com")?; assert_eq!(url.host_str(), Some("example.com")); let url = Url::parse("unix:/run/foo.socket")?; assert_eq!(url.host_str(), None); let url = Url::parse("data:text/plain,Stuff")?; assert_eq!(url.host_str(), None); ``` -------------------------------- ### Get URL Username Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Url.html Retrieves the username from a URL as a percent-encoded ASCII string. Returns an empty string if no username is present. ```rust use url::Url; let url = Url::parse("ftp://rms@example.com")?; assert_eq!(url.username(), "rms"); let url = Url::parse("ftp://:secret123@example.com")?; assert_eq!(url.username(), ""); let url = Url::parse("https://example.com")?; assert_eq!(url.username(), ""); ``` -------------------------------- ### Get URL Path Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Url.html Retrieves the path component of a URL as a percent-encoded ASCII string. For non-base URLs, it's an arbitrary string; for others, it starts with '/' and includes path segments. ```rust use url::{Url, ParseError}; let url = Url::parse("https://example.com/api/versions?page=2")?; assert_eq!(url.path(), "/api/versions"); let url = Url::parse("https://example.com")?; assert_eq!(url.path(), "/"); let url = Url::parse("https://example.com/countries/việt nam")?; assert_eq!(url.path(), "/countries/vi%E1%BB%87t%20nam"); ``` -------------------------------- ### Get URL Scheme Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Url.html Retrieves the scheme of a URL as a lower-cased ASCII string. The scheme delimiter ':' is excluded. ```rust use url::Url; let url = Url::parse("file:///tmp/foo")?; assert_eq!(url.scheme(), "file"); ``` -------------------------------- ### Get URL Origin (Other Scheme) Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Url.html Retrieves the origin of a URL with a non-special scheme. Such origins are typically opaque. ```rust use url::{Host, Origin, Url}; let url = Url::parse("foo:bar")?; assert!(!url.origin().is_tuple()); ``` -------------------------------- ### Get URL Password Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Url.html Retrieves the password from a URL, if present, as a percent-encoded ASCII string. Returns None if no password is set. ```rust use url::Url; let url = Url::parse("https://user:password@example.com")?; assert_eq!(url.password(), Some("password")); let url = Url::parse("https://example.com")?; assert_eq!(url.password(), None); ``` -------------------------------- ### impl AsRef for Url Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Url.html Provides a way to get a string slice reference to the URL's serialization. ```APIDOC ## impl AsRef for Url ### Description Return the serialization of this URL. ### Method `fn as_ref(&self) -> &str` ### Returns - **&str**: A string slice representing the URL. ``` -------------------------------- ### Get URL Query String Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Url.html Retrieves the query string of a URL, if present, as a percent-encoded ASCII string. Returns None if no query string exists. ```rust use url::Url; fn run() -> Result<(), ParseError> { let url = Url::parse("https://example.com/products?page=2")?; let query = url.query(); assert_eq!(query, Some("page=2")); let url = Url::parse("https://example.com/products")?; let query = url.query(); assert!(query.is_none()); let url = Url::parse("https://example.com/?country=español")?; let query = url.query(); assert_eq!(query, Some("country=espa%C3%B1ol")); } ``` -------------------------------- ### Get URL Origin (FTP) Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Url.html Retrieves the origin of a URL with an FTP scheme. The origin includes the scheme, host, and port. ```rust use url::{Host, Origin, Url}; let url = Url::parse("ftp://example.com/foo")?; assert_eq!(url.origin(), Origin::Tuple("ftp".into(), Host::Domain("example.com".into()), 21)); ``` -------------------------------- ### Configure URL Schemes with Builder Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Builder.html Demonstrates how to set custom URL schemes for the Builder. This is useful for allowing specific protocols like 'magnet' or custom schemes in links. ```rust use ammonia::Builder; use maplit::hashset; let url_schemes = hashset![ "http", "https", "mailto", "magnet" ]; let a = Builder::new().url_schemes(url_schemes) .clean("zero-length file") .to_string(); // See `link_rel` for information on the rel="noopener noreferrer" attribute // in the cleaned HTML. assert_eq!(a, "zero-length file"); ``` -------------------------------- ### Builder: New Instance with URL Rewriting Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Builder.html Illustrates creating a new Builder instance and configuring URL rewriting for relative links. ```rust use ammonia::{Builder, Url, UrlRelative}; let input = "This is an Ammonia example using the new() function."; let output = "This is an Ammonia example using the new() function."; let result = Builder::new() // <-- .url_relative(UrlRelative::RewriteWithBase(Url::parse("https://docs.rs/ammonia/1.0/ammonia/")?)) .clean(input) .to_string(); assert_eq!(result, output); ``` -------------------------------- ### Get Link Rel Setting Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Builder.html Retrieves the configured `rel` attribute setting for links. ```rust use ammonia::{Builder, UrlRelative}; let mut a = Builder::default(); a.link_rel(Some("a b")); assert_eq!(a.get_link_rel(), Some("a b")); ``` -------------------------------- ### Builder: Generic Attributes and ID Prefix Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Builder.html Demonstrates how to configure the Builder to allow specific generic attributes and apply an ID prefix. ```rust use ammonia::Builder; use maplit::hashset; let attributes = hashset!["id"]; let a = Builder::new() .generic_attributes(attributes) .id_prefix(Some("safe-")) .clean("") .to_string(); assert_eq!(a, ""); ``` -------------------------------- ### Builder Configuration: Tag in both whitelist and blacklist and panicking Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Builder.html Shows a configuration that will panic: a tag ('aside') is included in the general tag whitelist ('tags') and also in the content blacklist ('clean_content_tags'). This is contradictory as tags cannot be both allowed and disallowed for content. ```rust use ammonia::Builder; use maplit::hashset; Builder::default() .clean_content_tags(hashset!["aside"]) .clean(""); ``` -------------------------------- ### Clean HTML Input with Builder Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Document.html Demonstrates basic usage of the Builder to clean an HTML input string and convert the resulting Document to a String. ```rust use ammonia::Builder; let input = "This is an Ammonia example."; let output = "This is an Ammonia example."; let document = Builder::new() .clean(input); assert_eq!(document.to_string(), output); ``` -------------------------------- ### Set URL Path Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Url.html Shows how to change the path of a URL. The method handles percent-encoding automatically if the provided string is not already encoded. ```rust use url::Url; let mut url = Url::parse("https://example.com")?; url.set_path("api/comments"); assert_eq!(url.as_str(), "https://example.com/api/comments"); assert_eq!(url.path(), "/api/comments"); let mut url = Url::parse("https://example.com/api")?; url.set_path("data/report.csv"); assert_eq!(url.as_str(), "https://example.com/data/report.csv"); assert_eq!(url.path(), "/data/report.csv"); // `set_path` percent-encodes the given string if it's not already percent-encoded. let mut url = Url::parse("https://example.com")?; url.set_path("api/some comments"); assert_eq!(url.as_str(), "https://example.com/api/some%20comments"); assert_eq!(url.path(), "/api/some%20comments"); // `set_path` will not double percent-encode the string if it's already percent-encoded. let mut url = Url::parse("https://example.com")?; url.set_path("api/some%20comments"); assert_eq!(url.as_str(), "https://example.com/api/some%20comments"); assert_eq!(url.path(), "/api/some%20comments"); ``` -------------------------------- ### Builder: Empty Instance with URL Rewriting Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Builder.html Demonstrates creating an empty Builder instance (no allowed tags) and configuring URL rewriting. ```rust use ammonia::{Builder, Url, UrlRelative}; let input = "This is an Ammonia example using the empty() function."; let output = "This is an Ammonia example using the empty() function."; let result = Builder::empty() // <-- .url_relative(UrlRelative::RewriteWithBase(Url::parse("https://docs.rs/ammonia/1.0/ammonia/")?)) .clean(input) .to_string(); assert_eq!(result, output); ``` -------------------------------- ### Get URL Fragment Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Url.html Retrieves the fragment identifier of a URL, which is the part after the '#' symbol. This component is optional and not percent-encoded by the parser. ```rust use url::Url; let url = Url::parse("https://example.com/data.csv#row=4")?; assert_eq!(url.fragment(), Some("row=4")); let url = Url::parse("https://example.com/data.csv#cell=4,1-6,2")?; assert_eq!(url.fragment(), Some("cell=4,1-6,2")); ``` -------------------------------- ### TryFrom<&str> Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Url.html Attempts to create a Url from a string slice. Returns a `ParseError` on failure. ```APIDOC ## fn try_from(s: &'a str) -> Result>::Error> ### Description Performs the conversion from a string slice to a Url. ### Method TryFrom<&'a str>::try_from ### Parameters - **s** (&'a str) - The string slice to convert. ``` -------------------------------- ### Get URL Port Number Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Url.html Retrieves the port number specified in the URL. Does not return default ports for schemes. ```rust use url::Url; let url = Url::parse("https://example.com")?; assert_eq!(url.port(), None); let url = Url::parse("https://example.com:443/")?; assert_eq!(url.port(), None); let url = Url::parse("ssh://example.com:22")?; assert_eq!(url.port(), Some(22)); ``` -------------------------------- ### Builder Configuration: Valid tag whitelist/blacklist handling Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Builder.html Presents a valid configuration where tags are managed correctly. The 'aside' tag is explicitly removed from the general whitelist using rm_tags, and then added to clean_content_tags, avoiding the panic condition. ```rust use ammonia::Builder; use maplit::hashset; Builder::default() .rm_tags(&["aside"]) .clean_content_tags(hashset!["aside"]) .clean(""); ``` -------------------------------- ### Configure Relative URL Handling Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Builder.html Shows how to configure the Builder to handle relative URLs using `url_relative`. `UrlRelative::PassThrough` allows relative URLs to be preserved in the cleaned HTML. ```rust use ammonia::{Builder, UrlRelative}; let a = Builder::new().url_relative(UrlRelative::PassThrough) .clean("Home") .to_string(); // See `link_rel` for information on the rel="noopener noreferrer" attribute // in the cleaned HTML. assert_eq!( a, "Home"); ``` -------------------------------- ### Parse and Modify URL Query Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Url.html Demonstrates parsing a URL and modifying its query string by setting parameters and appending new ones. Also shows how to clear and rebuild the query. ```rust use url::Url; let mut url = Url::parse("https://example.com/products")?; assert_eq!(url.as_str(), "https://example.com/products"); url.set_query(Some("page=2")); assert_eq!(url.as_str(), "https://example.com/products?page=2"); assert_eq!(url.query(), Some("page=2")); ``` ```rust let mut url = Url::parse("https://example.net?lang=fr#nav")?; 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"); ``` -------------------------------- ### Get URL Origin (Blob) Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Url.html Retrieves the origin of a URL with a Blob scheme. For blob URLs, the origin is derived from the embedded URL. ```rust use url::{Host, Origin, Url}; let url = Url::parse("blob:https://example.com/foo")?; assert_eq!(url.origin(), Origin::Tuple("https".into(), Host::Domain("example.com".into()), 443)); ``` -------------------------------- ### Clone URL Schemes Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Builder.html Demonstrates how to retrieve a copy of the currently whitelisted URL schemes using `clone_url_schemes`. This can be useful for inspection or for reusing the schemes in another builder. ```rust use maplit::hashset; let url_schemes = hashset!["my-scheme-1", "my-scheme-2"]; let mut b = ammonia::Builder::default(); b.url_schemes(Clone::clone(&url_schemes)); assert_eq!(url_schemes, b.clone_url_schemes()); ``` -------------------------------- ### Url as String Reference Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Url.html Returns the serialization of this URL as a string reference. This is part of the `AsRef` trait implementation. ```rust fn as_ref(&self) -> &str; ``` -------------------------------- ### Get URL as String - Rust Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Url.html Returns the serialized string representation of a parsed URL. This is an efficient operation as the string is stored internally. ```rust use url::Url; let url_str = "https://example.net/"; let url = Url::parse(url_str)?; assert_eq!(url.as_str(), url_str); ``` -------------------------------- ### Check if URL is Special Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Url.html Determines if a URL has a 'special' scheme, which affects URL parsing and resolution rules. Examples include http and file schemes. ```rust use url::Url; assert!(Url::parse("http:///tmp/foo")?.is_special()); assert!(Url::parse("file:///tmp/foo")?.is_special()); assert!(!Url::parse("moz:///tmp/foo")?.is_special()); ``` -------------------------------- ### Basic HTML Sanitization with Builder Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Builder.html Demonstrates the default usage of the Builder to sanitize an HTML fragment. It handles parsing and cleaning disallowed tags and attributes according to the HTML5 algorithm. ```rust use ammonia::{Builder, UrlRelative}; let a = Builder::default() .link_rel(None) .url_relative(UrlRelative::PassThrough) .clean("test") .to_string(); assert_eq!( a, "test"); ``` -------------------------------- ### Get Parsed Host Representation Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Url.html Obtains the parsed host of a URL, which can be an IP address or a domain name. Returns None for URLs without a host. ```rust use url::Url; let url = Url::parse("https://127.0.0.1/index.html")?; assert!(url.host().is_some()); let url = Url::parse("ftp://rms@example.com")?; assert!(url.host().is_some()); let url = Url::parse("unix:/run/foo.socket")?; assert!(url.host().is_none()); let url = Url::parse("data:text/plain,Stuff")?; assert!(url.host().is_none()); ``` -------------------------------- ### Builder::new().url_schemes() Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Builder.html Initializes a new Builder and sets the allowed URL schemes for cleaning HTML content. This method overwrites any previously set URL schemes. ```APIDOC ## Builder::new().url_schemes() ### Description Sets the allowed URL schemes for cleaning HTML content. This method overwrites any previously set URL schemes. ### Method Builder::new().url_schemes() ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use ammonia::Builder; use maplit::hashset; let url_schemes = hashset![ "http", "https", "mailto", "magnet" ]; let a = Builder::new().url_schemes(url_schemes) .clean("zero-length file") .to_string(); assert_eq!(a, "zero-length file"); ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Url::options Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Url.html Returns a default `ParseOptions` struct that can be used to configure the URL parser. ```APIDOC ## Url::options ### Description Return a default `ParseOptions` that can fully configure the URL parser. ### Method `pub fn options<'a>() -> ParseOptions<'a>` ### Examples ```rust use url::Url; let options = Url::options(); let api = Url::parse("https://api.example.com")?; let base_url = options.base_url(Some(&api)); let version_url = base_url.parse("version.json")?; assert_eq!(version_url.as_str(), "https://api.example.com/version.json"); ``` ``` -------------------------------- ### Custom Attribute Filtering Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Builder.html Demonstrates using `attribute_filter` to modify or remove attributes. This example removes the 'src' attribute from 'img' tags, preventing images from being displayed. ```rust use ammonia::Builder; let a = Builder::new() .attribute_filter(|element, attribute, value| { match (element, attribute) { ("img", "src") => None, _ => Some(value.into()) } }) .link_rel(None) .clean("Home") .to_string(); assert_eq!(a, r###"Home"###); ``` -------------------------------- ### Adding Tags to Builder Whitelist Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Builder.html Shows how to add new tags to the existing whitelist of allowed tags using the `add_tags` method. This method does not remove tags that were previously whitelisted. ```rust let a = ammonia::Builder::default() .add_tags(&["my-tag"]) .clean("test mess").to_string(); assert_eq!("test mess", a); ``` -------------------------------- ### Get URL Authority Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Url.html Retrieves the authority component of a URL as an ASCII string. Handles encoding for non-ASCII domains and IPv6 addresses, and omits well-known ports. ```rust use url::Url; let url = Url::parse("unix:/run/foo.socket")?; assert_eq!(url.authority(), ""); let url = Url::parse("file:///tmp/foo")?; assert_eq!(url.authority(), ""); let url = Url::parse("https://user:password@example.com/tmp/foo")?; assert_eq!(url.authority(), "user:password@example.com"); let url = Url::parse("irc://àlex.рф.example.com:6667/foo")?; assert_eq!(url.authority(), "%C3%A0lex.%D1%80%D1%84.example.com:6667"); let url = Url::parse("http://àlex.рф.example.com:80/foo")?; assert_eq!(url.authority(), "xn--lex-8ka.xn--p1ai.example.com"); ``` -------------------------------- ### Setting Allowed Tags with Builder Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Builder.html Demonstrates how to explicitly set the set of allowed HTML tags using the `tags` method on the Builder. This overrides any default tag whitelist. ```rust use ammonia::Builder; use maplit::hashset; let tags = hashset!["my-tag"]; let a = Builder::new() .tags(tags) .clean("") .to_string(); assert_eq!(a, ""); ``` -------------------------------- ### Builder: Clean HTML from String Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Builder.html Shows the basic usage of the `clean` method to sanitize an HTML string according to the Builder's configuration. ```rust use ammonia::{Builder, Url, UrlRelative}; let input = "This is an Ammonia example using the new() function."; let output = "This is an Ammonia example using the new() function."; let result = Builder::new() .url_relative(UrlRelative::RewriteWithBase(Url::parse("https://docs.rs/ammonia/1.0/ammonia/")?)) .clean(input) .to_string(); // <-- assert_eq!(result, output); ``` -------------------------------- ### Get URL Path Segments Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Url.html Iterates over the path segments of a URL, each as a percent-encoded ASCII string. Returns None for cannot-be-base URLs. The iterator always yields at least one string, possibly empty. ```rust use url::Url; let url = Url::parse("https://example.com/foo/bar")?; let mut path_segments = url.path_segments().ok_or_else(|| "cannot be base")?; 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")?; let mut path_segments = url.path_segments().ok_or_else(|| "cannot be base")?; assert_eq!(path_segments.next(), Some("")); assert_eq!(path_segments.next(), None); let url = Url::parse("data:text/plain,HelloWorld")?; assert!(url.path_segments().is_none()); let url = Url::parse("https://example.com/countries/việt nam")?; let mut path_segments = url.path_segments().ok_or_else(|| "cannot be base")?; assert_eq!(path_segments.next(), Some("countries")); assert_eq!(path_segments.next(), Some("vi%E1%BB%87t%20nam")); ``` -------------------------------- ### Indexing with RangeFull Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Url.html Performs the indexing operation using `RangeFull`. ```APIDOC ## fn index(&self, _: RangeFull) -> &str ### Description Performs the indexing (`container[index]`) operation. ### Method Index ### Parameters - **_** (RangeFull) - Represents a full range for indexing. ``` -------------------------------- ### Clean HTML with Ammonia Source: https://docs.rs/ammonia/4.1.2/ammonia/index.html Use the `clean` function to sanitize HTML content. It removes potentially harmful tags and attributes, ensuring the output is safe for display. The example demonstrates cleaning a string with an embedded script. ```rust let result = ammonia::clean( "I'm not trying to XSS you" ); assert_eq!(result, "I'm not trying to XSS you"); ``` -------------------------------- ### Get Port or Default Port Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Url.html Retrieves the port number from the URL, or the known default port for schemes like http, https, ws, wss, and ftp. Returns None for unknown schemes without a specified port. ```rust use url::Url; let url = Url::parse("foo://example.com")?; assert_eq!(url.port_or_known_default(), None); let url = Url::parse("foo://example.com:1456")?; assert_eq!(url.port_or_known_default(), Some(1456)); let url = Url::parse("https://example.com")?; assert_eq!(url.port_or_known_default(), Some(443)); ``` -------------------------------- ### Serialization Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Url.html Serializes the Url into a `serde` stream. This implementation is available if the `serde` Cargo feature is enabled. ```APIDOC ## fn serialize( &self, serializer: S, ) -> Result<::Ok, ::Error> ### Description Serializes this Url value into the given Serde serializer. ### Method Serialize::serialize ### Parameters - **serializer** (S) - The Serde serializer. ``` -------------------------------- ### Set URL Host Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Url.html Illustrates changing or removing the host of a URL. Removing the host also removes any associated username, password, and port. Errors occur for special schemes like 'http' when trying to remove the host, or for cannot-be-a-base URLs. ```rust use url::Url; let mut url = Url::parse("https://example.net")?; let result = url.set_host(Some("rust-lang.org")); assert!(result.is_ok()); assert_eq!(url.as_str(), "https://rust-lang.org/"); ``` ```rust use url::Url; let mut url = Url::parse("foo://example.net")?; let result = url.set_host(None); assert!(result.is_ok()); assert_eq!(url.as_str(), "foo:/"); ``` ```rust use url::Url; let mut url = Url::parse("https://example.net")?; let result = url.set_host(None); assert!(result.is_err()); assert_eq!(url.as_str(), "https://example.net/"); ``` ```rust use url::Url; let mut url = Url::parse("mailto:rms@example.net")?; 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"); ``` -------------------------------- ### Builder Configuration: Allowing 'class' attribute and panicking Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Builder.html Demonstrates a configuration that will panic: allowing the 'class' attribute via generic_attributes and also defining allowed classes for specific tags. This is disallowed to prevent arbitrary class assignments. ```rust use ammonia::Builder; use maplit::{hashmap, hashset}; Builder::default() .generic_attributes(hashset!["class"]) .allowed_classes(hashmap!["span" => hashset!["hidden"]]) .clean(""); ``` -------------------------------- ### Convert Document to String using Display Trait Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Document.html Illustrates converting a sanitized HTML Document to a String using the `Display` trait implementation, which is the simplest method for string conversion. ```rust use ammonia::Builder; let input = "Some HTML here"; let output = "Some HTML here"; let document = Builder::new() .clean(input); assert_eq!(document.to_string(), output); ``` -------------------------------- ### Indexing with RangeFrom Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Url.html Performs the indexing operation using a `RangeFrom`. ```APIDOC ## fn index(&self, range: RangeFrom) -> &str ### Description Performs the indexing (`container[index]`) operation. ### Method Index ### Parameters - **range** (RangeFrom) - Description of the range for indexing. ``` -------------------------------- ### impl Clone for Url Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Url.html Allows cloning Url instances. ```APIDOC ## impl Clone for Url ### Description Provides methods for cloning Url instances. ### Methods #### `fn clone(&self) -> Url` Returns a duplicate of the value. #### `fn clone_from(&mut self, source: &Self)` Performs copy-assignment from `source`. ``` -------------------------------- ### Create Url from File Path Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Url.html Creates a Url from a file path. This method is only available if the `std` Cargo feature is enabled. It returns an error if the path is not absolute or if it's a URL without a file scheme. ```rust use url::Url; let url = Url::from_file_path("/tmp/foo.txt")?; 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()); ``` -------------------------------- ### Write Sanitized HTML to a Writer Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Document.html Shows how to use the `write_to` method to serialize a sanitized HTML Document directly to a writer, avoiding intermediate String buffering. ```rust use ammonia::Builder; let input = "Some HTML here"; let expected = b"Some HTML here"; let document = Builder::new() .clean(input); let mut sanitized = Vec::new(); document.write_to(&mut sanitized) .expect("Writing to a string should not fail (except on OOM)"); assert_eq!(sanitized, expected); ``` -------------------------------- ### query() Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Url.html Returns this URL’s query string, if any, as a percent-encoded ASCII string. ```APIDOC ## query() ### Description Retrieves the query string of the URL. ### Returns - `Option<&str>`: The percent-encoded query string, or `None` if no query string is present. ``` -------------------------------- ### Builder::new() Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Builder.html Creates a new Builder instance. This is an alternative to `Builder::default()` for creating a sanitizer. ```APIDOC ## Builder::new() ### Description Creates a new Builder instance. This is an alternative to `Builder::default()` for creating a sanitizer. ### Method `Builder::new()` ### Example ```rust use ammonia::Builder; let sanitizer = Builder::new(); ``` ``` -------------------------------- ### Compare Urls Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Url.html Compares two Urls for ordering. URLs compare like their serialization. ```APIDOC ## fn cmp(&self, other: &Url) -> Ordering ### Description Compares `self` and `other` Urls and returns an `Ordering`. ### Method Ord::cmp ### Parameters - **other** (&Url) - The other Url to compare against. ``` ```APIDOC ## fn partial_cmp(&self, other: &Url) -> Option ### Description Compares `self` and `other` Urls and returns an `Option` if one exists. ### Method PartialOrd::partial_cmp ### Parameters - **other** (&Url) - The other Url to compare against. ``` -------------------------------- ### Set IP Host for URL Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Url.html Changes the URL's host to a given IP address. Use this when you need to set an IP address directly as the host, bypassing the standard host parser. Returns an error if the URL cannot-be-a-base. ```rust use url::{Url, ParseError}; let mut url = Url::parse("http://example.com")?; url.set_ip_host("127.0.0.1".parse().unwrap()); assert_eq!(url.host_str(), Some("127.0.0.1")); assert_eq!(url.as_str(), "http://127.0.0.1/"); ``` ```rust use url::{Url, ParseError}; let mut url = Url::parse("mailto:rms@example.com")?; let result = url.set_ip_host("127.0.0.1".parse().unwrap()); assert_eq!(url.as_str(), "mailto:rms@example.com"); assert!(result.is_err()); ``` -------------------------------- ### Cloning the Set of Whitelisted Tags Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Builder.html Illustrates how to retrieve a copy of the current set of whitelisted tags from the Builder using the `clone_tags` method. ```rust use maplit::hashset; let tags = hashset!["my-tag-1", "my-tag-2"]; let mut b = ammonia::Builder::default(); b.tags(Clone::clone(&tags)); assert_eq!(tags, b.clone_tags()); ``` -------------------------------- ### impl Display for Url Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Url.html Provides a displayable string representation of the URL. ```APIDOC ## impl Display for Url ### Description Display the serialization of this URL. ### Method `fn fmt(&self, formatter: &mut Formatter<'_>) -> Result<(), Error>` ### Parameters #### Path Parameters - **formatter** (&mut Formatter<'_>): The formatter to use for displaying the URL. ### Returns - **Result<(), Error>**: Ok if formatting is successful, Err otherwise. ``` -------------------------------- ### Configure URL Parsing Options - Rust Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Url.html Retrieves default parsing options and configures a base URL for subsequent parsing operations. This allows relative URLs to be resolved against a specified base. ```rust use url::Url; let options = Url::options(); let api = Url::parse("https://api.example.com")?; let base_url = options.base_url(Some(&api)); let version_url = base_url.parse("version.json")?; assert_eq!(version_url.as_str(), "https://api.example.com/version.json"); ``` -------------------------------- ### Builder::clone_url_schemes() Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Builder.html Returns a copy of the current set of whitelisted URL schemes. ```APIDOC ## Builder::clone_url_schemes() ### Description Returns a copy of the set of whitelisted URL schemes. ### Method Builder::clone_url_schemes() ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use maplit::hashset; let url_schemes = hashset!["my-scheme-1", "my-scheme-2"]; let mut b = ammonia::Builder::default(); b.url_schemes(Clone::clone(&url_schemes)); assert_eq!(url_schemes, b.clone_url_schemes()); ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Parse URL and Extract Password Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Url.html Demonstrates parsing URLs and extracting the password component. Handles cases with and without passwords. ```rust use url::Url; let url = Url::parse("ftp://rms:secret123@example.com")?; assert_eq!(url.password(), Some("secret123")); let url = Url::parse("ftp://:secret123@example.com")?; assert_eq!(url.password(), Some("secret123")); let url = Url::parse("ftp://rms@example.com")?; assert_eq!(url.password(), None); let url = Url::parse("https://example.com")?; assert_eq!(url.password(), None); ``` -------------------------------- ### Serialize Url to String Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Url.html Converts a Url instance into its String representation. This method consumes the Url instance. ```rust use url::Url; let url_str = "https://example.net/"; let url = Url::parse(url_str)?; assert_eq!(String::from(url), url_str); ``` -------------------------------- ### Url::join Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Url.html Parses a string as a URL, using the current URL as the base. Handles various input types including scheme-relative and absolute URLs. ```APIDOC ## Url::join ### Description Parse a string as an URL, with this URL as the base URL. ### Method `pub fn join(&self, input: &str) -> Result` ### Parameters #### Path Parameters - **input** (str) - The string to parse as a URL relative to the base URL. ### 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). ### Errors If the function can not parse an URL from the given string with this URL as the base URL, a `ParseError` variant will be returned. ### Examples ```rust use url::Url; // Base without a trailing slash let base = Url::parse("https://example.net/a/b.html")?; let url = base.join("c.png")?; assert_eq!(url.as_str(), "https://example.net/a/c.png"); // Not /a/b.html/c.png // Base with a trailing slash let base = Url::parse("https://example.net/a/b/")?; let url = base.join("c.png")?; assert_eq!(url.as_str(), "https://example.net/a/b/c.png"); // Input as scheme relative special URL let base = Url::parse("https://alice.com/a")?; let url = base.join("//eve.com/b")?; assert_eq!(url.as_str(), "https://eve.com/b"); // Input as base url relative special URL let base = Url::parse("https://alice.com/a")?; let url = base.join("/v1/meta")?; assert_eq!(url.as_str(), "https://alice.com/v1/meta"); // Input as absolute URL let base = Url::parse("https://alice.com/a")?; let url = base.join("http://eve.com/b")?; assert_eq!(url.as_str(), "http://eve.com/b"); // http instead of https ``` ``` -------------------------------- ### Builder: Filter Style Properties Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Builder.html Shows how to filter specific properties within style attributes, ensuring only allowed CSS properties are kept. ```rust use ammonia::Builder; use maplit::hashset; let attributes = hashset!["style"]; let properties = hashset!["color"]; let a = Builder::new() .generic_attributes(attributes) .filter_style_properties(properties) .clean("

my html

") .to_string(); assert_eq!(a, "

my html

"); ``` -------------------------------- ### Builder Configuration: Allowing 'rel' attribute and panicking Source: https://docs.rs/ammonia/4.1.2/ammonia/struct.Builder.html Illustrates a configuration that will cause a panic: allowing the 'rel' attribute via generic_attributes while also setting a default link_rel. This is contradictory because the builder cannot simultaneously enforce a specific 'rel' value and allow it to be user-defined. ```rust use ammonia::Builder; use maplit::hashset; Builder::default() .generic_attributes(hashset!["rel"]) .clean(""); ```