aboutsummaryrefslogtreecommitdiff
path: root/internal/feed/template/template.go
diff options
context:
space:
mode:
authorRené 'Necoro' Neumann <necoro@necoro.eu>2020-04-23 20:51:11 +0200
committerRené 'Necoro' Neumann <necoro@necoro.eu>2020-04-23 20:51:11 +0200
commitf8a89ce8d9a3d5882a484fcaec810dc90f4a5e5d (patch)
treedd66407c2e9fede7730b82b61a6c284747cf62f5 /internal/feed/template/template.go
parentc883470c2ef977b8675b12428591bb003694e235 (diff)
downloadfeed2imap-go-f8a89ce8d9a3d5882a484fcaec810dc90f4a5e5d.tar.gz
feed2imap-go-f8a89ce8d9a3d5882a484fcaec810dc90f4a5e5d.tar.bz2
feed2imap-go-f8a89ce8d9a3d5882a484fcaec810dc90f4a5e5d.zip
Move template to subfolder of feed
Diffstat (limited to 'internal/feed/template/template.go')
-rw-r--r--internal/feed/template/template.go68
1 files changed, 68 insertions, 0 deletions
diff --git a/internal/feed/template/template.go b/internal/feed/template/template.go
new file mode 100644
index 0000000..dd31f51
--- /dev/null
+++ b/internal/feed/template/template.go
@@ -0,0 +1,68 @@
+package template
+
+import (
+ "fmt"
+ "html/template"
+ "strconv"
+ "strings"
+
+ "github.com/Necoro/feed2imap-go/internal/log"
+)
+
+func dict(v ...string) map[string]string {
+ dict := map[string]string{}
+ lenv := len(v)
+ for i := 0; i < lenv; i += 2 {
+ key := v[i]
+ if i+1 >= lenv {
+ dict[key] = ""
+ continue
+ }
+ dict[key] = v[i+1]
+ }
+ return dict
+}
+
+func join(sep string, parts []string) string {
+ return strings.Join(parts, sep)
+}
+
+func lastUrlPart(url string) string {
+ split := strings.Split(url, "/")
+ return split[len(split)-1]
+}
+
+func byteCount(str string) string {
+ b, err := strconv.ParseUint(str, 10, 64)
+ if 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) template.HTML {
+ return template.HTML(s)
+}
+
+var funcMap = template.FuncMap{
+ "dict": dict,
+ "join": join,
+ "lastUrlPart": lastUrlPart,
+ "byteCount": byteCount,
+ "html": html,
+}
+
+func fromString(name, templateStr string) *template.Template {
+ tpl := template.New(name).Funcs(funcMap)
+ return template.Must(tpl.Parse(templateStr))
+}