From 083a37a238d45fcf834070375d2fcd6082f3dda8 Mon Sep 17 00:00:00 2001 From: shengyudong Date: Wed, 26 Nov 2025 18:47:50 +0800 Subject: [PATCH] =?UTF-8?q?=E4=B8=8A=E4=BC=A0=E6=96=87=E4=BB=B6=E8=87=B3?= =?UTF-8?q?=20backend/pkg/utils?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/pkg/utils/utils.go | 61 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 backend/pkg/utils/utils.go diff --git a/backend/pkg/utils/utils.go b/backend/pkg/utils/utils.go new file mode 100644 index 0000000..6224530 --- /dev/null +++ b/backend/pkg/utils/utils.go @@ -0,0 +1,61 @@ +package utils + +import ( + "crypto/rand" + "fmt" + "math/big" + "os" + "path/filepath" + "regexp" + "strings" + "time" +) + +// GetCurrentTime 获取当前时间的格式化字符串 +func GetCurrentTime() string { + return time.Now().Format("2006-01-02 15:04:05") +} + +// FormatTimestamp 将时间戳转换为日期字符串 +func FormatTimestamp(timestamp int64) string { + t := time.Unix(timestamp, 0) + return t.Format("2006-01-02") +} + +// CreateDir 创建目录 +func CreateDir(dirPath string) error { + return os.MkdirAll(dirPath, 0755) +} + +// ExtractFromRegex 使用正则表达式提取内容 +func ExtractFromRegex(content, pattern string) (string, error) { + re := regexp.MustCompile(pattern) + matches := re.FindStringSubmatch(content) + if len(matches) < 2 { + return "", fmt.Errorf("no match found for pattern: %s", pattern) + } + return matches[1], nil +} + +// TransformLink 将原始链接转换为可直接访问的链接 +func TransformLink(originalLink string) string { + // 删除 amp; 字符 + return strings.ReplaceAll(originalLink, "amp;", "") +} + +// GenerateRandomString 生成随机字符串 +func GenerateRandomString(length int) string { + const charset = "0123456789" + result := make([]byte, length) + for i := range result { + num, _ := rand.Int(rand.Reader, big.NewInt(int64(len(charset)))) + result[i] = charset[num.Int64()] + } + return string(result) +} + +// EnsureParentDir 确保父目录存在 +func EnsureParentDir(filePath string) error { + parentDir := filepath.Dir(filePath) + return CreateDir(parentDir) +}