Skip to content

LucasvMontenegro/csv-helper

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Welcome to csv-helper 👋

Convert csv files to structs.

How to use


Install the module

go get github.com/lucasvmontenegro/csv-helper.git

Import the lib

import (
	csvhelper "github.com/lucasvmontenegro/csv-helper.git"
)

Create the struct type you want to fill using the TAG to reference the csv columns

type person struct {
	Name     string `csv_column_name:"name"`
	LastName string `csv_column_name:"lastname"`
}

Instantiate the helper by passing the type as a parameter

helper := csvhelper.New[person]()

[Optional] create a .csv file in your local project

name: file.csv

content:

name,lastname
Lucas,Montenegro
Vinicius,Vieira

[Optional] Read the csv file

file, err := ioutil.ReadFile("...file.csv")
	if err != nil {
        // handle err
		fmt.Println("err reading file")
		return
	}

file = bytes.NewBuffer(file)

[Optional] Or simulates one manually in memory

file := `name,lastname
Lucas,Montenegro
Vinicius,Vieira
`

file = bytes.NewBufferString(file)

Use the helper to Read the file or the variable and fill the model with their lines

models, err := helper.
ReadAll(file).
Marshal(csvhelper.MarshalConfig{})
if err != nil {
    // handle err
    fmt.Println("err reading/marshalling all")
    return
}

About the methods

The helper exposes the following interface

type CsvHelper[T any] interface {
	ReadAll(buffer *bytes.Buffer) CsvHelper[T]
	Validate() (bool, error)
	Records() ([][]string, error)
	Error() error
	Marshal(cfg MarshalConfig) ([]T, error)
}

ReadAll

The first method to be called. It uses a reader to convert the csv buffer to a map of records.

Validate

Verifies if some error happened in the ReadAll method, or in any other that was called before. Also validates the type inserted, looking for its tags and the amount of columns compared to the fields in the given struct type.

Records

Returns the read records in map format.

Error

Returns the error if it exists.

Marshal

Returns a list of the given struct type.

csv-helper

csv-helper

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Packages

No packages published