From 64daf7b1324d36bd1603095f4ff07cff6971b7e9 Mon Sep 17 00:00:00 2001 From: Alexander Date: Thu, 21 Dec 2023 00:44:45 +0500 Subject: [PATCH] Add method for converting object to JSON in template (#319) * Add method for converting object to JSON in template * Split to , * Rename toJson function --- cmd/backup/notifications.go | 23 ++++++++++++++++++++++- docs/how-tos/set-up-notifications.md | 2 ++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/cmd/backup/notifications.go b/cmd/backup/notifications.go index 9739418..7ec60f7 100644 --- a/cmd/backup/notifications.go +++ b/cmd/backup/notifications.go @@ -6,6 +6,7 @@ package main import ( "bytes" _ "embed" + "encoding/json" "errors" "fmt" "os" @@ -84,7 +85,9 @@ var templateHelpers = template.FuncMap{ "formatBytesBin": func(bytes uint64) string { return formatBytes(bytes, false) }, - "env": os.Getenv, + "env": os.Getenv, + "toJson": toJson, + "toPrettyJson": toPrettyJson, } // formatBytes converts an amount of bytes in a human-readable representation @@ -106,3 +109,21 @@ func formatBytes(b uint64, decimal bool) string { } return fmt.Sprintf(format, float64(b)/float64(div), "kMGTPE"[exp]) } + +func toJson(v interface{}) string { + var bytes []byte + var err error + if bytes, err = json.Marshal(v); err != nil { + return fmt.Sprintf("failed to marshal JSON in notification template: %v", err) + } + return string(bytes) +} + +func toPrettyJson(v interface{}) string { + var bytes []byte + var err error + if bytes, err = json.MarshalIndent(v, "", " "); err != nil { + return fmt.Sprintf("failed to marshal indent JSON in notification template: %v", err) + } + return string(bytes) +} diff --git a/docs/how-tos/set-up-notifications.md b/docs/how-tos/set-up-notifications.md index ee9ffdf..4a3e979 100644 --- a/docs/how-tos/set-up-notifications.md +++ b/docs/how-tos/set-up-notifications.md @@ -107,6 +107,8 @@ Some formatting and helper functions are also available: * `formatBytesBin`: formats an amount of bytes using powers of 1024 (e.g. `7055258` bytes will be `6.7 MiB`) * `formatBytesDec`: formats an amount of bytes using powers of 1000 (e.g. `7055258` bytes will be `7.1 MB`) * `env`: returns the value of the environment variable of the given key if set +* `toJson`: converting object to JSON +* `toPrettyJson`: converting object to pretty JSON ## Special characters in notification URLs