|
| 1 | +/// Finds the first value of a query parameter in a URL. Is not guaranteed to be accurate |
| 2 | +/// with the URL standard and is just meant to be a simple helper that doesn't require |
| 3 | +/// fully parsing the URL. |
| 4 | +/// |
| 5 | +/// # Example |
| 6 | +/// |
| 7 | +/// ```rust |
| 8 | +/// find_url_query_value("https://example.com/?foo=bar&baz=qux", "baz") // => Some("qux") |
| 9 | +/// ``` |
| 10 | +pub fn find_url_query_value<'url>(url: &'url str, key: &str) -> Option<&'url str> { |
| 11 | + // Return None right away if this doesn't look like a URL at all. |
| 12 | + if !url.starts_with("http://") && !url.starts_with("https://") { |
| 13 | + return None; |
| 14 | + } |
| 15 | + // Skip everything up to the first `?` as we're not parsing the host/path/etc. |
| 16 | + let url = url.split('?').nth(1)?; |
| 17 | + // Now parse the query string in pairs of `key=value`, we don't need |
| 18 | + // to be too strict about this as we're not trying to be spec-compliant. |
| 19 | + for pair in url.split('&') { |
| 20 | + if let Some((k, v)) = pair.split_once('=') { |
| 21 | + if k == key { |
| 22 | + return Some(v); |
| 23 | + } |
| 24 | + } |
| 25 | + } |
| 26 | + None |
| 27 | +} |
| 28 | + |
| 29 | +mod test { |
| 30 | + #[test] |
| 31 | + fn test_find_url_query_value() { |
| 32 | + use super::find_url_query_value; |
| 33 | + assert_eq!(find_url_query_value("something", "q"), None); |
| 34 | + assert_eq!(find_url_query_value("https://example.com/?foo=bar", "foo"), Some("bar")); |
| 35 | + assert_eq!(find_url_query_value("https://example.com/?foo=bar", "baz"), None); |
| 36 | + assert_eq!( |
| 37 | + find_url_query_value("https://example.com/?foo=bar&baz=qux", "baz"), |
| 38 | + Some("qux") |
| 39 | + ); |
| 40 | + assert_eq!( |
| 41 | + find_url_query_value("https://example.com/?foo=bar&foo=qux", "foo"), |
| 42 | + Some("bar") |
| 43 | + ); |
| 44 | + assert_eq!( |
| 45 | + find_url_query_value("https://polyfill.io/v3/polyfill.min.js?features=WeakSet%2CPromise%2CPromise.prototype.finally%2Ces2015%2Ces5%2Ces6", "features"), |
| 46 | + Some("WeakSet%2CPromise%2CPromise.prototype.finally%2Ces2015%2Ces5%2Ces6") |
| 47 | + ); |
| 48 | + } |
| 49 | +} |
0 commit comments