Files
backend/pkg/utils/format.go
lan 4b4980820f
Some checks failed
SonarQube Analysis / sonarqube (push) Has been cancelled
Test / test (push) Has been cancelled
Test / lint (push) Has been cancelled
Test / build (push) Has been cancelled
chore: 初始化仓库,排除二进制文件和覆盖率文件
2025-11-28 23:30:49 +08:00

48 lines
1.2 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package utils
import (
"go.uber.org/zap"
"strings"
)
// FormatUUID 将UUID格式化为带连字符的标准格式
// 如果输入已经是标准格式,直接返回
// 如果输入是32位十六进制字符串添加连字符
// 如果输入格式无效,返回错误
func FormatUUID(uuid string) string {
// 如果为空,直接返回
if uuid == "" {
return uuid
}
// 如果已经是标准格式8-4-4-4-12直接返回
if len(uuid) == 36 && uuid[8] == '-' && uuid[13] == '-' && uuid[18] == '-' && uuid[23] == '-' {
return uuid
}
// 如果是32位十六进制字符串添加连字符
if len(uuid) == 32 {
// 预分配容量以提高性能
var b strings.Builder
b.Grow(36) // 最终长度为36(32个字符 + 4个连字符)
// 使用WriteString和WriteByte优化性能
b.WriteString(uuid[0:8])
b.WriteByte('-')
b.WriteString(uuid[8:12])
b.WriteByte('-')
b.WriteString(uuid[12:16])
b.WriteByte('-')
b.WriteString(uuid[16:20])
b.WriteByte('-')
b.WriteString(uuid[20:32])
return b.String()
}
// 如果长度不是32或36说明格式无效直接返回原值
var logger *zap.Logger
logger.Warn("[WARN] UUID格式无效: ", zap.String("uuid:", uuid))
return uuid
}