如何将andeq/ne函数组合在一起?

我写了这段代码

{{ define "opsgenie.default.tmpl" }}
  <font size="+0"><b>{{.CommonLabels.alertname }}</b></font>
  {{- range $i, $alert := .Alerts }}
  <font size="+0">{{ .Annotations.description }}</font>
  {{- end -}}
  {{- "\n" -}}
  {{- "\n" -}}
  {{- if and eq .CommonLabels.infoalert "true" eq .CommonLabels.topic "database" -}}
  Grafana: https://{{ .CommonLabels.url }}
  {{- "\n" -}}{{- end -}}
  {{- if and ne .CommonLabels.infoalert "true" eq .CommonLabels.topic "database" -}}
  Database:
    • https://{{ .CommonLabels.url }}/
    • https://{{ .CommonLabels.url }}/
  {{- "\n" -}}{{- end -}}
  {{- end -}}
  {{- end -}}
{{- end -}}

目标是:

  • 如果我的alert 同时包含标签infoalert: truetopic: database,则仅显示Grafana链接
  • 如果我的alert 只包含标签topic: database而不包含infoalert: true,则仅显示数据缺失链接

条件{{- if and eq .CommonLabels.infoalert "true" eq .CommonLabels.topic "database" -}}的语法看起来不正确,因为在触发alert 时,我在警示管理器.log中收到以下错误:

notify retry canceled due to unrecoverable error after 1 attempts: templating error: template: email.tmpl:24:17: executing \"opsgenie.default.tmpl\" at <eq>: wrong number of args for eq: want at least 1 got 0

推荐答案

只需使用括号对表达式进行分组:

{{- if and (eq .CommonLabels.infoalert "true") (eq .CommonLabels.topic "database") -}}

{{- if and (ne .CommonLabels.infoalert "true") (eq .CommonLabels.topic "database") -}}

请参阅此可测试示例:

func main() {
    t := template.Must(template.New("").Parse(src))

    m := map[string]any{
        "infoalert": "true",
        "topic":     "database",
    }
    if err := t.Execute(os.Stdout, m); err != nil {
        panic(err)
    }

    fmt.Println("Second round")
    m["infoalert"] = "false"
    if err := t.Execute(os.Stdout, m); err != nil {
        panic(err)
    }
}

const src = `
{{- if and (eq .infoalert "true") (eq .topic "database") -}}
    infoalert is true and topic is database
{{- end -}}
{{- if and (ne .infoalert "true") (eq .topic "database") -}}
    infoalert is NOT true and topic is database
{{ end }}
`

这将输出(在Go Playground上试用):

infoalert is true and topic is database
Second round
infoalert is NOT true and topic is database

Go相关问答推荐

T的Golang通用切片,其中 *T实现接口

语法-for循环中的initit陈述是否允许分配?

在GO中创建[]字符串类型的变量

如何在围棋中从多部分.Part中获取多部分.文件而不保存到磁盘?

Wamtime Memory中的‘Offset’是什么?Read?

Golang内置打印(Ln)函数&S行为怪异

Golang String

提供的client_secret与此帐户上任何关联的SetupIntent都不匹配

如何用';贪婪原则';正确地

Golang Fiber Render - 将数据发送到多个布局

为什么 mux.Vars() 返回空的 map[]

如何将Golang测试用例的测试覆盖率值与特定阈值进行比较

从给定顶点查找图形中所有闭合路径的算法

如何使用名称具有包名称的嵌套 struct 启动 go struct

如何在 Go 中编写示例测试?

Go:如何在将 float64 转换为 float32 时判断精度损失

Golang泛型在用作 map 元素时不起作用

Golang Echo Labstack 如何在模板视图中调用函数/方法

Golang 泛型同时具有接口和实现

手动下载并放置一个 golang mod 文件