csvToStruct

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Oct 27, 2024 License: MIT Imports: 6 Imported by: 0

README

csvToStruct

Overview

This package is used to generate an array of Structs, based on a CSV file.

Installing

$ go get github.com/amandavmanduca/csvToStruct@v1.0.0

Usage

See complete example under examples

1. How to create the basic Structs

// 1. Create a struct of the desired CSV columns
type CsvColumns struct {
	ID       string `csv_column:"ID"`
	Name     string `csv_column:"Name"`
	LastName string `csv_column:"Last Name"`
	Number   string `csv_column:"Lucky Number"`
}

// 2. Create a struct of the payload you want to obtain
type ExamplePayload struct {
	ID          string `json:"id" validate:"required"`
	FullName    string `json:"full_name,omitempty"`
	LuckyNumber int64  `json:"lucky_number,omitempty"`
}

// 3. Add a ToPayload method to the CsvColumns returning your ExamplePayload
func (csv CsvColumns) ToPayload() (ExamplePayload, error) {
	num, err := strconv.ParseInt(csv.Number, 0, 0)
	if err != nil {
		num = 0
	}
	return ExamplePayload{
		ID:          csv.ID,
		FullName:    fmt.Sprintf("%s %s", csv.Name, csv.LastName),
		LuckyNumber: num,
	}, nil
}

2. How to use the handler
	file, err := os.Open("example.csv")
	if err != nil {
		return
	}
	defer file.Close()
	reader := csv.NewReader(file)
	dataArray, rowsWithErrors, err := csvToStruct.CsvHandler[CsvColumns, ExamplePayload](reader)
	if err != nil {
		fmt.Println("err ", err)
	}
	fmt.Println(dataArray, rowsWithErrors)
3. Handling Response Data
  1. dataArray contains all the correct rows of the CSV with the ExamplePayload format

  2. rowsWithErrors is an array of CsvDataWithError, containing all the incorrect rows information

type CsvDataWithError struct {
	ErrorMessage string `json:"error_message"`
	Error        string `json:"error"`
	Tag          string `json:"tag"`
	Row          string `json:"row"`
} 
Testing
$ go test

Contributing

I ❤ Open source!

Follow github guides for forking a project

Follow github guides for contributing open source

Squash pull request into a single commit

License

csvToStruct is released under the MIT license.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CsvColumnsToPayload

type CsvColumnsToPayload[P any] interface {
	ToPayload() (P, error)
}

type CsvDataWithError

type CsvDataWithError struct {
	ErrorMessage string `json:"error_message"`
	Error        string `json:"error"`
	Tag          string `json:"tag"`
	Row          string `json:"row"`
}

func CsvHandler

func CsvHandler[I CsvColumnsToPayload[P], P any](reader *csv.Reader) ([]P, []CsvDataWithError, error)

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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