csv.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package exchange
  2. import (
  3. "encoding/csv"
  4. "errors"
  5. "io"
  6. "strings"
  7. )
  8. func NewCSVReader(rc io.ReadCloser) (Reader, error) {
  9. if rc == nil {
  10. return nil, errors.New("reader is nil")
  11. }
  12. defer rc.Close()
  13. r := csv.NewReader(rc)
  14. r.TrimLeadingSpace = true
  15. header, err := r.Read()
  16. if err != nil {
  17. return nil, err
  18. }
  19. header = trimStringSliceSpace(header)
  20. records, err := r.ReadAll()
  21. if err != nil {
  22. return nil, err
  23. }
  24. for i, r := range records {
  25. records[i] = trimStringSliceSpace(r)
  26. }
  27. return &csvReader{
  28. header: header,
  29. records: records,
  30. curr: 0,
  31. total: len(records),
  32. }, nil
  33. }
  34. type csvReader struct {
  35. header []string
  36. records [][]string
  37. curr int
  38. total int
  39. }
  40. var _ Reader = (*csvReader)(nil)
  41. func (c *csvReader) Header() []string {
  42. return c.header
  43. }
  44. func (c *csvReader) ReadRow() ([]string, error) {
  45. if c.total < c.curr {
  46. return nil, errors.New("no more row")
  47. }
  48. return c.records[c.curr-1], nil
  49. }
  50. func (c *csvReader) Next() bool {
  51. if c.total <= c.curr {
  52. return false
  53. }
  54. c.curr++
  55. return true
  56. }
  57. func (c *csvReader) Total() uint {
  58. return uint(c.total)
  59. }
  60. func trimStringSliceSpace(rs []string) []string {
  61. nrs := make([]string, 0, len(rs))
  62. for _, r := range rs {
  63. nrs = append(nrs, strings.TrimSpace(r))
  64. }
  65. return nrs
  66. }
  67. func NewCSVWriter(w io.Writer) (Writer, error) {
  68. if w == nil {
  69. return nil, errors.New("writer is nil")
  70. }
  71. return &csvWriter{
  72. w: csv.NewWriter(w),
  73. }, nil
  74. }
  75. type csvWriter struct {
  76. w *csv.Writer
  77. }
  78. func (c *csvWriter) WriteHeader(h []string) error {
  79. return c.w.Write(h)
  80. }
  81. func (c *csvWriter) WriteRow(r []string) error {
  82. return c.w.Write(r)
  83. }
  84. func (c *csvWriter) Flush() error {
  85. c.w.Flush()
  86. return nil
  87. }