Skip to content
Snippets Groups Projects
Commit 4fbf60db authored by Tamer Tas's avatar Tamer Tas
Browse files

Implement human readable file size template function

parent dbf279a7
No related branches found
No related tags found
No related merge requests found
......@@ -3,6 +3,7 @@ package template
import (
"fmt"
"os"
"reflect"
"strconv"
"strings"
"text/template"
......@@ -30,6 +31,50 @@ var (
return fmt.Sprintf("%b", n)
},
"formatFilesize": func(value interface{}) string {
var size float64
v := reflect.ValueOf(value)
switch v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
size = float64(v.Int())
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
size = float64(v.Uint())
case reflect.Float32, reflect.Float64:
size = v.Float()
default:
return ""
}
var KB float64 = 1 << 10
var MB float64 = 1 << 20
var GB float64 = 1 << 30
var TB float64 = 1 << 40
var PB float64 = 1 << 50
filesizeFormat := func(filesize float64, suffix string) string {
return strings.Replace(fmt.Sprintf("%.1f %s", filesize, suffix), ".0", "", -1)
}
var result string
if size < KB {
result = filesizeFormat(size, "bytes")
} else if size < MB {
result = filesizeFormat(size/KB, "KB")
} else if size < GB {
result = filesizeFormat(size/MB, "MB")
} else if size < TB {
result = filesizeFormat(size/GB, "GB")
} else if size < PB {
result = filesizeFormat(size/TB, "TB")
} else {
result = filesizeFormat(size/PB, "PB")
}
return result
},
// String utilities
"toLower": strings.ToLower,
"toUpper": strings.ToUpper,
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment