ccsv

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 6, 2020 License: MIT Imports: 3 Imported by: 16

README

Concurrent CSV writer

Go Report Card GoDoc

A thread-safe way of concurrent writes to a CSV file in Go. Order of rows is NOT guaranteed.

Inspired by a blog post by Mark Needham.

Usage

import (
    "github.com/tsak/concurrent-csv-writer"
)
go get "github.com/tsak/concurrent-csv-writer"

Example

    package main
    
    import (
        "github.com/tsak/concurrent-csv-writer"
        "strconv"
    )
    
    func main() {
        // Create `sample.csv` in current directory
        csv, err := ccsv.NewCsvWriter("sample.csv")
        if err != nil {
            panic("Could not open `sample.csv` for writing")
        }
    
        // Flush pending writes and close file upon exit of main()
        defer csv.Close()
    
        count := 99
    
        done := make(chan bool)
    
        for i := count; i > 0; i-- {
            go func(i int) {
                csv.Write([]string{strconv.Itoa(i), "bottles", "of", "beer"})
                done <- true
            }(i)
        }
    
        for i := 0; i < count; i++ {
            <-done
        }
    }
Output

Notice the lack of order of entries.

98,bottles,of,beer
90,bottles,of,beer
89,bottles,of,beer
93,bottles,of,beer
97,bottles,of,beer
96,bottles,of,beer
95,bottles,of,beer
94,bottles,of,beer
99,bottles,of,beer
92,bottles,of,beer
...

License

MIT

Documentation

Overview

Package ccsv provides a "thread" safe way of writing to CSV files

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CsvWriter

type CsvWriter struct {
	// contains filtered or unexported fields
}

CsvWriter holds pointers to a Mutex, csv.Writer and the underlying CSV file

func NewCsvWriter

func NewCsvWriter(fileName string) (*CsvWriter, error)

NewCsvWriter creates a CSV file and returns a CsvWriter

func (*CsvWriter) Close

func (w *CsvWriter) Close() error

Close CSV file for writing Implicitly calls Flush() before

func (*CsvWriter) Flush

func (w *CsvWriter) Flush() error

Flush writes any pending rows

func (*CsvWriter) Write

func (w *CsvWriter) Write(row []string) error

Write a single row to a CSV file

func (*CsvWriter) WriteAll

func (w *CsvWriter) WriteAll(records [][]string) error

WriteAll writes multiple rows to a CSV file

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL