funcs.go 2.0 KB

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