Demo for gocsv (ticket #159)
> cat demo.csv
client_id,client_name,client_age
1,Jose,42
2,Daniel,26
3,Vincent,32
> go run ./main.go --csvFile=demo.csv
[client_name client_age client_id]%
> cat demo.csv
client_id,client_name,client_age
1,Jose,42
2,Daniel,26
3,Vincent,32
> go run ./main.go --csvFile=demo.csv
[client_name client_age client_id]%
client_id | client_name | client_age | |
---|---|---|---|
1 | Jose | 42 | |
2 | Daniel | 26 | |
3 | Vincent | 32 |
module demo | |
go 1.19 | |
require github.com/gocarina/gocsv v0.0.0-20221105105431-c8ef78125b99 |
github.com/gocarina/gocsv v0.0.0-20221105105431-c8ef78125b99 h1:qNAaZUnCulf2xIQc7rM6F3uGYr80h40rtilsVKyAHoM= | |
github.com/gocarina/gocsv v0.0.0-20221105105431-c8ef78125b99/go.mod h1:5YoVOkjYAQumqlV356Hj3xeYh4BdZuLE0/nRkf2NKkI= |
package main | |
import ( | |
"bufio" | |
"flag" | |
"fmt" | |
"log" | |
"os" | |
"github.com/gocarina/gocsv" | |
) | |
func getHeader(csvFile string) []string { | |
in, err := os.Open(csvFile) | |
if err != nil { | |
log.Fatalf("%s", err) | |
} | |
defer in.Close() | |
m, err := gocsv.CSVToMaps(bufio.NewReader(in)) | |
if err != nil { | |
log.Fatalf("%s", err) | |
} | |
header := []string{} | |
for k := range m[0] { | |
header = append(header, k) | |
} | |
return header | |
} | |
func main() { | |
csvFile := flag.String("csvFile", "csvFile", "name of the csv file (data)") | |
flag.Parse() | |
if *csvFile == "" { | |
fmt.Println("Missing --csvFile") | |
os.Exit(0) | |
} | |
header := getHeader(*csvFile) | |
fmt.Printf("%v", header) | |
} |