Read csv file from go using tags
go get github.com/artonge/go-csv-tag
The csv file:
name, ID, number
name1, 1, 1.2
name2, 2, 2.3
name3, 3, 3.4
Your go code:
type Demo struct { // A structure with tags
Name string `csv:"name"`
ID int `csv:"ID"`
Num float64 `csv:"number"`
}
tab := []Demo{} // Create the slice where to put the file content
err := csvtag.Load(csvtag.Config{ // Load your csv with the appropriate configuration
Path: "file.csv", // Path of the csv file
Dest: &tab, // A pointer to the create slice
Separator: ';', // Optional - if your csv use something else than ',' to separate values
Header: []string{"name", "ID", "number"}, // Optional - if your csv does not contains a header
})You go code:
type Demo struct { // A structure with tags
Name string `csv:"name"`
ID int `csv:"ID"`
Num float64 `csv:"number"`
}
tab := []Demo{ // Create the slice where to put the file content
Demo{
Name: "some name",
ID: 1,
Num: 42.5,
},
}
err := csvtag.DumpToFile(tab, "csv_file_name.csv")You can also dump the data into an io.Writer with
err := csvtag.Dump(tab, yourIOWriter)The csv file written:
name,ID,number
some name,1,42.5
- Update
Loadto also match csv fields with property name (case sensitive and lowercases)