func.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. )
  26. func RegisterAdditionalFuncs() {
  27. conf.FuncMap = sprig.FuncMap()
  28. conf.FuncMap["json"] = conf.FuncMap["toJson"]
  29. conf.FuncMap["base64"] = Base64Encode
  30. }
  31. func Base64Encode(para interface{}) (string, error) {
  32. v := reflect.ValueOf(para)
  33. if !v.IsValid() {
  34. return "", fmt.Errorf("based64 error for nil")
  35. }
  36. switch v.Kind() {
  37. case reflect.Bool:
  38. bv := strconv.FormatBool(v.Bool())
  39. return base64.StdEncoding.EncodeToString([]byte(bv)), nil
  40. case reflect.Int, reflect.Int64:
  41. iv := strconv.FormatInt(v.Int(), 10)
  42. return base64.StdEncoding.EncodeToString([]byte(iv)), nil
  43. case reflect.Uint64:
  44. iv := strconv.FormatUint(v.Uint(), 10)
  45. return base64.StdEncoding.EncodeToString([]byte(iv)), nil
  46. case reflect.Float32:
  47. fv := strconv.FormatFloat(v.Float(), 'f', -1, 32)
  48. return base64.StdEncoding.EncodeToString([]byte(fv)), nil
  49. case reflect.Float64:
  50. fv := strconv.FormatFloat(v.Float(), 'f', -1, 64)
  51. return base64.StdEncoding.EncodeToString([]byte(fv)), nil
  52. case reflect.String:
  53. return base64.StdEncoding.EncodeToString([]byte(v.String())), nil
  54. case reflect.Map:
  55. if a, err := json.Marshal(para); err != nil {
  56. return "", err
  57. } else {
  58. en := base64.StdEncoding.EncodeToString(a)
  59. return en, nil
  60. }
  61. default:
  62. return "", fmt.Errorf("Unsupported data type %s for base64 function.", v.Kind())
  63. }
  64. }