Skip to content

Commit

Permalink
Added sha256Hex function
Browse files Browse the repository at this point in the history
this will compute the sha256 hash function and output the hex verion
of it.

tests and doc updated.
  • Loading branch information
vfoucault committed Dec 16, 2019
1 parent 09d1603 commit 42abf71
Show file tree
Hide file tree
Showing 4 changed files with 53 additions and 0 deletions.
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ this functionality might prove useful.
- [regexMatch](#regexmatch)
- [regexReplaceAll](#regexreplaceall)
- [replaceAll](#replaceall)
- [sha256Hex](#sha256hex)
- [split](#split)
- [timestamp](#timestamp)
- [toJSON](#tojson)
Expand Down Expand Up @@ -1838,6 +1839,14 @@ This function can be chained with other functions as well:
{{ service "web" }}{{ .Name | replaceAll ":" "_" }}{{ end }}
```
##### `sha256Hex`
Takes the argument as a string and compute the sha256_hex value
```liquid
{{ "bladibla" | sha256Hex }}
```
##### `split`
Splits the given string on the provided separator:
Expand Down
10 changes: 10 additions & 0 deletions template/funcs.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ package template

import (
"bytes"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"io/ioutil"
Expand Down Expand Up @@ -1379,3 +1381,11 @@ func sockaddr(args ...string) (string, error) {
}
return k, nil
}

// sha256Hex return the sha256 hex of a string
func sha256Hex(item string) (string, error) {
h := sha256.New()
h.Write([]byte(item))
output := hex.EncodeToString(h.Sum(nil))
return output, nil
}
33 changes: 33 additions & 0 deletions template/funcs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -234,3 +234,36 @@ func Test_byMeta(t *testing.T) {
})
}
}

func Test_sha256Hex(t *testing.T) {
type args struct {
item string
}
tests := []struct {
name string
args args
want string
wantErr bool
}{
{
name: "Should return the proper string",
args: args{
item: "bladibla",
},
want: "54cf4c66bcabb5c20e25331c01dd600b73369e97a947861bd8d3a0e0b8b3d70b",
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := sha256Hex(tt.args.item)
if (err != nil) != tt.wantErr {
t.Errorf("sha256Hex() error = %v, wantErr %v", err, tt.wantErr)
return
}
if got != tt.want {
t.Errorf("sha256Hex() got = %v, want %v", got, tt.want)
}
})
}
}
1 change: 1 addition & 0 deletions template/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,7 @@ func funcMap(i *funcMapInput) template.FuncMap {
"regexReplaceAll": regexReplaceAll,
"regexMatch": regexMatch,
"replaceAll": replaceAll,
"sha256Hex": sha256Hex,
"timestamp": timestamp,
"toLower": toLower,
"toJSON": toJSON,
Expand Down

0 comments on commit 42abf71

Please sign in to comment.