modulepackage
0.0.0-20240520201108-78e41c74b4b1
Repository: https://github.com/gocarina/gocsv.git
Documentation: pkg.go.dev
# README
Go CSV
The GoCSV package aims to provide easy serialization and deserialization functions to use CSV in Golang
API and techniques inspired from https://godoc.org/gopkg.in/mgo.v2
Installation
go get -u github.com/gocarina/gocsv
Full example
Consider the following CSV file
client_id,client_name,client_age
1,Jose,42
2,Daniel,26
3,Vincent,32
Easy binding in Go!
package main
import (
"fmt"
"os"
"github.com/gocarina/gocsv"
)
type NotUsed struct {
Name string
}
type Client struct { // Our example struct, you can use "-" to ignore a field
Id string `csv:"client_id"`
Name string `csv:"client_name"`
Age string `csv:"client_age"`
NotUsedString string `csv:"-"`
NotUsedStruct NotUsed `csv:"-"`
}
func main() {
clientsFile, err := os.OpenFile("clients.csv", os.O_RDWR|os.O_CREATE, os.ModePerm)
if err != nil {
panic(err)
}
defer clientsFile.Close()
clients := []*Client{}
if err := gocsv.UnmarshalFile(clientsFile, &clients); err != nil { // Load clients from file
panic(err)
}
for _, client := range clients {
fmt.Println("Hello", client.Name)
}
if _, err := clientsFile.Seek(0, 0); err != nil { // Go to the start of the file
panic(err)
}
clients = append(clients, &Client{Id: "12", Name: "John", Age: "21"}) // Add clients
clients = append(clients, &Client{Id: "13", Name: "Fred"})
clients = append(clients, &Client{Id: "14", Name: "James", Age: "32"})
clients = append(clients, &Client{Id: "15", Name: "Danny"})
csvContent, err := gocsv.MarshalString(&clients) // Get all clients as CSV string
//err = gocsv.MarshalFile(&clients, clientsFile) // Use this to save the CSV back to the file
if err != nil {
panic(err)
}
fmt.Println(csvContent) // Display all clients as CSV string
}
Customizable Converters
type DateTime struct {
time.Time
}
// Convert the internal date as CSV string
func (date *DateTime) MarshalCSV() (string, error) {
return date.Time.Format("20060201"), nil
}
// You could also use the standard Stringer interface
func (date *DateTime) String() (string) {
return date.String() // Redundant, just for example
}
// Convert the CSV string as internal date
func (date *DateTime) UnmarshalCSV(csv string) (err error) {
date.Time, err = time.Parse("20060201", csv)
return err
}
type Client struct { // Our example struct with a custom type (DateTime)
Id string `csv:"id"`
Name string `csv:"name"`
Employed DateTime `csv:"employed"`
}
Customizable CSV Reader / Writer
func main() {
...
gocsv.SetCSVReader(func(in io.Reader) gocsv.CSVReader {
r := csv.NewReader(in)
r.Comma = '|'
return r // Allows use pipe as delimiter
})
...
gocsv.SetCSVReader(func(in io.Reader) gocsv.CSVReader {
r := csv.NewReader(in)
r.LazyQuotes = true
r.Comma = '.'
return r // Allows use dot as delimiter and use quotes in CSV
})
...
gocsv.SetCSVReader(func(in io.Reader) gocsv.CSVReader {
//return csv.NewReader(in)
return gocsv.LazyCSVReader(in) // Allows use of quotes in CSV
})
...
gocsv.UnmarshalFile(file, &clients)
...
gocsv.SetCSVWriter(func(out io.Writer) *gocsv.SafeCSVWriter {
writer := csv.NewWriter(out)
writer.Comma = '|'
return gocsv.NewSafeCSVWriter(writer)
})
...
gocsv.MarshalFile(&clients, file)
...
}
# Functions
CSVToChanMaps parses the CSV from the reader and send a dictionary in the chan c, using the header row as the keys.
CSVToMap creates a simple map from a CSV of 2 columns.
CSVToMaps takes a reader and returns an array of dictionaries, using the header row as the keys.
DefaultCSVReader is the default CSV reader used to parse CSV (cf.
DefaultCSVWriter is the default SafeCSVWriter used to format CSV (cf.
DefaultNameNormalizer is a nop Normalizer.
LazyCSVReader returns a lazy CSV reader, with LazyQuotes and TrimLeadingSpace.
Marshal returns the CSV in writer from the interface.
MarshalBytes returns the CSV bytes from the interface.
MarshalChan returns the CSV read from the channel.
MarshalChanWithoutHeaders returns the CSV read from the channel.
MarshalCSV returns the CSV in writer from the interface.
MarshalCSVWithoutHeaders returns the CSV in writer from the interface.
MarshalFile saves the interface as CSV in the file.
MarshalString returns the CSV string from the interface.
MarshalStringWithoutHeaders returns the CSV string from the interface.
MarshalWithoutHeaders returns the CSV in writer from the interface.
NewSimpleDecoderFromCSVReader creates a SimpleDecoder, which may be passed to the UnmarshalDecoder* family of functions, from a CSV reader.
NewUnmarshaller creates an unmarshaller from a csv.Reader and a struct.
SetCSVReader sets the CSV reader used to parse CSV.
SetCSVWriter sets the SafeCSVWriter used to format CSV.
SetHeaderNormalizer sets the normalizer used to normalize struct and header field names.
Unmarshal parses the CSV from the reader in the interface.
UnmarshalBytes parses the CSV from the bytes in the interface.
UnmarshalBytesToCallback parses the CSV from the bytes and send each value to the given func f.
UnmarshalBytesToCallbackWithError parses the CSV from the bytes and send each value to the given func f.
UnmarshalBytesToChan parses the CSV from the bytes and send each value in the chan c.
UnmarshalCSV parses the CSV from the reader in the interface.
UnmarshalCSVToMap parses a CSV of 2 columns into a map.
UnmarshalCSVWithoutHeaders parses a headerless CSV with passed in CSV reader.
UnmarshalDecoder parses the CSV from the decoder in the interface.
UnmarshalDecoderToCallback parses the CSV from the decoder and send each value to the given func f.
UnmarshalDecoderToChan parses the CSV from the decoder and send each value in the chan c.
UnmarshalFile parses the CSV from the file in the interface.
UnmarshalFileWithErrorHandler parses the CSV from the file in the interface.
UnmarshalMultipartFile parses the CSV from the multipart file in the interface.
UnmarshalString parses the CSV from the string in the interface.
UnmarshalStringToCallback parses the CSV from the string and send each value to the given func f.
UnmarshalStringToCallbackWithError parses the CSV from the string and send each value to the given func f.
UnmarshalStringToChan parses the CSV from the string and send each value in the chan c.
UnmarshalToCallback parses the CSV from the reader and send each value to the given func f.
UnmarshalToCallbackWithError parses the CSV from the reader and send each value to the given func f.
UnmarshalToChan parses the CSV from the reader and send each value in the chan c.
UnmarshalToChanWithErrorHandler parses the CSV from the reader in the interface.
UnmarshalToChanWithoutHeaders parses the CSV from the reader and send each value in the chan c.
Unmarshal parses the CSV from the reader in the interface.
UnmarshalWithoutHeaders parses the CSV from the reader in the interface.
# Variables
FailIfDoubleHeaderNames indicates whether it is considered an error when a header name is repeated in the csv header.
FailIfUnmatchedStructTags indicates whether it is considered an error when there is an unmatched struct tag.
FieldSeperator defines how to combine parent struct with child struct.
ShouldAlignDuplicateHeadersWithStructFieldOrder indicates whether we should align duplicate CSV headers per their alignment in the struct definition.
TagName defines key in the struct field's tag to scan.
TagSeparator defines seperator string for multiple csv tags in struct fields.
# Structs
NoMarshalFuncError is the custom error type to be raised in case there is no marshal function defined on type.
NoUnmarshalFuncError is the custom error type to be raised in case there is no unmarshal function defined on type.
Unmarshaller is a CSV to struct unmarshaller.
# Interfaces
Decoder .
SimpleDecoder .
TypeMarshaller is implemented by any value that has a MarshalCSV method This converter is used to convert the value to it string representation.
TypeUnmarshalCSVWithFields can be implemented on whole structs to allow for whole structures to customized internal vs one off fields.
TypeUnmarshaller is implemented by any value that has an UnmarshalCSV method This converter is used to convert a string to your value representation of that string.