You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

79 lines
2.2 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package internal
import (
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/util/gconv"
"regexp"
"strings"
"time"
)
// 单位与字节的换算关系1单位 = 多少字节)
var unitMap = map[string]int64{
"b": 1, // 字节
"kb": 1 << 10, // 1KB = 1024B
"mb": 1 << 20, // 1MB = 1024KB
"gb": 1 << 30, // 1GB = 1024MB
"tb": 1 << 40, // 1TB = 1024GB
}
// 单位与秒的换算1单位 = 多少秒)
var durationMap = map[string]int64{
"s": 1,
"m": 60,
"h": 3600,
"d": 86400,
}
// parseSize 将带单位的大小字符串(如"100kb"、"2MB")转换为字节数
func parseSize(sizeStr string) (int64, error) {
if sizeStr == "" {
return 0, gerror.New("空的大小配置")
}
// 正则匹配:提取数字和单位(支持整数/小数,如"1.5mb"
re := regexp.MustCompile(`^(\d+(\.\d+)?)([a-zA-Zb]+)$`)
matches := re.FindStringSubmatch(strings.TrimSpace(sizeStr))
if len(matches) != 4 {
return 0, gerror.New("无效的大小格式示例100kb、2mb、1g")
}
// 提取数值和单位
valueStr := matches[1]
unit := strings.ToLower(matches[3]) // 单位转为小写(统一处理)
// 转换数值为float64
value := gconv.Float64(valueStr)
// 查找单位对应的字节数
unitBytes, ok := unitMap[unit]
if !ok {
return 0, gerror.Newf("不支持的单位:{%+v}支持b、kb、mb、gb、tb", unit)
}
// 计算总字节数(数值 * 单位字节数)
return int64(value * float64(unitBytes)), nil
}
// parseDuration 将带单位的时间字符串(如"30s"、"5m"转换为time.Duration
func parseDuration(intervalStr string) (time.Duration, error) {
if intervalStr == "" {
return 30 * time.Second, nil // 默认30秒
}
re := regexp.MustCompile(`^(\d+)([smhd])$`) // 匹配数字+单位s/m/h/d
matches := re.FindStringSubmatch(strings.TrimSpace(intervalStr))
if len(matches) != 3 {
return 0, gerror.New("无效的时间格式示例30s、5m、1h")
}
num := gconv.Int(matches[1])
unit := matches[2]
sec, ok := durationMap[unit]
if !ok {
return 0, gerror.New("不支持的单位仅支持s/m/h/d")
}
return time.Duration(num) * time.Duration(sec) * time.Second, nil
}