diff --git a/pkg/stdlib/strings/decode.go b/pkg/stdlib/strings/decode.go new file mode 100644 index 00000000..82bb7a6a --- /dev/null +++ b/pkg/stdlib/strings/decode.go @@ -0,0 +1,31 @@ +package strings + +import ( + "context" + "encoding/base64" + + "github.com/MontFerret/ferret/pkg/runtime/values" + + "github.com/MontFerret/ferret/pkg/runtime/core" +) + +/* + * Returns the value of a base64 representation. + * @param base64String (String) - The string to decode. + * @returns value (String) - The decoded string. + */ +func FromBase64(_ context.Context, args ...core.Value) (core.Value, error) { + err := core.ValidateArgs(args, 1, 1) + if err != nil { + return values.EmptyString, err + } + + value := args[0].String() + + out, err := base64.StdEncoding.DecodeString(value) + if err != nil { + return values.EmptyString, err + } + + return values.NewString(string(out)), nil +} diff --git a/pkg/stdlib/strings/decode_test.go b/pkg/stdlib/strings/decode_test.go new file mode 100644 index 00000000..c3564ef8 --- /dev/null +++ b/pkg/stdlib/strings/decode_test.go @@ -0,0 +1,46 @@ +package strings_test + +import ( + "context" + "testing" + + "github.com/MontFerret/ferret/pkg/runtime/values" + + "github.com/MontFerret/ferret/pkg/stdlib/strings" + + . "github.com/smartystreets/goconvey/convey" +) + +func TestFromBase64(t *testing.T) { + Convey("When args are not passed", t, func() { + Convey("It should return an error", func() { + var err error + _, err = strings.FromBase64(context.Background()) + + So(err, ShouldBeError) + }) + }) + + Convey("When hash is not valid base64", t, func() { + Convey("It should return an error", func() { + var err error + _, err = strings.FromBase64( + context.Background(), + values.NewString("foobar"), + ) + + So(err, ShouldBeError) + }) + }) + + Convey("Should decode a given hash", t, func() { + out, err := strings.FromBase64( + context.Background(), + values.NewString("Zm9vYmFy"), + ) + + So(err, ShouldBeNil) + So(out, ShouldNotEqual, "Zm9vYmFy") + So(out, ShouldEqual, "foobar") + }) +} diff --git a/pkg/stdlib/strings/lib.go b/pkg/stdlib/strings/lib.go index ef7a45a2..8ae9c877 100644 --- a/pkg/stdlib/strings/lib.go +++ b/pkg/stdlib/strings/lib.go @@ -31,6 +31,7 @@ func NewLib() map[string]core.Function { "SUBSTITUTE": Substitute, "SUBSTRING": Substring, "TO_BASE64": ToBase64, + "FROM_BASE64": FromBase64, "TRIM": Trim, "UPPER": Upper, }