csv

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Jul 6, 2023 License: MIT Imports: 4 Imported by: 1

README

CSV

Static Badge Build Go Reference codecov Release Go Report Card codebeat badge 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

import github.com/gofast-pkg/csv

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

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

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

Index

Examples

Constants

View Source
const (
	ExtensionFile = ".csv"
)

ExtensionFile for the csv file type

Variables

View Source
var (
	ErrConfDecoder            = errors.New("error to create a csv.NewDecoder")
	ErrNewCSVReader           = errors.New("error to create a csv.NewCSV, reader is invalid")
	ErrOBJDecode              = errors.New("error to decode into specific object")
	ErrNewDecoder             = errors.New("error to create a csvutil.NewDecoder")
	ErrDecoder                = errors.New("decoder is nil")
	ErrBadConfiguration       = errors.New("configuration are not full setup to decode csv")
	ErrNoCreateObjectToDecode = errors.New("no create object function to decode")
	ErrRecorder               = errors.New("function save instance was return an error")
	ErrNilReader              = errors.New("reader is nil")
)

error for the csv parser

Functions

This section is empty.

Types

type CSV

type CSV interface {
	DecodeWithDecoder(d Decoder) (Warning, error)
	Decode(obj any) (Warning, error)
}

CSV interface for new csv reader

func New

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

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

Example
package main

import (
	"fmt"
	"os"

	"github.com/gofast-pkg/csv"
)

const testFilePath = "testdata/testfile.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(testFilePath)
	if err != nil {
		panic(err)
	}
	defer reader.Close()

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

	list := []Model{}
	cfg := csv.ConfigDecoder{
		NewInstanceFunc: func() any { return &Model{} },
		SaveInstanceFunc: func(obj any, d csv.Decoder) error {
			if v, ok := d.ContextGet("type"); ok {
				obj.(*Model).Type = v
			}
			list = append(list, *(obj.(*Model)))

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

	warn, err := csvReader.DecodeWithDecoder(decoder)
	if err != nil {
		panic(err)
	}
	fmt.Println(len(warn))
	for _, v := range list {
		fmt.Println(v)
	}
}
Output:

0
{Root Dog black big}
{Toto Human blue small}

type ConfigDecoder

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

ConfigDecoder is the struct that contains the configuration to create a new decoder.

type Decoder

type Decoder interface {
	ContextSet(key, value string)
	ContextGet(key string) (value string, 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 configuration passed as parameter. If the configuration is not valid, the function returns an error of type ErrConfDecoder.

type Warning

type Warning map[string][]string

Warning collect relevants informations about the process on the csv file

func NewWarning

func NewWarning() Warning

NewWarning return a new warning For read a warning it's possible to iterate over it like a map

Example
package main

import (
	"fmt"

	"github.com/gofast-pkg/csv"
)

func main() {
	w := csv.NewWarning()
	w["key"] = []string{"value1", "value2"}
	for key, values := range w {
		for _, value := range values {
			fmt.Println(key, value)
		}
	}
}
Output:

key value1
key value2

func (*Warning) Wrap

func (w *Warning) Wrap(warn Warning)

Wrap relevants informations from the warn to the warning

Jump to

Keyboard shortcuts

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