use url::Url;
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
#[derive(Debug, Clone)]
pub struct Config {
pub url: Url,
pub api_key: String,
pub api_version: String,
pub debug: bool,
pub client_stub: String,
}
impl Config {
pub fn new(api_key: impl Into<String>) -> Self {
let default_url = Url::parse("https://api.sendwithus.com").unwrap();
Self {
url: default_url,
api_key: api_key.into(),
api_version: "1".to_string(),
debug: false,
client_stub: format!("rust-{}", VERSION),
}
}
pub fn with_url(mut self, url: impl Into<String>) -> Self {
self.url =
Url::parse(&url.into()).unwrap_or_else(|_| Url::parse("https://api.sendwithus.com").unwrap());
self
}
pub fn with_api_version(mut self, version: impl Into<String>) -> Self {
self.api_version = version.into();
self
}
pub fn with_debug(mut self, debug: bool) -> Self {
self.debug = debug;
self
}
pub fn protocol(&self) -> &str {
self.url.scheme()
}
pub fn host(&self) -> &str {
self.url.host_str().unwrap_or("api.sendwithus.com")
}
pub fn port(&self) -> u16 {
self
.url
.port()
.unwrap_or_else(|| if self.protocol() == "https" { 443 } else { 80 })
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_default_config() {
let config = Config::new("test-api-key");
assert_eq!(config.protocol(), "https");
assert_eq!(config.host(), "api.sendwithus.com");
assert_eq!(config.port(), 443);
assert_eq!(config.api_key, "test-api-key");
assert_eq!(config.api_version, "1");
assert!(!config.debug);
assert_eq!(config.client_stub, format!("rust-{}", VERSION));
}
#[test]
fn test_custom_url_config() {
let config = Config::new("test-api-key").with_url("http://example.com");
assert_eq!(config.protocol(), "http");
assert_eq!(config.host(), "example.com");
assert_eq!(config.port(), 80);
}
#[test]
fn test_invalid_url_fallback() {
let config = Config::new("test-api-key").with_url("invalid-url");
assert_eq!(config.protocol(), "https");
assert_eq!(config.host(), "api.sendwithus.com");
assert_eq!(config.port(), 443);
}
#[test]
fn test_with_api_version() {
let config = Config::new("test-api-key").with_api_version("2");
assert_eq!(config.api_version, "2");
}
#[test]
fn test_with_debug_mode() {
let config = Config::new("test-api-key").with_debug(true);
assert!(config.debug);
}
#[test]
fn test_custom_port() {
let config = Config::new("test-api-key").with_url("https://example.com:8443");
assert_eq!(config.protocol(), "https");
assert_eq!(config.host(), "example.com");
assert_eq!(config.port(), 8443);
}
}