Add template formatting
This commit is contained in:
parent
bf6bc34364
commit
36cb91953c
3 changed files with 48 additions and 1 deletions
|
|
@ -51,7 +51,11 @@ func FormatValue(format string, val interface{}) string {
|
|||
// ReplaceFormatted replaces all occurrences of ${key} with formatted val from the kv map
|
||||
func ReplaceFormatted(s string, kv map[string]interface{}) (string, error) {
|
||||
// Enhanced golang template logic
|
||||
tpl, err := template.New("base").Funcs(sprig.FuncMap()).Parse(s)
|
||||
tpl, err := template.New("base").
|
||||
Funcs(sprig.FuncMap()).
|
||||
Funcs(map[string]any{
|
||||
"timeRound": timeRound,
|
||||
}).Parse(s)
|
||||
if err != nil {
|
||||
return s, err
|
||||
}
|
||||
|
|
|
|||
14
util/format_functions.go
Normal file
14
util/format_functions.go
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
package util
|
||||
|
||||
import "time"
|
||||
|
||||
func timeRound(d time.Duration, round string) time.Duration {
|
||||
switch round {
|
||||
case "s", "sec":
|
||||
return d.Round(time.Second)
|
||||
case "m", "min":
|
||||
return d.Round(time.Minute)
|
||||
default:
|
||||
return d
|
||||
}
|
||||
}
|
||||
|
|
@ -3,6 +3,7 @@ package util
|
|||
import (
|
||||
"math"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestTruish(t *testing.T) {
|
||||
|
|
@ -70,3 +71,31 @@ func TestReplaceNoMatch(t *testing.T) {
|
|||
t.Error(s, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReplaceTemplate(t *testing.T) {
|
||||
tc := []struct {
|
||||
in, out, key string
|
||||
val any
|
||||
}{
|
||||
{`"{{ .mode }}"`, `"pv"`, "mode", "pv"},
|
||||
{`{{ printf "%.1f" .chargedEnergy }}kW`, `1.2kW`, "chargedEnergy", 1.234},
|
||||
{`{{ round .chargedEnergy 1 }}kW`, `1.2kW`, "chargedEnergy", 1.234},
|
||||
{`{{ timeRound .connectedDuration "s" }}`, `1s`, "connectedDuration", 1234 * time.Millisecond},
|
||||
{`{{ timeRound .connectedDuration "m" }}`, `21m0s`, "connectedDuration", 1234 * time.Second},
|
||||
}
|
||||
|
||||
for _, tc := range tc {
|
||||
s, err := ReplaceFormatted(tc.in, map[string]interface{}{
|
||||
tc.key: tc.val,
|
||||
})
|
||||
|
||||
t.Log(s)
|
||||
if err != nil {
|
||||
t.Error(s, err)
|
||||
}
|
||||
|
||||
if s != tc.out {
|
||||
t.Errorf("expected: %s, got: %s", tc.out, s)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue