converter.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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 delimited
  15. import (
  16. "bytes"
  17. "fmt"
  18. "sort"
  19. "strconv"
  20. "strings"
  21. "github.com/lf-edge/ekuiper/pkg/message"
  22. )
  23. type Converter struct {
  24. delimiter string
  25. cols []string
  26. }
  27. func NewConverter(delimiter string) (message.Converter, error) {
  28. if delimiter == "" {
  29. delimiter = ","
  30. }
  31. return &Converter{delimiter: delimiter}, nil
  32. }
  33. func (c *Converter) SetColumns(cols []string) {
  34. c.cols = cols
  35. }
  36. // Encode If no columns defined, the default order is sort by key
  37. func (c *Converter) Encode(d interface{}) ([]byte, error) {
  38. switch m := d.(type) {
  39. case map[string]interface{}:
  40. sb := &bytes.Buffer{}
  41. if len(c.cols) == 0 {
  42. keys := make([]string, 0, len(m))
  43. for k := range m {
  44. keys = append(keys, k)
  45. }
  46. sort.Strings(keys)
  47. c.cols = keys
  48. }
  49. for i, v := range c.cols {
  50. if i > 0 {
  51. sb.WriteString(c.delimiter)
  52. }
  53. fmt.Fprintf(sb, "%v", m[v])
  54. }
  55. return sb.Bytes(), nil
  56. default:
  57. return nil, fmt.Errorf("unsupported type %v, must be a map", d)
  58. }
  59. }
  60. // Decode If the cols is not set, the default key name is col1, col2, col3...
  61. // The return value is always a map
  62. func (c *Converter) Decode(b []byte) (interface{}, error) {
  63. tokens := strings.Split(string(b), c.delimiter)
  64. m := make(map[string]interface{})
  65. if len(c.cols) == 0 {
  66. for i, v := range tokens {
  67. m["col"+strconv.Itoa(i)] = v
  68. }
  69. } else {
  70. for i, v := range tokens {
  71. if i < len(c.cols) {
  72. m[c.cols[i]] = v
  73. }
  74. }
  75. }
  76. return m, nil
  77. }