Domani connects your domain to whatever you want to host on it, all with no account needed
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
domani/src/domain/settings.rs

77 lines
2.0 KiB

use crate::error::unexpected::{self, Mappable};
use crate::origin;
use std::borrow;
use hex::ToHex;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
/// Defines how a domain will behave when it is accessed. These are configured by the owner of the
/// domain during setup.
pub struct Settings {
#[serde(flatten)]
pub origin_descr: origin::Descr,
pub add_path_prefix: Option<String>,
}
impl Settings {
pub fn hash(&self) -> Result<String, unexpected::Error> {
let mut h = Sha256::new();
serde_json::to_writer(&mut h, self).or_unexpected()?;
Ok(h.finalize().encode_hex::<String>())
}
fn add_path_prefix<'path>(
path: borrow::Cow<'path, str>,
prefix: &str,
) -> borrow::Cow<'path, str> {
if prefix.is_empty() {
return path;
}
let mut prefix = prefix.trim_end_matches('/');
prefix = prefix.trim_start_matches('/');
let mut prefixed_path = String::with_capacity(1 + prefix.len() + path.len());
prefixed_path.push('/');
prefixed_path.push_str(prefix);
prefixed_path.push_str(path.as_ref());
borrow::Cow::Owned(prefixed_path)
}
pub fn process_path<'a>(&self, path: &'a str) -> borrow::Cow<'a, str> {
let mut path = borrow::Cow::Borrowed(path);
if let Some(ref prefix) = self.add_path_prefix {
path = Self::add_path_prefix(path, prefix);
}
path
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::borrow;
#[test]
fn add_path_prefix() {
let assert_add = |want: &str, path: &str, prefix: &str| {
assert_eq!(
want,
Settings::add_path_prefix(borrow::Cow::Borrowed(path), prefix).as_ref(),
)
};
assert_add("/foo/bar", "/bar", "/foo");
assert_add("/foo/", "/", "/foo");
assert_add("/foo/", "/", "/foo///");
assert_add("/bar", "/bar", "");
}
}