template.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. package transform
  15. import (
  16. "bytes"
  17. "encoding/json"
  18. "fmt"
  19. "github.com/lf-edge/ekuiper/internal/conf"
  20. "text/template"
  21. )
  22. type TransFunc func(interface{}) ([]byte, bool, error)
  23. func GenTransform(dt string) (TransFunc, error) {
  24. var tp *template.Template = nil
  25. if dt != "" {
  26. temp, err := template.New("sink").Funcs(conf.FuncMap).Parse(dt)
  27. if err != nil {
  28. return nil, err
  29. }
  30. tp = temp
  31. }
  32. return func(d interface{}) ([]byte, bool, error) {
  33. if tp != nil {
  34. var output bytes.Buffer
  35. err := tp.Execute(&output, d)
  36. if err != nil {
  37. return nil, false, fmt.Errorf("fail to encode data %v with dataTemplate for error %v", d, err)
  38. }
  39. return output.Bytes(), true, nil
  40. } else {
  41. j, err := json.Marshal(d)
  42. return j, false, err
  43. }
  44. }, nil
  45. }
  46. func GenTp(dt string) (*template.Template, error) {
  47. return template.New("sink").Funcs(conf.FuncMap).Parse(dt)
  48. }