-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcsv_writer.go
57 lines (50 loc) · 1.25 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
// Package ccsv provides a "thread" safe way of writing to CSV files
package ccsv
import (
"encoding/csv"
"os"
"sync"
)
// CsvWriter holds pointers to a Mutex, csv.Writer and the underlying CSV file
type CsvWriter struct {
mutex *sync.Mutex
csvWriter *csv.Writer
file *os.File
}
// NewCsvWriter creates a CSV file and returns a CsvWriter
func NewCsvWriter(fileName string) (*CsvWriter, error) {
csvFile, err := os.Create(fileName)
if err != nil {
return nil, err
}
w := csv.NewWriter(csvFile)
return &CsvWriter{csvWriter: w, mutex: &sync.Mutex{}, file: csvFile}, nil
}
// Write a single row to a CSV file
func (w *CsvWriter) Write(row []string) error {
w.mutex.Lock()
defer w.mutex.Unlock()
return w.csvWriter.Write(row)
}
// WriteAll writes multiple rows to a CSV file
func (w *CsvWriter) WriteAll(records [][]string) error {
w.mutex.Lock()
defer w.mutex.Unlock()
return w.csvWriter.WriteAll(records)
}
// Flush writes any pending rows
func (w *CsvWriter) Flush() error {
w.mutex.Lock()
defer w.mutex.Unlock()
w.csvWriter.Flush()
return w.csvWriter.Error()
}
// Close CSV file for writing
// Implicitly calls Flush() before
func (w *CsvWriter) Close() error {
err := w.Flush()
if err != nil {
return err
}
return w.file.Close()
}