/
reader.go
96 lines (81 loc) · 1.86 KB
/
reader.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package csv
import (
"encoding/csv"
"strconv"
"strings"
"github.com/qor/exchange"
"github.com/qor/qor"
"github.com/qor/qor/resource"
)
// NewReader new csv reader
func (c *CSV) NewReader(res *exchange.Resource, context *qor.Context) (exchange.Rows, error) {
var rows = Rows{CSV: c, Resource: res}
readCloser, err := c.getReader()
if err == nil {
defer readCloser.Close()
reader := csv.NewReader(readCloser)
reader.TrimLeadingSpace = true
rows.records, err = reader.ReadAll()
if c.config.TrimSpace {
for _, rows := range rows.records {
for i, record := range rows {
rows[i] = strings.TrimSpace(record)
}
}
}
rows.total = len(rows.records) - 1
if res.Config.WithoutHeader {
rows.total++
}
}
return &rows, err
}
// Rows CSV rows struct
type Rows struct {
*CSV
Resource *exchange.Resource
current int
total int
}
// Header CSV header column
func (rows Rows) Header() (results []string) {
if rows.total > 0 {
if rows.Resource.Config.WithoutHeader {
for i := 0; i <= len(rows.records[0]); i++ {
results = append(results, strconv.Itoa(i))
}
} else {
return rows.records[0]
}
}
return
}
// Total CSV total rows
func (rows *Rows) Total() uint {
return uint(rows.total)
}
// Next read next rows from CSV
func (rows *Rows) Next() bool {
if rows.total >= rows.current+1 {
rows.current++
return true
}
return false
}
// ReadRow read row from CSV
func (rows Rows) ReadRow() (*resource.MetaValues, error) {
var metaValues resource.MetaValues
columns := rows.Header()
for index, column := range columns {
metaValue := resource.MetaValue{
Name: column,
Value: rows.records[rows.current][index],
}
if meta := rows.Resource.GetMeta(column); meta != nil {
metaValue.Meta = meta
metaValue.Name = meta.Name
}
metaValues.Values = append(metaValues.Values, &metaValue)
}
return &metaValues, nil
}