Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/iamd3vil/csvgen

Golang code generator for parsing CSVs into structs
https://github.com/iamd3vil/csvgen

Last synced: 9 days ago
JSON representation

Golang code generator for parsing CSVs into structs

Awesome Lists containing this project

README

        

# csvgen

Golang code generator for parsing CSVs into structs.

## Usage

```
csvgen -file models.go -dest csvgen.go
```

`csvgen` reads all the structs in the file given as input and then generates `ParseCSV` method on the structs. An array of strings in a csv line can be given as input to `ParseCSV()` and get the parsed struct.

Supported types for the fields in the struct are:

- `int32`
- `int64`
- `float32`
- `float64`
- `string`

### Custom Columns

By default, csvgen assumes that the fields start from 0 and incremented by 1 for every consecutive field.

A custom column for a field can be given by using `csv:"{column_position}"`. Columns starts with `0`, so for example 3rd column will be `csv:"2"`.

The subsequent fields will automatically increment from the given custom column.

### Example

A sample program for using the code generated by `csvgen`.

```go
type testCsv struct {
TestStr string // Column number 1
TestInt32 int32 `csv:"5"` // Column number 6
TestInt64 int64 // Column number 7
TestFloat32 float32 // Column number 8
TestFloat64 float64 `csv:"14"` // Column number 15
}

func Parse() {
f, err := os.Open("test.csv")
if err != nil {
log.Fatalln(err)
}

rdr := csv.NewReader(f)
for {
rec, err := rdr.Read()
if err != nil {
if err == io.EOF {
break
}
log.Fatalf("error reading csv: %v", err)
}
str := testCsv{}
if err := str.ParseCSV(rec); err != nil {
log.Fatalf("error parsing csv record: %v", err)
}

fmt.Println("test csv record: %#v", str)
}
}
```

After generating code with `csvgen`, there will be a `ParseCSV` method on `testCSV` struct, which parses the whole struct.