Skip to content

Commit

Permalink
Merge pull request #1327 from ContentSquare/func/sha256Hex
Browse files Browse the repository at this point in the history
Added sha256Hex function
  • Loading branch information
eikenb authored Apr 24, 2020
2 parents b11b029 + 42abf71 commit dbcb0c6
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 @@ -1848,6 +1849,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 @@ -1519,3 +1521,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 @@ -201,3 +201,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 dbcb0c6

Please sign in to comment.