The Commando package aims to provide easy marshalling and unmarshalling of CSV in Go. It’s a fork of gocarina/gocsv, with a simplified API.
go get -u github.com/evenco/commando
Consider the following CSV file
client_id,client_name,client_age1,Jose,422,Daniel,263,Vincent,32package main
import (
"fmt""os""github.com/evenco/commando"
)
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{}
// Create an Unmarshaller which deserializes into *Client{}unmarshaller, err:=commando.NewUnmarshaller(&Client{}, csv.NewReader(clientsFile))
iferr!=nil {
panic(err)
}
// Read everything, accumulating in clientserr=commando.ReadAllCallback(um, func(recordinterface{}) error {
clients=append(clients, record.(*Client))
returnnil
})
iferr!=nil {
panic(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"})
// Initialize Marshaller for *Client{} structsmarshaller, err:=commando.NewMarshaller(&Client{}, csv.NewWriter(clientsFile))
iferr!=nil {
panic(err)
}
for_, client:=rangeclients {
iferr:=marshaller.Write(client); err!=nil {
panic(err)
}
}
}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"`
}