csv

package module
v0.0.0-...-c3fcf77 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 5, 2019 License: Apache-2.0 Imports: 7 Imported by: 0

README

CSV Decoder

Simple library that parses a CSV io.Reader and maps it to a given array struct.

Limitations
  • Works only with a struct that contains string, int, uint, bool, time and float fields.

Getting started

Install
go get -u github.com/licasterian/csvdecoder
Usage

Define your struct:

type YourStruct struct{
  Field1 string
  Field2 int
  Field3 bool
  Field4 float64
  Field5 time.Time `csvDate:"2006-05-07"`
}

If you don't add 'csv' tags close to each struct's field, the lib will set the first field using the first column of csv's row, and so on. So the previous struct is the same as:

type Entry struct{
  Field1 string    `csv:"field1"`
  Field2 int       `csv:"field2"`
  Field3 bool      `csv:"field3"`
  Field4 float64   `csv:"field4"`
  Field5 time.Time `csv:"field5" csvDate:"2006-01-02"`
}
Note for time.Time fields:

It's required to specify a csvDate tag that will be used for parsing, following the rules describere here

Parse the file:
decoder := csv.NewDecoder(reader)
var entries []*Entry
err := decoder.Decode(&entries)
if err != nil {
    fmt.Printf("decoder.Decode error: %s\n", err.Error())
    return
}
for _, entry := range entries {
  fmt.Printf("%+v\n", *entry)
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Decoder

type Decoder struct {
	// contains filtered or unexported fields
}

Decoder decodes a csv specific io.Reader.

func NewDecoder

func NewDecoder(reader io.Reader) *Decoder

NewDecoder receives as an argument a io.Reader and returns a pointer to a CsvDecoder.

func (*Decoder) Decode

func (p *Decoder) Decode(v interface{}) error

Decode method accepts a pointer to a slice with it will populate and returns a error. TODO accept tag values as index also?

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL