utils.go 906 B raw
1
package main
2
3
import (
4
	"fmt"
5
	"strings"
6
	"time"
7
)
8
9
func FormatBytes(bytes int64) string {
10
	const unit = 1024
11
	if bytes < unit {
12
		return fmt.Sprintf("%d B", bytes)
13
	}
14
	div, exp := int64(unit), 0
15
	for n := bytes / unit; n >= unit; n /= unit {
16
		div *= unit
17
		exp++
18
	}
19
	return fmt.Sprintf("%.1f %ciB", float64(bytes)/float64(div), "KMGTPE"[exp])
20
}
21
22
func FormatUptime(uptime time.Duration) string {
23
	days := int(uptime.Hours() / 24)
24
	hours := int(uptime.Hours()) % 24
25
	minutes := int(uptime.Minutes()) % 60
26
	seconds := int(uptime.Seconds()) % 60
27
28
	var parts []string
29
	if days > 0 {
30
		parts = append(parts, fmt.Sprintf("%dd", days))
31
	}
32
	if hours > 0 {
33
		parts = append(parts, fmt.Sprintf("%dh", hours))
34
	}
35
	if minutes > 0 {
36
		parts = append(parts, fmt.Sprintf("%dm", minutes))
37
	}
38
	if seconds > 0 || len(parts) == 0 {
39
		parts = append(parts, fmt.Sprintf("%ds", seconds))
40
	}
41
42
	return strings.Join(parts, " ")
43
}