util.go
| 1 | // Package util holds small formatting helpers shared by the service and |
| 2 | // handler layers. |
| 3 | package util |
| 4 | |
| 5 | import ( |
| 6 | "fmt" |
| 7 | "net/url" |
| 8 | "strings" |
| 9 | ) |
| 10 | |
| 11 | // FormatClock renders a duration in whole seconds as H:MM:SS, or M:SS when |
| 12 | // under an hour. |
| 13 | func FormatClock(seconds int) string { |
| 14 | if seconds < 0 { |
| 15 | seconds = 0 |
| 16 | } |
| 17 | m := seconds / 60 |
| 18 | s := seconds % 60 |
| 19 | h := m / 60 |
| 20 | m = m % 60 |
| 21 | if h > 0 { |
| 22 | return fmt.Sprintf("%d:%02d:%02d", h, m, s) |
| 23 | } |
| 24 | return fmt.Sprintf("%d:%02d", m, s) |
| 25 | } |
| 26 | |
| 27 | // FormatBytes renders a byte count as a compact human-readable size using |
| 28 | // 1024-based (binary) units with the matching iB suffix. |
| 29 | func FormatBytes(n int64) string { |
| 30 | const unit = 1024 |
| 31 | if n < unit { |
| 32 | return fmt.Sprintf("%d B", n) |
| 33 | } |
| 34 | div, exp := int64(unit), 0 |
| 35 | for m := n / unit; m >= unit; m /= unit { |
| 36 | div *= unit |
| 37 | exp++ |
| 38 | } |
| 39 | return fmt.Sprintf("%.1f %ciB", float64(n)/float64(div), "KMGTPE"[exp]) |
| 40 | } |
| 41 | |
| 42 | // URLEncodePath escapes each segment of a slash-separated path, preserving the |
| 43 | // slashes themselves. |
| 44 | func URLEncodePath(p string) string { |
| 45 | parts := strings.Split(strings.Trim(p, "/"), "/") |
| 46 | for i, part := range parts { |
| 47 | parts[i] = url.PathEscape(part) |
| 48 | } |
| 49 | return strings.Join(parts, "/") |
| 50 | } |
| 51 |