-
Notifications
You must be signed in to change notification settings - Fork 0
/
csv_writer.go
72 lines (61 loc) · 1.45 KB
/
csv_writer.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
package main
import (
"context"
"encoding/csv"
"encoding/json"
"fmt"
"os"
"strconv"
)
type CSVWriter struct {
file *os.File
writer *csv.Writer
headers []string
}
func NewCSVWriter(filename string) (*CSVWriter, error) {
file, err := os.OpenFile(filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return nil, err
}
headers := []string{"sequence_number", "node_id", "signature", "name", "close_time", "operations_json", "network"}
writer := csv.NewWriter(file)
writer.Comma = ',' // Use comma as separator
err = writer.Write(headers)
if err != nil {
return nil, err
}
return &CSVWriter{
file: file,
writer: writer,
headers: headers,
}, nil
}
func (w *CSVWriter) Write(ctx context.Context, msg Message) error {
validator := msg.Payload.(Validator)
operationsJSON, err := json.Marshal(validator.Operations)
if err != nil {
fmt.Println("Error marshaling operations to JSON:", err)
return err
}
// Prepare the row data
row := []string{
strconv.Itoa(int(validator.SequenceNumber)),
validator.NodeId,
validator.Signature,
validator.Name,
strconv.FormatInt(validator.CloseTime, 10),
string(operationsJSON), // operations as json in CSV
validator.Network,
}
// Write the row
if err := w.writer.Write(row); err != nil {
return err
}
w.writer.Flush()
return w.writer.Error()
}
func (w *CSVWriter) Close() {
w.writer.Flush()
err := w.file.Close()
fmt.Printf("error closing CSV file %v", err)
}