3
0

Added base64 encoder to expressions

This commit is contained in:
Peter Grlica
2021-10-28 11:03:43 +02:00
committed by Denis Arh
parent 2a8a3bfdb4
commit 351a9b6c1c
2 changed files with 42 additions and 0 deletions

View File

@@ -1,8 +1,11 @@
package expr
import (
"bytes"
"encoding/base64"
"errors"
"fmt"
"io"
"reflect"
"regexp"
"strings"
@@ -39,6 +42,7 @@ func StringFunctions() []gval.Language {
gval.Function("camelize", camelize),
gval.Function("snakify", snakify),
gval.Function("match", match),
gval.Function("base64encode", base64encode),
}
}
@@ -201,6 +205,37 @@ func snakify(s string) string {
return strings.ToLower(strings.Replace(strings.Title(s), " ", "_", -1))
}
func base64encode(s interface{}) string {
var (
buf bytes.Buffer
)
switch s.(type) {
case string:
s = []byte(s.(string))
case []byte:
s = s.([]byte)
case io.Reader:
buf := new(bytes.Buffer)
buf.ReadFrom(s.(io.Reader))
s = buf.Bytes()
default:
return ""
}
encoder := base64.NewEncoder(base64.StdEncoding, &buf)
if _, err := encoder.Write(s.([]byte)); err != nil {
return ""
}
if err := encoder.Close(); err != nil {
return ""
}
return buf.String()
}
func match(s string, regex interface{}) (b bool, err error) {
var (
r *regexp.Regexp

View File

@@ -196,3 +196,10 @@ func Example_match() {
// output:
// true
}
func Example_base64encode() {
eval(`base64encode("foo bar baz_test")`, nil)
// output:
// Zm9vIGJhciBiYXpfdGVzdA==
}