From 5a8a85f0f9462a99be8f7fba22032de7cff13573 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thorben=20G=C3=BCnther?= Date: Tue, 21 Feb 2023 14:37:26 +0100 Subject: [PATCH] Sort labels alphabetically Closes: https://todo.xenrox.net/~xenrox/ntfy-alertmanager/13 --- functions.go | 12 ++++++++++++ main.go | 11 +++++++---- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/functions.go b/functions.go index 8395f8e..642195d 100644 --- a/functions.go +++ b/functions.go @@ -1,5 +1,7 @@ package main +import "sort" + func sliceContains(s []string, e string) bool { for _, v := range s { if e == v { @@ -9,3 +11,13 @@ func sliceContains(s []string, e string) bool { return false } + +func sortKeys(m map[string]string) []string { + var s []string + for key := range m { + s = append(s, key) + } + + sort.Strings(s) + return s +} diff --git a/main.go b/main.go index 344830d..e6b71a3 100644 --- a/main.go +++ b/main.go @@ -79,8 +79,9 @@ func (br *bridge) singleAlertNotifications(p *payload) []*notification { // create body n.body = "Labels:\n" - for key, value := range alert.Labels { - n.body = fmt.Sprintf("%s%s = %s\n", n.body, key, value) + sortedLabelKeys := sortKeys(alert.Labels) + for _, key := range sortedLabelKeys { + n.body = fmt.Sprintf("%s%s = %s\n", n.body, key, alert.Labels[key]) } n.body += "\nAnnotations:\n" @@ -168,8 +169,10 @@ func (br *bridge) multiAlertNotification(p *payload) *notification { for _, alert := range p.Alerts { alertBody := fmt.Sprintf("%s\nLabels:\n", c.String(alert.Status)) - for key, value := range alert.Labels { - alertBody = fmt.Sprintf("%s%s = %s\n", alertBody, key, value) + + sortedLabelKeys := sortKeys(alert.Labels) + for _, key := range sortedLabelKeys { + alertBody = fmt.Sprintf("%s%s = %s\n", alertBody, key, alert.Labels[key]) } alertBody += "Annotations:\n"