54 lines
997 B
Go
54 lines
997 B
Go
package util
|
|
|
|
import (
|
|
"fmt"
|
|
"math/rand"
|
|
"strings"
|
|
)
|
|
|
|
func HumanSize(size int64) string {
|
|
const unit = 1024
|
|
if size < unit {
|
|
return fmt.Sprintf("%d B", size)
|
|
}
|
|
div, exp := int64(unit), 0
|
|
for n := size / unit; n >= unit; n /= unit {
|
|
div *= unit
|
|
exp++
|
|
}
|
|
return fmt.Sprintf("%.1f %cB",
|
|
float64(size)/float64(div),
|
|
"KMGTPE"[exp],
|
|
)
|
|
}
|
|
|
|
func SafeFilename(name string) string {
|
|
name = strings.TrimSpace(name)
|
|
|
|
out := make([]rune, 0, len(name))
|
|
for _, r := range name {
|
|
// block control chars (incl CR/LF/TAB), DEL, quotes, backslash
|
|
if r < 32 || r == 127 || r == '"' || r == '\\' {
|
|
continue
|
|
}
|
|
out = append(out, r)
|
|
}
|
|
if len(out) == 0 {
|
|
return "file"
|
|
}
|
|
// optional: cap length
|
|
if len(out) > 200 {
|
|
out = out[:200]
|
|
}
|
|
return string(out)
|
|
}
|
|
|
|
func RandomString(n int) string {
|
|
const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
|
b := make([]byte, n)
|
|
for i := range b {
|
|
b[i] = letters[rand.Intn(len(letters))]
|
|
}
|
|
return string(b)
|
|
}
|