forked from vickxxx/appstore
-
Notifications
You must be signed in to change notification settings - Fork 3
/
csv.go
67 lines (58 loc) · 1.48 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
package appstore
import (
"bytes"
"encoding/csv"
"github.com/gocarina/gocsv"
"io"
"strings"
)
//UnmarshalCSV unmarshal raw data to structures
func UnmarshalCSV(in []byte, out interface{}) error {
r := NewCSVReader(bytes.NewReader(in))
return gocsv.UnmarshalCSV(r, out)
}
//UnmarshalCSVWithFilterLines unmarshal raw data to structures with filter lines
func UnmarshalCSVWithFilterLines(in []byte, out interface{}) error {
decoder, err := NewLineSkipDecoder(bytes.NewReader(in))
if err != nil {
return err
}
return gocsv.UnmarshalDecoder(decoder, out)
}
//NewCSVReader Create new CSV reader for unmarshaler
func NewCSVReader(in io.Reader) gocsv.CSVReader {
r := csv.NewReader(in)
r.LazyQuotes = true
r.Comma = '\t'
return r
}
//NewLineSkipDecoder
func NewLineSkipDecoder(r io.Reader) (gocsv.SimpleDecoder, error) {
reader := csv.NewReader(r)
reader.LazyQuotes = true
reader.Comma = '\t'
reader.FieldsPerRecord = -1
var buf bytes.Buffer
writer := csv.NewWriter(&buf)
writer.Comma = reader.Comma
for {
row, err := reader.Read()
if err != nil {
return nil, err
}
if err == io.EOF || strings.Contains(row[0], "Total_") {
break
}
err = writer.Write(row)
if err != nil {
return nil, err
}
}
reader.FieldsPerRecord = 0
writer.Flush()
rf := bytes.NewReader(buf.Bytes())
readerFiltered := csv.NewReader(rf)
readerFiltered.LazyQuotes = reader.LazyQuotes
readerFiltered.Comma = reader.Comma
return gocsv.NewSimpleDecoderFromCSVReader(readerFiltered), nil
}