99 lines
1.9 KiB
Go
99 lines
1.9 KiB
Go
package helper
|
|
|
|
import (
|
|
"fmt"
|
|
"mime"
|
|
"net/url"
|
|
"path/filepath"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
func ParseSizeToKB(sizeStr string) (int64, error) {
|
|
s := strings.TrimSpace(strings.ToLower(sizeStr))
|
|
|
|
var multiplier float64
|
|
switch {
|
|
case strings.HasSuffix(s, "gb"):
|
|
multiplier = 1024 * 1024
|
|
s = strings.TrimSuffix(s, "gb")
|
|
case strings.HasSuffix(s, "mb"):
|
|
multiplier = 1024
|
|
s = strings.TrimSuffix(s, "mb")
|
|
case strings.HasSuffix(s, "kb"):
|
|
multiplier = 1
|
|
s = strings.TrimSuffix(s, "kb")
|
|
default:
|
|
return 0, fmt.Errorf("unrecognized unit in %q", sizeStr)
|
|
}
|
|
|
|
s = strings.TrimSpace(s)
|
|
value, err := strconv.ParseFloat(s, 64)
|
|
if err != nil {
|
|
return 0, fmt.Errorf("invalid number %q: %w", s, err)
|
|
}
|
|
|
|
return int64(value * multiplier), nil
|
|
}
|
|
|
|
func FormatSizeFromKB(sizeKB int64) (string, error) {
|
|
if sizeKB < 0 {
|
|
return "", fmt.Errorf("size must be non-negative")
|
|
}
|
|
|
|
units := []string{"Kb", "Mb", "Gb", "Tb"} //Add more if needed.
|
|
unitIndex := 0
|
|
|
|
sizeFloat := float64(sizeKB)
|
|
|
|
for sizeFloat >= 1024 && unitIndex < len(units)-1 {
|
|
sizeFloat /= 1024
|
|
unitIndex++
|
|
}
|
|
|
|
return fmt.Sprintf("%.2f %s", sizeFloat, units[unitIndex]), nil
|
|
}
|
|
|
|
func GetLastPathElement(u *url.URL) string {
|
|
|
|
path := u.Path
|
|
if path == "" {
|
|
return "" // Handle empty path
|
|
}
|
|
|
|
parts := strings.Split(path, "/")
|
|
if len(parts) == 0 {
|
|
return ""
|
|
}
|
|
|
|
return parts[len(parts)-1]
|
|
}
|
|
|
|
func GetMimeTypeFromFilename(filename string) string {
|
|
ext := strings.ToLower(filepath.Ext(filename))
|
|
if ext == "" {
|
|
return "application/octet-stream" // fallback
|
|
}
|
|
|
|
mimeType := mime.TypeByExtension(ext)
|
|
if mimeType != "" {
|
|
return mimeType
|
|
}
|
|
|
|
// handle common missing types
|
|
switch ext {
|
|
case ".mov":
|
|
return "video/quicktime"
|
|
case ".rar":
|
|
return "application/x-rar-compressed"
|
|
default:
|
|
return "application/octet-stream"
|
|
}
|
|
}
|
|
|
|
func ParseCustomDateTime(input string) (time.Time, error) {
|
|
layout := "15:04:05 02/01/2006"
|
|
return time.Parse(layout, input)
|
|
}
|