douzhuanqian8244 2016-07-25 17:52 采纳率: 100%
浏览 100

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

Does anyone know how to concatenate strings from consul for consul-template?

If I have a service 'foo' registered in Consul

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

I would like consul-template to generate the following line:

servers=192.168.0.1:3333,192.168.0.2:4444/bogus

The following attempt does not work since it leaves a trailing comma ,

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

I know consul-template uses golang template syntax, but I simply cannot figure out the syntax to get this working. Its likely that I should use consul-template's join but how do I pass both .Address and .Port to join? This is just a trivial example, and I'm not using indexes intentionally since the number of services could be more than two. Any ideas?

  • 写回答

2条回答 默认 最新

  • dongwei3712 2016-07-26 07:14
    关注

    You can use a custom plugin.

    servers={{service "foo" | toJSON | plugin "path/to/plugin"}}
    

    The plugin code:

    package main
    
    import (
        "encoding/json"
        "fmt"
        "os"
    )
    
    type InputEntry struct {
        Node    string
        Address string
        Port    int
    }
    
    func main() {
        arg := []byte(os.Args[1])
        var input []InputEntry
        if err := json.Unmarshal(arg, &input); err != nil {
            fmt.Fprintln(os.Stderr, fmt.Sprintf("err: %s", err))
            os.Exit(1)
        }
    
        var output string
        for i, entry := range input {
            output += fmt.Sprintf("%v:%v", entry.Address, entry.Port)
            if i != len(input)-1 {
                output += ","
            }
        }
    
        fmt.Fprintln(os.Stdout, string(output))
        os.Exit(0)
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 ubuntu系统下挂载磁盘上执行./提示权限不够
  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 关于#r语言#的问题:差异分析前数据准备,报错Error in data[, sampleName1] : subscript out of bounds请问怎么解决呀以下是全部代码:
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥30 3天&7天&&15天&销量如何统计同一行