Skip to content

Commit

Permalink
add CSV writer interface
Browse files Browse the repository at this point in the history
  • Loading branch information
tochka committed Aug 19, 2020
1 parent 46266ca commit 88e7b1b
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 5 deletions.
6 changes: 3 additions & 3 deletions csv.go
Original file line number Diff line number Diff line change
Expand Up @@ -149,17 +149,17 @@ func MarshalWithoutHeaders(in interface{}, out io.Writer) (err error) {
}

// MarshalChan returns the CSV read from the channel.
func MarshalChan(c <-chan interface{}, out *SafeCSVWriter) error {
func MarshalChan(c <-chan interface{}, out CSVWriter) error {
return writeFromChan(out, c)
}

// MarshalCSV returns the CSV in writer from the interface.
func MarshalCSV(in interface{}, out *SafeCSVWriter) (err error) {
func MarshalCSV(in interface{}, out CSVWriter) (err error) {
return writeTo(out, in, false)
}

// MarshalCSVWithoutHeaders returns the CSV in writer from the interface.
func MarshalCSVWithoutHeaders(in interface{}, out *SafeCSVWriter) (err error) {
func MarshalCSVWithoutHeaders(in interface{}, out CSVWriter) (err error) {
return writeTo(out, in, true)
}

Expand Down
4 changes: 2 additions & 2 deletions encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ func newEncoder(out io.Writer) *encoder {
return &encoder{out}
}

func writeFromChan(writer *SafeCSVWriter, c <-chan interface{}) error {
func writeFromChan(writer CSVWriter, c <-chan interface{}) error {
// Get the first value. It wil determine the header structure.
firstValue, ok := <-c
if !ok {
Expand Down Expand Up @@ -63,7 +63,7 @@ func writeFromChan(writer *SafeCSVWriter, c <-chan interface{}) error {
return writer.Error()
}

func writeTo(writer *SafeCSVWriter, in interface{}, omitHeaders bool) error {
func writeTo(writer CSVWriter, in interface{}, omitHeaders bool) error {
inValue, inType := getConcreteReflectValueAndType(in) // Get the concrete type (not pointer) (Slice<?> or Array<?>)
if err := ensureInType(inType); err != nil {
return err
Expand Down
6 changes: 6 additions & 0 deletions safe_csv.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@ import (
"sync"
)

type CSVWriter interface {
Write(row []string) error
Flush()
Error() error
}

type SafeCSVWriter struct {
*csv.Writer
m sync.Mutex
Expand Down

0 comments on commit 88e7b1b

Please sign in to comment.