-
Notifications
You must be signed in to change notification settings - Fork 1
/
csvoperator.go
110 lines (82 loc) · 2.38 KB
/
csvoperator.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package k6utils
import (
"encoding/csv"
"fmt"
"io"
"math/rand"
"os"
)
func (k6utils *K6Utils) TakeRandomRow() (map[string]string, error) {
if k6utils.csvRecords == nil || len(k6utils.csvRecords) == 0 {
return nil, fmt.Errorf("%s", "List of CSV records not loaded, call Load method first")
}
randomIndex := rand.Intn(len(k6utils.csvRecords))
record := k6utils.csvRecords[randomIndex]
dict := map[string]string{}
for i := range record {
dict[k6utils.header[i]] = record[i]
}
return dict, nil
}
func (k6utils *K6Utils) PollRandomRow() (map[string]string, error) {
if k6utils.csvRecords == nil || len(k6utils.csvRecords) == 0 {
return nil, fmt.Errorf("%s", "List of CSV records not loaded, call Load method first")
}
randomIndex := rand.Intn(len(k6utils.csvRecords))
record := k6utils.csvRecords[randomIndex]
k6utils.csvRecords = removeElementByIndex(k6utils.csvRecords, randomIndex)
dict := map[string]string{}
for i := range record {
dict[k6utils.header[i]] = record[i]
}
return dict, nil
}
func removeElementByIndex[T any](slice []T, index int) []T {
return append(slice[:index], slice[index+1:]...)
}
func (k6utils *K6Utils) TakeRowByIndex(index int) (map[string]string, error) {
if k6utils.csvRecords == nil || len(k6utils.csvRecords) == 0 {
return nil, fmt.Errorf("%s", "List of CSV records not loaded, call Load method first")
}
if index < 0 || index > len(k6utils.csvRecords) {
return nil, fmt.Errorf("Invalid index %d. CSV feed has %d rows", index, len(k6utils.csvRecords))
}
record := k6utils.csvRecords[index]
dict := map[string]string{}
for i := range record {
dict[k6utils.header[i]] = record[i]
}
return dict, nil
}
func (k6utils *K6Utils) Load(filePath string, separator []byte) (interface{}, error) {
if len(separator) == 0 {
return nil, fmt.Errorf("%s", "Separator not valid")
}
file, err := os.Open(filePath)
if err != nil {
return nil, fmt.Errorf("%s", err)
}
reader := csv.NewReader(file)
header, err := reader.Read()
k6utils.header = header
if err != nil {
return nil, fmt.Errorf("%s", err)
}
k6utils.csvRecords = [][]string{}
for {
record, err := reader.Read()
if err == io.EOF {
break
}
if err != nil {
return nil, fmt.Errorf("%s", err)
}
// skip empty lines
if len(record) == 0 {
continue
}
k6utils.csvRecords = append(k6utils.csvRecords, record)
}
file.Close()
return k6utils.csvRecords, nil
}