diff --git a/docs/encoding.md b/docs/encoding.md index 1c7a36f8..0613cd2c 100644 --- a/docs/encoding.md +++ b/docs/encoding.md @@ -4,3 +4,4 @@ Sprig has the following encoding and decoding functions: - `b64enc`/`b64dec`: Encode or decode with Base64 - `b32enc`/`b32dec`: Encode or decode with Base32 +- `printf "%x"` / `hexdec`: Encode or decode as hexadecimal diff --git a/docs/index.md b/docs/index.md index 7e898fa5..8067e29d 100644 --- a/docs/index.md +++ b/docs/index.md @@ -9,7 +9,7 @@ The Sprig library provides over 70 template functions for Go's template language - [Float Math Functions](mathf.md): `addf`, `maxf`, `mulf`, etc. - [Date Functions](date.md): `now`, `date`, etc. - [Defaults Functions](defaults.md): `default`, `empty`, `coalesce`, `fromJson`, `toJson`, `toPrettyJson`, `toRawJson`, `ternary` -- [Encoding Functions](encoding.md): `b64enc`, `b64dec`, etc. +- [Encoding Functions](encoding.md): `b64enc`, `b64dec`, `hexdec` - [Lists and List Functions](lists.md): `list`, `first`, `uniq`, etc. - [Dictionaries and Dict Functions](dicts.md): `get`, `set`, `dict`, `hasKey`, `pluck`, `dig`, `deepCopy`, etc. - [Type Conversion Functions](conversion.md): `atoi`, `int64`, `toString`, etc. diff --git a/functions.go b/functions.go index 57fcec1d..f5001eec 100644 --- a/functions.go +++ b/functions.go @@ -289,6 +289,7 @@ var genericMap = map[string]interface{}{ "b64dec": base64decode, "b32enc": base32encode, "b32dec": base32decode, + "hexdec": hexdecode, // Data Structures: "tuple": list, // FIXME: with the addition of append/prepend these are no longer immutable. diff --git a/strings.go b/strings.go index e0ae628c..2fbcd839 100644 --- a/strings.go +++ b/strings.go @@ -3,6 +3,7 @@ package sprig import ( "encoding/base32" "encoding/base64" + "encoding/hex" "fmt" "reflect" "strconv" @@ -35,6 +36,14 @@ func base32decode(v string) string { return string(data) } +func hexdecode(v string) string { + data, err := hex.DecodeString(v) + if err != nil { + return err.Error() + } + return string(data) +} + func abbrev(width int, s string) string { if width < 4 { return s diff --git a/strings_test.go b/strings_test.go index a75ab086..89943c70 100644 --- a/strings_test.go +++ b/strings_test.go @@ -171,6 +171,16 @@ func TestBase64EncodeDecode(t *testing.T) { t.Error(err) } } + +func TestHexEncodeDecode(t *testing.T) { + magicWord := "\x00coffee\xfb" + + tpl := `{{printf "%x" "\x00coffee\xfb" | hexdec }}` + if err := runt(tpl, magicWord); err != nil { + t.Error(err) + } +} + func TestBase32EncodeDecode(t *testing.T) { magicWord := "coffee" expect := base32.StdEncoding.EncodeToString([]byte(magicWord))