util.go
⎇
Raw
1// Package util holds small helpers shared by the service and handler layers:
2// output formatting and external-command plumbing.
3package util
4
5import (
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.
13func 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 uses 1024-based units with the matching iB suffix.
28func FormatBytes(n int64) string {
29 const unit = 1024
30 if n < unit {
31 return fmt.Sprintf("%d B", n)
32 }
33 div, exp := int64(unit), 0
34 for m := n / unit; m >= unit; m /= unit {
35 div *= unit
36 exp++
37 }
38 return fmt.Sprintf("%.1f %ciB", float64(n)/float64(div), "KMGTPE"[exp])
39}
40
41// URLEncodePath escapes each segment of a slash-separated path, preserving the
42// slashes themselves.
43func URLEncodePath(p string) string {
44 parts := strings.Split(strings.Trim(p, "/"), "/")
45 for i, part := range parts {
46 parts[i] = url.PathEscape(part)
47 }
48 return strings.Join(parts, "/")
49}
50