csvstruct

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 21, 2020 License: MIT Imports: 4 Imported by: 1

README

csvstruct

Package csvstruct allows decoding of string slice obtained from a csv.Reader.Read call into a struct type.

See documentation: https://pkg.go.dev/github.com/artyom/csvstruct

Documentation

Overview

Package csvstruct allows decoding of string slice obtained from a csv.Reader.Read call into a struct type.

It supports decoding to string, integer, and float struct fields.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Decoder

type Decoder func(row []string, dst interface{}) error

Decoder is a function that decodes CSV row to dst, which must be a pointer to a struct type. Decoder must be called on the same type it was created from by the NewDecoder call.

Example
package main

import (
	"encoding/csv"
	"fmt"
	"io"
	"log"
	"strings"
)

type Person struct {
	FirstName string `csv:"first_name"`
	LastName  string `csv:"last_name"`
}

const Table = `first_name,last_name,username
"Rob","Pike",rob
Ken,Thompson,ken
"Robert","Griesemer","gri"
`

func main() {
	r := csv.NewReader(strings.NewReader(Table))
	header, err := r.Read()
	if err != nil {
		log.Fatal(err)
	}
	dec, err := NewDecoder(header, Person{})
	if err != nil {
		log.Fatal(err)
	}
	for {
		record, err := r.Read()
		if err == io.EOF {
			break
		}
		if err != nil {
			log.Fatal(err)
		}
		var person Person
		if err := dec(record, &person); err != nil {
			log.Fatal(err)
		}
		fmt.Println(person.FirstName, person.LastName)
	}
}
Output:


Rob Pike
Ken Thompson
Robert Griesemer

func NewDecoder

func NewDecoder(header []string, dst interface{}) (Decoder, error)

NewDecoder takes CSV header and dst which must be a struct type or a pointer to a struct type with struct "csv" tags mapped to header names, and returns a Decoder function for this type and field ordering. It does not modify dst.

Only exported fields are processed.

Jump to

Keyboard shortcuts

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