Skip to content

Commit

Permalink
gstrings
Browse files Browse the repository at this point in the history
  • Loading branch information
snail007 committed Jan 8, 2024
1 parent 03243a8 commit 6fb1d48
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
9 changes: 9 additions & 0 deletions util/strings/strings.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package gstrings

import (
"os"
"strings"
"unsafe"
)
Expand Down Expand Up @@ -72,3 +73,11 @@ func Replace(str string, oldNew ...string) string {
r := strings.NewReplacer(oldNew...)
return r.Replace(str)
}

// Render replaces ${var} or $var in the string based on the mapping data,
// 'var' is key in data map.
func Render(str string, data map[string]string) string {
return os.Expand(str, func(key string) string {
return data[key]
})
}
33 changes: 33 additions & 0 deletions util/strings/strings_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,3 +63,36 @@ func TestContainsAll(t *testing.T) {
assert.True(t, ContainsAll("abcd", "ab", "bc", "cd"))
assert.True(t, ContainsAll("abcd"))
}

func TestRender(t *testing.T) {
// Define test cases
tests := []struct {
input string
data map[string]string
expected string
}{
{
input: "Hello, ${NAME}!",
data: map[string]string{"NAME": "John"},
expected: "Hello, John!",
},
{
input: "This is $CITY, ${COUNTRY}.",
data: map[string]string{"CITY": "New York", "COUNTRY": "USA"},
expected: "This is New York, USA.",
},
{
input: "No placeholders here!",
data: map[string]string{"KEY": "VALUE"},
expected: "No placeholders here!",
},
}

// Run test cases
for _, test := range tests {
result := Render(test.input, test.data)
if result != test.expected {
t.Errorf("Render(%s, %v) = %s, want %s", test.input, test.data, result, test.expected)
}
}
}

0 comments on commit 6fb1d48

Please sign in to comment.