mirror of
https://github.com/adnanh/webhook.git
synced 2025-06-06 04:32:29 +00:00
feat: Add two template functions (#712)
* chore: replace ioutil.ReadFile by os.ReadFile * feat: Add two template functions - cat: Allows reading a value from a file - credential: Allows reading a credential passed by systemd
This commit is contained in:
parent
7bb680821d
commit
eb7e8f5ba8
1 changed files with 31 additions and 3 deletions
|
@ -13,12 +13,12 @@ import (
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"hash"
|
"hash"
|
||||||
"io/ioutil"
|
|
||||||
"log"
|
"log"
|
||||||
"math"
|
"math"
|
||||||
"net"
|
"net"
|
||||||
"net/textproto"
|
"net/textproto"
|
||||||
"os"
|
"os"
|
||||||
|
"path"
|
||||||
"reflect"
|
"reflect"
|
||||||
"regexp"
|
"regexp"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
@ -750,14 +750,18 @@ func (h *Hooks) LoadFromFile(path string, asTemplate bool) error {
|
||||||
}
|
}
|
||||||
|
|
||||||
// parse hook file for hooks
|
// parse hook file for hooks
|
||||||
file, e := ioutil.ReadFile(path)
|
file, e := os.ReadFile(path)
|
||||||
|
|
||||||
if e != nil {
|
if e != nil {
|
||||||
return e
|
return e
|
||||||
}
|
}
|
||||||
|
|
||||||
if asTemplate {
|
if asTemplate {
|
||||||
funcMap := template.FuncMap{"getenv": getenv}
|
funcMap := template.FuncMap{
|
||||||
|
"cat": cat,
|
||||||
|
"credential": credential,
|
||||||
|
"getenv": getenv,
|
||||||
|
}
|
||||||
|
|
||||||
tmpl, err := template.New("hooks").Funcs(funcMap).Parse(string(file))
|
tmpl, err := template.New("hooks").Funcs(funcMap).Parse(string(file))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
@ -956,3 +960,27 @@ func compare(a, b string) bool {
|
||||||
func getenv(s string) string {
|
func getenv(s string) string {
|
||||||
return os.Getenv(s)
|
return os.Getenv(s)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// cat provides a template function to retrieve content of files
|
||||||
|
// Similarly to getenv, if no file is found, it returns the empty string
|
||||||
|
func cat(s string) string {
|
||||||
|
data, e := os.ReadFile(s)
|
||||||
|
|
||||||
|
if e != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
return string(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
// credential provides a template function to retreive secrets using systemd's LoadCredential mechanism
|
||||||
|
func credential(s string) string {
|
||||||
|
dir := getenv("CREDENTIALS_DIRECTORY")
|
||||||
|
|
||||||
|
// If no credential directory is found, fallback to the env variable
|
||||||
|
if dir == "" {
|
||||||
|
return getenv(s)
|
||||||
|
}
|
||||||
|
|
||||||
|
return cat(path.Join(dir, s))
|
||||||
|
}
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue