Skip to content

Commit

Permalink
Add method for converting object to JSON in template (#319)
Browse files Browse the repository at this point in the history
* Add method for converting object to JSON in template

* Split  to ,

* Rename toJson function
  • Loading branch information
hywax authored Dec 20, 2023
1 parent 06792eb commit 64daf7b
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
23 changes: 22 additions & 1 deletion cmd/backup/notifications.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package main
import (
"bytes"
_ "embed"
"encoding/json"
"errors"
"fmt"
"os"
Expand Down Expand Up @@ -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
Expand All @@ -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)
}
2 changes: 2 additions & 0 deletions docs/how-tos/set-up-notifications.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down

0 comments on commit 64daf7b

Please sign in to comment.