perf(auth): compile email regex once via LazyLock

auth.rs 与 comments/helpers.rs 原先每次校验都 Regex::new 重新编译。
改为 LazyLock 全局静态,正则只编译一次。
This commit is contained in:
xfy 2026-06-18 11:25:15 +08:00
parent 3d187382cc
commit 9986d1ce4e
2 changed files with 12 additions and 4 deletions

View File

@ -34,10 +34,14 @@ fn validate_username(username: &str) -> Result<(), String> {
Ok(()) Ok(())
} }
#[cfg(feature = "server")]
static EMAIL_REGEX: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| {
regex::Regex::new(r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$").unwrap()
});
#[cfg(feature = "server")] #[cfg(feature = "server")]
fn validate_email(email: &str) -> Result<(), String> { fn validate_email(email: &str) -> Result<(), String> {
let re = regex::Regex::new(r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$").unwrap(); if !EMAIL_REGEX.is_match(email) {
if !re.is_match(email) {
return Err("邮箱格式不正确".to_string()); return Err("邮箱格式不正确".to_string());
} }
Ok(()) Ok(())

View File

@ -109,11 +109,15 @@ pub fn validate_comment_name(name: &str) -> Result<(), String> {
Ok(()) Ok(())
} }
#[cfg(feature = "server")]
static EMAIL_REGEX: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| {
regex::Regex::new(r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$").unwrap()
});
/// 校验评论作者邮箱格式。 /// 校验评论作者邮箱格式。
#[cfg(feature = "server")] #[cfg(feature = "server")]
pub fn validate_comment_email(email: &str) -> Result<(), String> { pub fn validate_comment_email(email: &str) -> Result<(), String> {
let re = regex::Regex::new(r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$").unwrap(); if !EMAIL_REGEX.is_match(email.trim()) {
if !re.is_match(email.trim()) {
return Err("邮箱格式不正确".to_string()); return Err("邮箱格式不正确".to_string());
} }
Ok(()) Ok(())