Skip to content

Golang code generator for parsing CSVs into structs

License

Notifications You must be signed in to change notification settings

iamd3vil/csvgen

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

8 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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.

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.

About

Golang code generator for parsing CSVs into structs

Resources

License

Stars

Watchers

Forks

Packages

No packages published