aboutsummaryrefslogtreecommitdiff
path: root/internal/template/template.go
blob: 350a0edcc7ddd45034a88c7d5b0fe64b89bccc54 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package template

import (
	"fmt"
	"html/template"
	"strings"
)

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(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 %cB", float64(b)/float64(div), "KMGTPE"[exp])
}

var funcMap = template.FuncMap{
	"dict":        dict,
	"join":        join,
	"lastUrlPart": LastUrlPart,
	"byteCount":   byteCount,
}

func fromString(name, templateStr string) *template.Template {
	tpl := template.New(name).Funcs(funcMap)
	return template.Must(tpl.Parse(templateStr))
}