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 写uniapp时遇到的问题
  • ¥15 vs 2008 安装遇到问题
  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥20 MATLAB绘制两隐函数曲面的交线
  • ¥15 求TYPCE母转母转接头24PIN线路板图