converter.go 2.0 KB

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