fix
Some checks failed
部署后端服务 / 🧪 测试后端 (push) Failing after 5m8s
部署后端服务 / 🚀 构建并部署 (push) Has been skipped
部署后端服务 / 🔄 回滚部署 (push) Has been skipped

This commit is contained in:
xujiang
2025-07-10 18:09:11 +08:00
parent 35004f224e
commit 010fe2a8c7
96 changed files with 23709 additions and 19 deletions

View File

@ -0,0 +1,68 @@
package utils
import (
"regexp"
"strconv"
"strings"
"unicode"
)
// GenerateSlug 生成URL友好的slug
func GenerateSlug(text string) string {
// 转换为小写
text = strings.ToLower(text)
// 移除重音字符
text = removeAccents(text)
// 替换空格和特殊字符为连字符
reg := regexp.MustCompile(`[^\p{L}\p{N}]+`)
text = reg.ReplaceAllString(text, "-")
// 移除首尾的连字符
text = strings.Trim(text, "-")
// 移除连续的连字符
reg = regexp.MustCompile(`-+`)
text = reg.ReplaceAllString(text, "-")
return text
}
// removeAccents 移除重音字符的转换函数
func removeAccents(text string) string {
var result strings.Builder
for _, r := range text {
if !unicode.Is(unicode.Mn, r) {
result.WriteRune(r)
}
}
return result.String()
}
// TruncateString 截断字符串到指定长度
func TruncateString(s string, length int) string {
if len(s) <= length {
return s
}
return s[:length]
}
// GenerateUniqueSlug 生成唯一的slug
func GenerateUniqueSlug(base string, existingCheck func(string) bool) string {
slug := GenerateSlug(base)
if !existingCheck(slug) {
return slug
}
// 如果存在重复,添加数字后缀
for i := 1; i <= 1000; i++ {
candidateSlug := slug + "-" + strconv.Itoa(i)
if !existingCheck(candidateSlug) {
return candidateSlug
}
}
// 如果还是重复,使用时间戳
return slug + "-" + GenerateRandomString(6)
}