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 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏