From f05c89afa485b0fd8ec7cba954d73102cacc551f Mon Sep 17 00:00:00 2001 From: ETL Date: Wed, 23 Sep 2015 14:24:34 -0400 Subject: [PATCH] Adds a toMap function which converts a ServiceTags element into a map. This is needed to use the Registrator (http://gliderlabs.com/registrator) / Consul-Template tools in order to dynamically configure Apache. Since Consul does not support Registrator's Attributes, and can only work with labels, a method of having key-values is necessary. By creating key=value labels, one can achieve this. --- README.md | 13 +++++++++++++ template.go | 1 + template_functions.go | 15 +++++++++++++++ 3 files changed, 29 insertions(+) diff --git a/README.md b/README.md index 018cf1ce4..d9771f533 100644 --- a/README.md +++ b/README.md @@ -749,6 +749,19 @@ Takes the argument as a string and converts it to lowercase. See Go's [strings.ToLower()](http://golang.org/pkg/strings/#ToLower) for more information. +##### 'toMap' +Takes the argument as a ServiceTags and converts any tag which are of the style `key=value` into a `map`. + +Given the following tags in a service entry: ``path=/test lbset=group1`` + +```liquid +{{range service "www"}} + {{$x := .Tags | toMap}} + ProxyPass {{$x.path}} http://{{$x.lbset}}{{$x.path}} + ProxyPassReverse {{$x.path}} http://{{$x.lbset}}{{$x.path}} +{{end}} +``` + ##### `toTitle` Takes the argument as a string and converts it to titlecase. diff --git a/template.go b/template.go index 5a52956a9..5a4d6acc0 100644 --- a/template.go +++ b/template.go @@ -116,6 +116,7 @@ func funcMap(brain *Brain, used, missing map[string]dep.Dependency) template.Fun "replaceAll": replaceAll, "timestamp": timestamp, "toLower": toLower, + "toMap": toMap, "toJSON": toJSON, "toJSONPretty": toJSONPretty, "toTitle": toTitle, diff --git a/template_functions.go b/template_functions.go index d652521e7..70a4b08da 100644 --- a/template_functions.go +++ b/template_functions.go @@ -810,3 +810,18 @@ func addDependency(m map[string]dep.Dependency, d dep.Dependency) { m[d.HashCode()] = d } } + +// toMap converts ServiceTags into a map. It loops through the tags +// and any tag that has an equal sign in it is indexed in the map. +func toMap(entries dep.ServiceTags) (map[string]string, error) { + m := make(map[string]string) + for i := 0; i < len(entries); i++ { + if strings.Contains(entries[i], "=") { + item := strings.Split(entries[i], "=") + m[item[0]] = item[1] + } + } + return m, nil +} + +