github.com/MontFerret/ferret@v0.18.0/pkg/stdlib/strings/decode.go (about)

     1  package strings
     2  
     3  import (
     4  	"context"
     5  	"encoding/base64"
     6  	"net/url"
     7  	"strconv"
     8  
     9  	"github.com/MontFerret/ferret/pkg/runtime/values"
    10  
    11  	"github.com/MontFerret/ferret/pkg/runtime/core"
    12  )
    13  
    14  // FROM_BASE64 returns the value of a base64 representation.
    15  // @param {String} str - The string to decode.
    16  // @return {String} - The decoded string.
    17  func FromBase64(_ context.Context, args ...core.Value) (core.Value, error) {
    18  	err := core.ValidateArgs(args, 1, 1)
    19  
    20  	if err != nil {
    21  		return values.EmptyString, err
    22  	}
    23  
    24  	value := args[0].String()
    25  
    26  	out, err := base64.StdEncoding.DecodeString(value)
    27  	if err != nil {
    28  		return values.EmptyString, err
    29  	}
    30  
    31  	return values.NewString(string(out)), nil
    32  }
    33  
    34  // DECODE_URI_COMPONENT returns the decoded String of uri.
    35  // @param {String} uri - Uri to decode.
    36  // @return {String} - Decoded string.
    37  func DecodeURIComponent(_ context.Context, args ...core.Value) (core.Value, error) {
    38  	err := core.ValidateArgs(args, 1, 1)
    39  
    40  	if err != nil {
    41  		return values.EmptyString, err
    42  	}
    43  
    44  	str, err := url.QueryUnescape(args[0].String())
    45  
    46  	if err != nil {
    47  		return values.None, err
    48  	}
    49  
    50  	// hack for decoding unicode symbols.
    51  	// eg. convert "\u0026" -> "&""
    52  	str, err = strconv.Unquote("\"" + str + "\"")
    53  	if err != nil {
    54  		return values.None, err
    55  	}
    56  
    57  	return values.NewString(str), nil
    58  }