Skip to content

Commit 0f92e64

Browse files
committed
feat: read .csv functions
1 parent fa6e720 commit 0f92e64

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

csv/read.go

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package csv
2+
3+
import (
4+
"encoding/csv"
5+
"github.com/DanielFillol/DataJUD_API_CALLER/models"
6+
"log"
7+
"os"
8+
)
9+
10+
// The Read function reads data from a CSV file located at the specified filePath, with the specified separator.
11+
// It returns a slice of models.ReadCsv structs containing the data from the CSV file, excluding the header.
12+
func Read(filePath string, separator rune, skipHeaderLine bool) ([]models.ReadCsv, error) {
13+
csvFile, err := os.Open(filePath)
14+
if err != nil {
15+
log.Println(err)
16+
return nil, err
17+
}
18+
defer csvFile.Close()
19+
20+
csvR := csv.NewReader(csvFile)
21+
csvR.Comma = separator
22+
23+
csvData, err := csvR.ReadAll()
24+
if err != nil {
25+
log.Println(err)
26+
return nil, err
27+
}
28+
29+
var data []models.ReadCsv
30+
for i, line := range csvData {
31+
if skipHeaderLine {
32+
// Skip the header line
33+
if i != 0 {
34+
document := line[0]
35+
data = append(data, models.ReadCsv{
36+
CNJNumber: document,
37+
})
38+
}
39+
} else {
40+
document := line[0]
41+
data = append(data, models.ReadCsv{
42+
CNJNumber: document,
43+
})
44+
}
45+
}
46+
47+
return data, nil
48+
}

0 commit comments

Comments
 (0)