diff --git a/template/functions.go b/template/functions.go index 0f5b180c..157935d9 100644 --- a/template/functions.go +++ b/template/functions.go @@ -31,10 +31,11 @@ type funcMap struct { // Map returns a map of template functions that are compiled during template parsing. func (f *funcMap) Map() template.FuncMap { return template.FuncMap{ - "dict": dict, - "hasKey": hasKey, - "truncate": truncate, - "isEmail": isEmail, + "formatFileSize": formatFileSize, + "dict": dict, + "hasKey": hasKey, + "truncate": truncate, + "isEmail": isEmail, "baseURL": func() string { return config.Opts.BaseURL() }, @@ -200,3 +201,17 @@ func proxify(router *mux.Router, link string) string { // We use base64 url encoding to avoid slash in the URL. return route.Path(router, "proxy", "encodedURL", base64.URLEncoding.EncodeToString([]byte(link))) } + +func formatFileSize(b int64) string { + const unit = 1024 + if b < unit { + return fmt.Sprintf("%d B", b) + } + div, exp := int64(unit), 0 + for n := b / unit; n >= unit; n /= unit { + div *= unit + exp++ + } + return fmt.Sprintf("%.1f %ciB", + float64(b)/float64(div), "KMGTPE"[exp]) +} diff --git a/template/functions_test.go b/template/functions_test.go index 5e373196..4f1ec083 100644 --- a/template/functions_test.go +++ b/template/functions_test.go @@ -314,3 +314,22 @@ func TestProxyFilterWithHttpsInvalid(t *testing.T) { t.Errorf(`Not expected output: got "%s" instead of "%s"`, output, expected) } } + +func TestFormatFileSize(t *testing.T) { + scenarios := []struct { + input int64 + expected string + }{ + {500, "500 B"}, + {1024, "1.0 KiB"}, + {43520, "42.5 KiB"}, + {5000 * 1024 * 1024, "4.9 GiB"}, + } + + for _, scenario := range scenarios { + result := formatFileSize(scenario.input) + if result != scenario.expected { + t.Errorf(`Unexpected result, got %q instead of %q for %d`, result, scenario.expected, scenario.input) + } + } +} diff --git a/template/html/entry.html b/template/html/entry.html index 4dcd3ca2..c7eea4a7 100644 --- a/template/html/entry.html +++ b/template/html/entry.html @@ -115,8 +115,8 @@ {{ end }}