Convert csv files to structs.
go get github.com/lucasvmontenegro/csv-helper.git
import (
csvhelper "github.com/lucasvmontenegro/csv-helper.git"
)
type person struct {
Name string `csv_column_name:"name"`
LastName string `csv_column_name:"lastname"`
}
helper := csvhelper.New[person]()
name: file.csv
content:
name,lastname
Lucas,Montenegro
Vinicius,Vieira
file, err := ioutil.ReadFile("...file.csv")
if err != nil {
// handle err
fmt.Println("err reading file")
return
}
file = bytes.NewBuffer(file)
file := `name,lastname
Lucas,Montenegro
Vinicius,Vieira
`
file = bytes.NewBufferString(file)
models, err := helper.
ReadAll(file).
Marshal(csvhelper.MarshalConfig{})
if err != nil {
// handle err
fmt.Println("err reading/marshalling all")
return
}
The helper exposes the following interface
type CsvHelper[T any] interface {
ReadAll(buffer *bytes.Buffer) CsvHelper[T]
Validate() (bool, error)
Records() ([][]string, error)
Error() error
Marshal(cfg MarshalConfig) ([]T, error)
}
The first method to be called. It uses a reader to convert the csv buffer to a map of records.
Verifies if some error happened in the ReadAll method, or in any other that was called before. Also validates the type inserted, looking for its tags and the amount of columns compared to the fields in the given struct type.
Returns the read records in map format.
Returns the error if it exists.
Returns a list of the given struct type.