pub struct ResponseOnlyFormatter;
impl ResponseOnlyFormatter {
pub fn format(normal_output: &str, hostname: &str, port: u16) -> String {
Self::strip_target_prefix(normal_output, hostname, port)
}
pub fn strip_target_prefix(output: &str, hostname: &str, port: u16) -> String {
let mut result = String::new();
let prefix_patterns = [
format!("[{}:{}]", hostname, port), format!("{}:{}", hostname, port), format!("[{}]", hostname), hostname.to_string(), ];
for line in output.lines() {
let stripped = Self::strip_line_prefix(line, &prefix_patterns);
if !stripped.is_empty() {
result.push_str(&stripped);
result.push('\n');
}
}
result.trim_end().to_string()
}
fn strip_line_prefix(line: &str, patterns: &[String]) -> String {
for pattern in patterns {
if line.starts_with(pattern) {
let remainder = line[pattern.len()..].trim();
let cleaned = remainder
.trim_start_matches('-')
.trim_start_matches(':')
.trim();
if !cleaned.is_empty() {
return cleaned.to_string();
}
}
}
line.trim().to_string()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_strip_line_prefix() {
let patterns = vec![
"[example.com:443]".to_string(),
"example.com:443".to_string(),
"[example.com]".to_string(),
"example.com".to_string(),
];
let result =
ResponseOnlyFormatter::strip_line_prefix("[example.com:443] TLS 1.3", &patterns);
assert_eq!(result, "TLS 1.3");
let result = ResponseOnlyFormatter::strip_line_prefix("example.com:443 TLS 1.3", &patterns);
assert_eq!(result, "TLS 1.3");
let result =
ResponseOnlyFormatter::strip_line_prefix("example.com:443 - TLS 1.3", &patterns);
assert_eq!(result, "TLS 1.3");
let result = ResponseOnlyFormatter::strip_line_prefix("TLS 1.3", &patterns);
assert_eq!(result, "TLS 1.3");
}
#[test]
fn test_strip_target_prefix() {
let output = "[example.com:443] TLS 1.3\n[example.com:443] TLS_AES_128_GCM_SHA256\n";
let result = ResponseOnlyFormatter::strip_target_prefix(output, "example.com", 443);
let lines: Vec<&str> = result.lines().collect();
assert_eq!(lines.len(), 2);
assert_eq!(lines[0], "TLS 1.3");
assert_eq!(lines[1], "TLS_AES_128_GCM_SHA256");
}
#[test]
fn test_empty_output() {
let result = ResponseOnlyFormatter::strip_target_prefix("", "example.com", 443);
assert_eq!(result, "");
}
#[test]
fn test_multiline_output() {
let output = "[example.com:443] Supported Protocols:\n\
[example.com:443] TLS 1.2\n\
[example.com:443] TLS 1.3\n";
let result = ResponseOnlyFormatter::strip_target_prefix(output, "example.com", 443);
let lines: Vec<&str> = result.lines().collect();
assert_eq!(lines[0], "Supported Protocols:");
assert_eq!(lines[1], "TLS 1.2");
assert_eq!(lines[2], "TLS 1.3");
}
}