fix: ignore non-utf8 words when saving to db

This commit is contained in:
wizardchen
2025-08-21 19:47:12 +08:00
committed by lyingbug
parent 53d8b13aad
commit 1eed11fc4f
7 changed files with 404 additions and 3 deletions
+25
View File
@@ -6,6 +6,7 @@ import (
"regexp"
"slices"
"strings"
"unicode/utf8"
)
// ToInterfaceSlice converts a slice of strings to a slice of empty interfaces.
@@ -73,3 +74,27 @@ func ParseLLMJsonResponse(content string, target interface{}) error {
// If no code block found, return the original error
return err
}
// CleanInvalidUTF8 移除字符串中的非法 UTF-8 字符和 \x00
func CleanInvalidUTF8(s string) string {
var b strings.Builder
b.Grow(len(s))
for i := 0; i < len(s); {
r, size := utf8.DecodeRuneInString(s[i:])
if r == utf8.RuneError && size == 1 {
// 非法 UTF-8 字节,跳过
i++
continue
}
if r == 0 {
// NULL 字符 \x00,跳过
i += size
continue
}
b.WriteRune(r)
i += size
}
return b.String()
}