Implement Stringer interface for Pairs and KVs (#3256)

This commit implements the Stringer interface for Pairs and KVs.
It changes how Pairs are printed in templates from
map[name1:value1 name2:value2] to name1=value1, name2=value2. KVs
work similar, but are first sorted into pairs before being printed.

Signed-off-by: George Robinson <george.robinson@grafana.com>
This commit is contained in:
George Robinson 2023-02-22 11:38:15 +00:00 committed by GitHub
parent fe1b045c00
commit 11d0b57c97
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 24 additions and 0 deletions

View File

@ -187,6 +187,19 @@ func (ps Pairs) Values() []string {
return vs return vs
} }
func (ps Pairs) String() string {
b := strings.Builder{}
for i, p := range ps {
b.WriteString(p.Name)
b.WriteRune('=')
b.WriteString(p.Value)
if i < len(ps)-1 {
b.WriteString(", ")
}
}
return b.String()
}
// KV is a set of key/value string pairs. // KV is a set of key/value string pairs.
type KV map[string]string type KV map[string]string
@ -239,6 +252,10 @@ func (kv KV) Values() []string {
return kv.SortedPairs().Values() return kv.SortedPairs().Values()
} }
func (kv KV) String() string {
return kv.SortedPairs().String()
}
// Data is the data passed to notification templates and webhook pushes. // Data is the data passed to notification templates and webhook pushes.
// //
// End-users should not be exposed to Go's type system, as this will confuse them and prevent // End-users should not be exposed to Go's type system, as this will confuse them and prevent

View File

@ -48,6 +48,13 @@ func TestPairValues(t *testing.T) {
require.EqualValues(t, expected, pairs.Values()) require.EqualValues(t, expected, pairs.Values())
} }
func TestPairsString(t *testing.T) {
pairs := Pairs{{"name1", "value1"}}
require.Equal(t, "name1=value1", pairs.String())
pairs = append(pairs, Pair{"name2", "value2"})
require.Equal(t, "name1=value1, name2=value2", pairs.String())
}
func TestKVSortedPairs(t *testing.T) { func TestKVSortedPairs(t *testing.T) {
kv := KV{"d": "dVal", "b": "bVal", "c": "cVal"} kv := KV{"d": "dVal", "b": "bVal", "c": "cVal"}