62 lines
1.5 KiB
Go
62 lines
1.5 KiB
Go
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)
|
|
}
|