csv

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Mar 30, 2026 License: MIT Imports: 5 Imported by: 2

README

CSV

Static Badge Build Go Reference codecov Release Go Report Card FOSSA Status License

Package CSV is a package to parse a full csv reader inside a slice structure. Allow to configure a decoder to transform directly csv entries into csv structure.

I had this specific need because i would to parse many csv files for differents type structure.

This package allow to configure dynamicly the structure builder to parse each entries files.

If you need an easy parser to decode csv file basicly, prefer use the csvutil package

Install

$> go get github.com/gofast-pkg/csv@latest

Usage

Examples are provided on the go doc reference

Contributing

 ❕  Use issues for everything

Read more informations with the CONTRIBUTING_GUIDE

For all changes, please update the CHANGELOG.txt file by replacing the existant content.

Thank you  🙏  👍 

Made with contrib.rocks.

Licence

MIT

Documentation

Overview

Package csv allow to parse csv file line by line and transform each row in a data model. Expose a DecoderConfig to define custom behavior for each row.

Index

Examples

Constants

View Source
const (
	ExtensionFile = ".csv"
)

ExtensionFile for the csv file type.

Variables

View Source
var (
	ErrNilOBJ              = errors.New("obj is nil")
	ErrNilReader           = errors.New("io.reader is nil")
	ErrNilDecoder          = errors.New("decoder is nil")
	ErrOBJDecode           = errors.New("fails to decode into specific object")
	ErrToCreateNewInstance = errors.New("fails to create new obj instance")
	ErrToSaveNewInstance   = errors.New("fails to save new obj instance")
	ErrToCheckWarning      = errors.New("fails to check the unused fields")
)

Errors supported by the csv operations.

View Source
var (
	ErrInvalidConfigDecoder = errors.New("ConfigDecoder is invalid")
)

Errors supported by the decoder.

Functions

This section is empty.

Types

type CSV

type CSV interface {
	// DecodeWithDecoder parse the CSV file with a custom decoder.
	// Decoder allows you to apply specific behavior to each line of the csv.
	// (see: Decoder type and NewDecoder func)
	DecodeWithDecoder(d Decoder) error
	// Decode the csv file loaded into the obj instance.
	// Each call to Decode read and process one line of the CSV file.
	// Decode return a Warning object iterable like a map to check fields
	// which are not used.
	Decode(obj any) (Warning, error)
}

CSV interface creates a new interface ready to parse a csv file.

func New

func New(r io.Reader, separator rune) (CSV, error)

New create a new CSV reader from an io.Reader. Separator is the separator used in the CSV file.

Example
package main

import (
	"fmt"
	"os"

	"github.com/gofast-pkg/csv"
	"github.com/stretchr/testify/assert"
)

const withValidCSVFile = "testdata/valid.csv"

func main() {
	type Model struct {
		Name      string `csv:"name"`
		Type      string `csv:"type"`
		MainColor string `csv:"main_color"`
		Size      string `csv:"size"`
	}

	reader, err := os.Open(withValidCSVFile)
	if err != nil {
		panic(err)
	}
	defer func() {
		if err = reader.Close(); err != nil {
			panic(err)
		}
	}()

	csvReader, err := csv.New(reader, ';')
	if err != nil {
		panic(err)
	}

	exampleContextKey := "example-key"

	list := []Model{}
	cfg := csv.ConfigDecoder{
		NewInstanceFunc: func(_ csv.Decoder) (any, error) { return &Model{}, nil },
		SaveInstanceFunc: func(dec csv.Decoder, obj any) error {
			// manipulate data in the decoder context
			v, ok := dec.ContextGet(exampleContextKey)
			if !ok {
				return assert.AnError
			}
			if count, ok := v.(*int); ok {
				(*count)++
				dec.ContextSet(exampleContextKey, count)
			}

			if v, ok := obj.(*Model); ok {
				list = append(list, *v)

				return nil
			}

			return assert.AnError
		},
		WarningInstanceFunc: func(_ csv.Decoder, warn csv.Warning) error {
			for k, v := range warn {
				fmt.Printf("warning with key %s value %s\n", k, v)
			}

			return nil
		},
	}
	decoder, err := csv.NewDecoder(cfg)
	if err != nil {
		panic(err)
	}

	// records some datas in the decoder context
	count := int(0)
	decoder.ContextSet(exampleContextKey, &count)

	err = csvReader.DecodeWithDecoder(decoder)
	if err != nil {
		panic(err)
	}

	for _, v := range list {
		fmt.Println(v)
	}

	fmt.Println(count)

}
Output:
{Root Dog black big}
{Toto Human blue small}
2

type ConfigDecoder

type ConfigDecoder struct {
	NewInstanceFunc     func(Decoder) (any, error)
	SaveInstanceFunc    func(Decoder, any) error
	WarningInstanceFunc func(Decoder, Warning) error
}

ConfigDecoder is the configuration to create a new decoder.

type Decoder

type Decoder interface {
	ContextSet(key string, value any)
	ContextGet(key string) (value any, found bool)
	// contains filtered or unexported methods
}

Decoder is the interface that wraps the basic methods to decode a csv file with a specific process for each line of the file.

func NewDecoder

func NewDecoder(conf ConfigDecoder) (Decoder, error)

NewDecoder returns a new decoder with the specific configuration. If the configuration is not valid, the function returns an error of type ErrInvalidConfigDecoder.

type Warning

type Warning map[string]string

Warning collect relevants informations about the process on the csv file.

func NewWarning

func NewWarning() Warning

NewWarning create a warning instance. For read a warning it's possible to iterate over it like a map.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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