mirror of
https://github.com/offen/docker-volume-backup.git
synced 2026-04-15 05:45:34 +02:00
Add method for converting object to JSON in template (#319)
* Add method for converting object to JSON in template * Split to , * Rename toJson function
This commit is contained in:
@@ -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)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user