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
go get -u github.com/DefinitelyMod/gocsv
Consider the following CSV file
client_id,client_name,client_age1,Jose,422,Daniel,263,Vincent,32package main
import (
"fmt""gocsv""os"
)
typeClientstruct { // Our example struct, you can use "-" to ignore a fieldIdstring`csv:"client_id"`Namestring`csv:"client_name"`Agestring`csv:"client_age"`NotUsedstring`csv:"-"`
}
funcmain() {
clientsFile, err:=os.OpenFile("clients.csv", os.O_RDWR|os.O_CREATE, os.ModePerm)
iferr!=nil {
panic(err)
}
deferclientsFile.Close()
clients:= []*Client{}
iferr:=gocsv.UnmarshalFile(clientsFile, &clients); err!=nil { // Load clients from filepanic(err)
}
for_, client:=rangeclients {
fmt.Println("Hello", client.Name)
}
if_, err:=clientsFile.Seek(0, 0); err!=nil { // Go to the start of the filepanic(err)
}
clients=append(clients, &Client{Id: "12", Name: "John", Age: "21"}) // Add clientsclients=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 fileiferr!=nil {
panic(err)
}
fmt.Println(csvContent) // Display all clients as CSV string
}typeDateTimestruct {
time.Time
}
// Convert the internal date as CSV stringfunc (date*DateTime) MarshalCSV() (string, error) {
returndate.Time.Format("20060201"), nil
}
// You could also use the standard Stringer interface func (date*DateTime) String() (string) {
returndate.String() // Redundant, just for example
}
// Convert the CSV string as internal datefunc (date*DateTime) UnmarshalCSV(csvstring) (errerror) {
date.Time, err=time.Parse("20060201", csv)
returnerr
}
typeClientstruct { // Our example struct with a custom type (DateTime)Idstring`csv:"id"`Namestring`csv:"name"`EmployedDateTime`csv:"employed"`
}funcmain() {
...gocsv.SetCSVReader(func(in io.Reader) gocsv.CSVReader {
r:=csv.NewReader(in)
r.Comma='|'returnr// Allows use pipe as delimiter
}) ...gocsv.SetCSVReader(func(in io.Reader) gocsv.CSVReader {
r:=csv.NewReader(in)
r.LazyQuotes=truer.Comma='.'returnr// Allows use dot as delimiter and use quotes in CSV
})
...gocsv.SetCSVReader(func(in io.Reader) gocsv.CSVReader {
//return csv.NewReader(in)returngocsv.LazyCSVReader(in) // Allows use of quotes in CSV
})
...gocsv.UnmarshalFile(file, &clients)
...gocsv.SetCSVWriter(func(out io.Writer) *SafeCSVWriter {
writer:=csv.NewWriter(out)
writer.Comma='|'returngocsv.NewSafeCSVWriter(writer)
})
...gocsv.MarshalFile(&clients, file)
...
}