templates - 如何用逗号连接领事模板的服务元数据

标签 templates go consul consul-template

有谁知道如何将 consul 的字符串连接到 consul-template?

如果我在 Consul 中注册了一个服务 'foo'

{
  "Node": "node1",
  "Address": "192.168.0.1",
  "Port": 3333
},
{
  "Node": "node2",
  "Address": "192.168.0.2",
  "Port": 4444
}

我希望 consul-template 生成以下行:

servers=192.168.0.1:3333,192.168.0.2:4444/bogus

以下尝试无效,因为它留下了尾随逗号 ,

servers={{range service "foo"}}{{.Address}}{{.Port}},{{end}}/bogus
# renders
servers=192.168.0.1:3333,192.168.0.2:4444,/bogus

# What I actually want
servers=192.168.0.1:3333,192.168.0.2:4444/bogus

我知道 consul-template 使用 golang 模板语法,但我就是想不出使它正常工作的语法。我很可能应该使用 consul-template 的 join 但我如何将 .Address.Port 传递给 join?这只是一个微不足道的例子,我并没有故意使用索引,因为服务的数量可能超过两个。有什么想法吗?

最佳答案

这应该有效。

{{$foo_srv := service "foo"}}
{{if $foo_srv}}
  {{$last := len $foo_srv | subtract 1}}
servers=
  {{- range $i := loop $last}}
    {{- with index $foo_srv $i}}{{.Address}}{{.Port}},{{end}}
  {{- end}}
  {{- with index $foo_srv last}}{{.Address}}{{.Port}}{{end}}/bogus
{{end}}

我在想是否可以使用“join”。

注意“{{-”表示删除前导空格(如 ' '、\t、\n)。

关于templates - 如何用逗号连接领事模板的服务元数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38574399/

相关文章:

mongodb - Mongo-go-driver:超出上下文截止日期

encryption - 如何用RSA加密大文件?

java - 如何从 Spring Boot 应用程序更改 consul K/V Store 中的值

spring-boot - Spring Cloud 配置服务器与领事之间的区别?

java - Freemarker 模板引擎 <#if condition> 具有动态条件

c++ - 从我的 .exe 中隐藏纯文本字符串

c++ - 可以设计一个包含模板参数默认值的类吗?

c++ - 返回特定类型的模板

go - 在 Go 中读取不断增长的 mmap 文件

docker - Docker Swarm领事未启动