func.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright 2022 EMQ Technologies Co., Ltd.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. //go:build template || !core
  15. // +build template !core
  16. package transform
  17. import (
  18. "encoding/base64"
  19. "encoding/json"
  20. "fmt"
  21. "reflect"
  22. "strconv"
  23. "github.com/Masterminds/sprig/v3"
  24. "github.com/lf-edge/ekuiper/internal/conf"
  25. "github.com/lf-edge/ekuiper/pkg/cast"
  26. )
  27. func RegisterAdditionalFuncs() {
  28. conf.FuncMap = sprig.FuncMap()
  29. conf.FuncMap["json"] = conf.FuncMap["toJson"]
  30. conf.FuncMap["base64"] = Base64Encode
  31. }
  32. func Base64Encode(para interface{}) (string, error) {
  33. v := reflect.ValueOf(para)
  34. if !v.IsValid() {
  35. return "", fmt.Errorf("based64 error for nil")
  36. }
  37. switch v.Kind() {
  38. case reflect.Bool:
  39. bv := strconv.FormatBool(v.Bool())
  40. return base64.StdEncoding.EncodeToString([]byte(bv)), nil
  41. case reflect.Int, reflect.Int64:
  42. iv := strconv.FormatInt(v.Int(), 10)
  43. return base64.StdEncoding.EncodeToString([]byte(iv)), nil
  44. case reflect.Uint64:
  45. iv := strconv.FormatUint(v.Uint(), 10)
  46. return base64.StdEncoding.EncodeToString([]byte(iv)), nil
  47. case reflect.Float32:
  48. fv := strconv.FormatFloat(v.Float(), 'f', -1, 32)
  49. return base64.StdEncoding.EncodeToString([]byte(fv)), nil
  50. case reflect.Float64:
  51. fv := strconv.FormatFloat(v.Float(), 'f', -1, 64)
  52. return base64.StdEncoding.EncodeToString([]byte(fv)), nil
  53. case reflect.String:
  54. return base64.StdEncoding.EncodeToString(cast.StringToBytes(v.String())), nil
  55. case reflect.Map:
  56. if a, err := json.Marshal(para); err != nil {
  57. return "", err
  58. } else {
  59. en := base64.StdEncoding.EncodeToString(a)
  60. return en, nil
  61. }
  62. default:
  63. return "", fmt.Errorf("Unsupported data type %s for base64 function.", v.Kind())
  64. }
  65. }