dougaicha5258 2017-01-06 12:24
浏览 611
已采纳

在Go模板中对Alertmanager电子邮件模板进行排序

I'm trying to customize an Email template from AlertManager that uses a Go html template that prints a list of alerts using the following construct :

{{ range .Alerts.Firing }}

It gets inserted into the template like this :

func (n *Email) Notify(ctx context.Context, as ...*types.Alert) (bool, error) {
   ...
   data = n.tmpl.Data(receiverName(ctx), groupLabels(ctx), as...)
   ...
}

Alert being defined like this :

type Alert struct {
    Labels LabelSet `json:"labels"`

    Annotations LabelSet `json:"annotations"`

    StartsAt     time.Time `json:"startsAt,omitempty"`
    EndsAt       time.Time `json:"endsAt,omitempty"`
    GeneratorURL string    `json:"generatorURL"`
}

I would like to do the sorting on the StartsAt field.

I tried using the sort function but it wasn't available in the email template.

{{ range sort .Alerts.Firing }}

I'm getting

function \"sort\" not defined

Any ideas on how I can get it to sort on StartsAt ?

  • 写回答

2条回答 默认 最新

  • dpdhf02040 2017-01-06 13:00
    关注

    Sort the alerts before you pass it to template execution. It's easier, also a template should not alter the data it's destined to display.

    Example:

    type ByStart []*types.Alert
    
    func (a ByStart) Len() int           { return len(a) }
    func (a ByStart) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
    func (a ByStart) Less(i, j int) bool { return a[i].StartAt.Before(a[j].StartAt) }
    
    func (n *Email) Notify(ctx context.Context, as ...*types.Alert) (bool, error) {
        ...
        sort.Sort(ByStart(as))
        data = n.tmpl.Data(receiverName(ctx), groupLabels(ctx), as...)
        ...
    }
    

    Edit:

    Sorting functionality is not available from templates by default. You can register custom functions that can be called from templates, but this must be done prior to parsing the templates, and from Go code (not from the template text; see Template.Funcs()). This is so because templates must be statically analyzable, and knowing what custom functions are valid is key when parsing the template text.

    Just from the template text, without the help of custom functions, you can't achieve this.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图