Skip to content

Commit

Permalink
Merge pull request #21 from segmentio/allow-special-characters-in-tem…
Browse files Browse the repository at this point in the history
…plate-variables

add json template function to allow escaping of environment variables
  • Loading branch information
achille-roussel committed Dec 10, 2017
2 parents c52a746 + 2795942 commit ee865b9
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
24 changes: 24 additions & 0 deletions load_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,30 @@ points:
}
}

func TestTemplateFunc(t *testing.T) {
const configFile = "/tmp/conf-json-test.yml"
ioutil.WriteFile(configFile, []byte(`---
hello: {{ .NAME | json }}
`), 0644)
defer os.Remove(configFile)

var cfg struct {
Hello string `conf:"hello"`
}

_, _, err := defaultLoader([]string{"test", "-config-file", configFile}, []string{
"NAME=first: Luke, second: Leia",
}).Load(&cfg)

if err != nil {
t.Error(err)
}

if cfg.Hello != "first: Luke, second: Leia" {
t.Error("bad value:", cfg.Hello)
}
}

func TestCommand(t *testing.T) {
t.Run("Success", func(t *testing.T) {
ld := Loader{
Expand Down
11 changes: 10 additions & 1 deletion source.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@ package conf
import (
"bytes"
"flag"
"html/template"
"strings"
"text/template"

"github.com/segmentio/objconv/json"
)

// Source is the interface that allow new types to be plugged into a loader to
Expand Down Expand Up @@ -120,6 +122,13 @@ func (f *fileSource) Load(dst Map) (err error) {
buf := &bytes.Buffer{}
buf.Grow(len(b))

tpl = tpl.Funcs(template.FuncMap{
"json": func(v interface{}) (string, error) {
b, err := json.Marshal(v)
return string(b), err
},
})

if _, err = tpl.Parse(string(b)); err != nil {
return
}
Expand Down

0 comments on commit ee865b9

Please sign in to comment.