molecule-man / vipertpl

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

vipertpl

GoDoc CircleCI

Package vipertpl extends viper's functionality with ability to use golang templates in string variables.

Usage example

input := []byte(`
foo: 'foo_val'
bar: 'bar_val + {{ ViperGet "foo" }}'
`)

viper.SetConfigType("yaml")

err := viper.ReadConfig(bytes.NewBuffer(input))
if err != nil {
	panic(err)
}

err = vipertpl.Parse(viper.GetViper())
if err != nil {
	panic(err)
}

fmt.Printf("%#v", viper.Get("bar"))
// Output: "bar_val + foo_val"

Template funcs

ViperGet

ViperGet is a built-in function, a wrapper over viper.Get function which applies template parsing to the output of viper.Get (can be used recursively. See the following example).

# example yaml config
foo: "foo value"
bar: 'bar value + {{ ViperGet "foo" }}'
buz: 'buz value + {{ ViperGet "bar" }}'
// ... read config with viper ...
vipertpl.Parse(viper.GetViper())
fmt.Printf("%#v", viper.Get("buz"))
// Output: "buz value + bar val + foo val"

Exec

Exec is a built-in function which executes specified external command.

# example yaml config
foo: '{{ Exec "echo" "foo_val" }}'

Docker port

It is possible to invoke command docker port CONTAINER PRIVATE_PORT inside the template:

database:
  dsn: 'user:password@tcp({{ DockerPort "myservice.mysql" 3306 }})
import (
	"text/template"

	"github.com/molecule-man/vipertpl"
	"github.com/molecule-man/vipertpl/docker"
	"github.com/spf13/viper"
)

// ... read config with viper ...
// ...

dockerFuncs, err := docker.New()
if err != nil {
	panic(err)
}

// as the `docker port` function is not built-in we must initialize parser with
// this function added to a list of available template functions:
parser := vipertpl.New(template.FuncMap{
	"DockerPort": dockerFuncs.Port,
})

parser.Parse(viper.GetViper())
fmt.Printf("%#v", viper.Get("database.dsn"))
// Given that there is docker container running under name myservice.mysql with
// private port published at port 32173 the output will be
// "user:password@tcp(0.0.0.0:32173)"

About

License:MIT License


Languages

Language:Go 100.0%