dsntk_common/
uri.rs

1//! # URI
2
3use self::errors::*;
4use crate::Result;
5use uriparse::{URIReference, URI};
6
7pub type Uri = String;
8
9pub fn to_uri(value: &str) -> Result<Uri> {
10  if let Ok(uri_reference) = URIReference::try_from(value) {
11    if let Ok(uri) = URI::try_from(uri_reference) {
12      if uri.has_query() || uri.has_fragment() {
13        return Err(err_invalid_uri(value));
14      }
15      return Ok(uri.to_string().trim().trim_end_matches('/').to_string());
16    }
17  }
18  Err(err_invalid_uri(value))
19}
20
21/// Returns a string with URL encoded path segments.
22pub fn encode_segments(input: &str) -> String {
23  input.split('/').map(|s| urlencoding::encode(s).to_string()).collect::<Vec<String>>().join("/")
24}
25
26mod errors {
27  use crate::{DsntkError, ToErrorMessage};
28
29  /// Errors reported by [Uri](super::Uri).
30  #[derive(ToErrorMessage)]
31  struct UriError(String);
32
33  /// Creates an error indicating an invalid URI.
34  pub fn err_invalid_uri(s: &str) -> DsntkError {
35    UriError(format!("invalid URI: '{s}'")).into()
36  }
37}