Skip to content

Commit

Permalink
feat(interpolate): add helper (#6266)
Browse files Browse the repository at this point in the history
  • Loading branch information
fsamin authored Sep 7, 2022
1 parent 5b8d932 commit c33aa76
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
9 changes: 9 additions & 0 deletions sdk/interpolate/interpolate_helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"net/url"
"path"
"reflect"
"strconv"
"strings"
"text/template"

Expand Down Expand Up @@ -66,6 +67,7 @@ func init() {
"b64enc": base64encode,
"b64dec": base64decode,
"escape": escape,
"stringQuote": stringQuote,
"add": func(i ...interface{}) int64 {
var a int64 = 0
for _, b := range i {
Expand Down Expand Up @@ -375,6 +377,13 @@ func escape(s string) string {
return s1
}

func stringQuote(s string) string {
x := strconv.Quote(s)
x = strings.TrimPrefix(x, `"`)
x = strings.TrimSuffix(x, `"`)
return x
}

func ternary(v, v2, a interface{}) interface{} {
if cast.ToBool(a) {
return v
Expand Down
9 changes: 9 additions & 0 deletions sdk/interpolate/interpolate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -673,3 +673,12 @@ func TestDashReplacementWithµµµ(t *testing.T) {
assert.NoError(t, err)
assert.Equal(t, "result.headers.x-cache is a", got)
}

func TestStringQuote(t *testing.T) {
vars := map[string]string{
"content": `{"foo": "{\"bar\":\"baz\"}"}`,
}
got, err := Do("content is {{.content | stringQuote}}", vars)
assert.NoError(t, err)
assert.Equal(t, `content is {\"foo\": \"{\\\"bar\\\":\\\"baz\\\"}\"}`, got)
}

0 comments on commit c33aa76

Please sign in to comment.