diff options
author | René 'Necoro' Neumann <necoro@necoro.eu> | 2022-01-09 00:20:24 +0100 |
---|---|---|
committer | René 'Necoro' Neumann <necoro@necoro.eu> | 2022-01-09 00:20:24 +0100 |
commit | d480edb65af5d6e9d8906940cdd4093761c1b451 (patch) | |
tree | 186cf7e2aee6576d84fdb3df11e6a06bc80d6a52 /internal/feed/template/funcs.go | |
parent | 0d3a8c8bab2fad592e192169a83e286d0d2ab692 (diff) | |
download | feed2imap-go-d480edb65af5d6e9d8906940cdd4093761c1b451.tar.gz feed2imap-go-d480edb65af5d6e9d8906940cdd4093761c1b451.tar.bz2 feed2imap-go-d480edb65af5d6e9d8906940cdd4093761c1b451.zip |
template: Restructuring and adding tests.
Diffstat (limited to 'internal/feed/template/funcs.go')
-rw-r--r-- | internal/feed/template/funcs.go | 72 |
1 files changed, 72 insertions, 0 deletions
diff --git a/internal/feed/template/funcs.go b/internal/feed/template/funcs.go new file mode 100644 index 0000000..300b9ca --- /dev/null +++ b/internal/feed/template/funcs.go @@ -0,0 +1,72 @@ +package template + +import ( + "fmt" + html "html/template" + "strconv" + "strings" + + "github.com/Necoro/feed2imap-go/pkg/log" +) + +// dict creates a map out of the passed in key/value pairs. +func dict(v ...interface{}) map[string]interface{} { + dict := make(map[string]interface{}) + lenv := len(v) + for i := 0; i < lenv; i += 2 { + key := v[i].(string) + if i+1 >= lenv { + dict[key] = "" + continue + } + dict[key] = v[i+1] + } + return dict +} + +// join takes a separator and a list of strings and puts the former in between each pair of the latter. +func join(sep string, parts []string) string { + return strings.Join(parts, sep) +} + +// lastUrlPart returns the last part of a URL string +func lastUrlPart(url string) string { + split := strings.Split(url, "/") + return split[len(split)-1] +} + +// byteCount receives an integer as a string, that is interpreted as a size in bytes. +// This size is then equipped with the corresponding unit: +// +func byteCount(str string) string { + var b uint64 + if str != "" { + var err error + if b, err = strconv.ParseUint(str, 10, 64); err != nil { + log.Printf("Cannot convert '%s' to byte count: %s", str, err) + } + } + + const unit = 1024 + if b < unit { + return fmt.Sprintf("%d B", b) + } + div, exp := uint64(unit), 0 + for n := b / unit; n >= unit; n /= unit { + div *= unit + exp++ + } + return fmt.Sprintf("%.1f %cB", float64(b)/float64(div), "KMGTPE"[exp]) +} + +func _html(s string) html.HTML { + return html.HTML(s) +} + +var funcMap = map[string]interface{}{ + "dict": dict, + "join": join, + "lastUrlPart": lastUrlPart, + "byteCount": byteCount, + "html": _html, +} |