fix
This commit is contained in:
68
backend-old/internal/utils/slug.go
Normal file
68
backend-old/internal/utils/slug.go
Normal 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)
|
||||
}
|
||||
Reference in New Issue
Block a user