Files
ProjectOctopus/agent-common/utils/StringUtils.go
2024-04-28 16:55:18 +08:00

52 lines
842 B
Go

package utils
import (
"fmt"
"math/rand"
"time"
)
func GenerateRandomString(length int) string {
rand.Seed(time.Now().UnixNano())
chars := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
b := make([]byte, length)
for i := range b {
b[i] = chars[rand.Intn(len(chars))]
}
return string(b)
}
func ByteSizeToString(size uint64) string {
const (
B = 1
KB = 1024 * B
MB = 1024 * KB
GB = 1024 * MB
TB = 1024 * GB
)
var unit string
var value float64
switch {
case size >= TB:
value = float64(size) / TB
unit = "TB"
case size >= GB:
value = float64(size) / GB
unit = "GB"
case size >= MB:
value = float64(size) / MB
unit = "MB"
case size >= KB:
value = float64(size) / KB
unit = "KB"
default:
value = float64(size)
unit = "B"
}
return fmt.Sprintf("%.2f %s", value, unit)
}