-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcsv.go
81 lines (75 loc) · 1.57 KB
/
csv.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
package utils
import (
"encoding/csv"
"io"
"log"
)
// CSVParser parses csv and runs callback function
func CSVParser(r *csv.Reader, cb func(res *[]string, chunk int), rows int) error {
ins := []string{}
chunk := 0
for {
record, err := r.Read()
if err == io.EOF {
break
}
if err != nil {
log.Println(err.Error())
return err
}
// no error, safe to read record
ins = append(ins, record...)
// if ins length is ROWSIZE, chunk size reached, make this a chunk (++chunk)
if len(ins) == rows {
// run chunk callback function
go cb(&ins, chunk)
// empty slice
ins = ins[:0]
chunk++
}
}
if len(ins) > 0 {
go cb(&ins, chunk)
}
log.Printf("finish parsing csv, total chunks : %d\n", chunk)
return nil
}
// CSVParserH parses csv with headers and runs callback function
func CSVParserH(r *csv.Reader, cb func(res *[]map[string]string, chunk int), rows int) error {
ins := []map[string]string{}
headers := []string{}
chunk := 0
for {
record, err := r.Read()
if err == io.EOF {
break
}
if err != nil {
log.Println(err.Error())
return err
}
// no error, safe to read record
if len(headers) == 0 {
headers = record
continue
}
// headers inserted
tmp := map[string]string{}
for i := range headers {
tmp[headers[i]] = record[i]
}
ins = append(ins, tmp)
// if ins length is ROWSIZE, chunk size reached, make this a chunk (++chunk)
if len(ins) == rows {
// run chunk callback function
go cb(&ins, chunk)
// empty slice
ins = ins[:0]
chunk++
}
}
if len(ins) > 0 {
go cb(&ins, chunk)
}
return nil
}