writer_hooks.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Copyright 2023 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 file
  15. import "bytes"
  16. type writerHooks interface {
  17. Header() []byte
  18. Line() []byte
  19. Footer() []byte
  20. }
  21. type jsonWriterHooks struct{}
  22. func (j *jsonWriterHooks) Header() []byte {
  23. return []byte("[")
  24. }
  25. func (j *jsonWriterHooks) Line() []byte {
  26. return []byte(",")
  27. }
  28. func (j *jsonWriterHooks) Footer() []byte {
  29. return []byte("]")
  30. }
  31. var jsonHooks = &jsonWriterHooks{}
  32. type linesWriterHooks struct{}
  33. func (l *linesWriterHooks) Header() []byte {
  34. return nil
  35. }
  36. func (l *linesWriterHooks) Line() []byte {
  37. return []byte("\n")
  38. }
  39. func (l *linesWriterHooks) Footer() []byte {
  40. return nil
  41. }
  42. var linesHooks = &linesWriterHooks{}
  43. type csvWriterHooks struct {
  44. header []byte
  45. }
  46. func (c *csvWriterHooks) Header() []byte {
  47. if c.header != nil {
  48. return bytes.Join([][]byte{c.header, c.Line()}, nil)
  49. }
  50. return nil
  51. }
  52. func (c *csvWriterHooks) Line() []byte {
  53. return []byte("\n")
  54. }
  55. func (c *csvWriterHooks) Footer() []byte {
  56. return nil
  57. }
  58. func (c *csvWriterHooks) SetHeader(header string) {
  59. c.header = []byte(header)
  60. }