csvreader

package
v1.3.19 Latest Latest
Warning

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

Go to latest
Published: May 6, 2023 License: Apache-2.0, MIT Imports: 10 Imported by: 0

README

csvreader

csv reader is a simple decoder for decoding csv file to struct

README_ZH_cn.adoc

todo

  • Custom parster
  • pointer attribute

install

go get github.com/zhnxin/csvreader

usage

simple

As the default,the first line of csv file would be regared as the header.Take a look as follows.

file.csv

hosname,ip
redis,172.17.0.2
mariadb,172.17.0.3
type Info struct{
Hostname string
IP string
}

//struc slice
infos := []Info{}
_ = csvreader.New().UnMarshalFile("file.csv", &infos)
body, _ := json.Marshal(infos)
fmt.Println(string(body))

//point slice
infos := []*Info{}
_ = csvreader.New().UnMarshalFile("file.csv", &infos)
body, _ := json.Marshal(infos)
fmt.Println(string(body))

If the csv file do not contain headers,you can also set it.

_ = csvreader.New().WithHeader([]string{"hostname","ip"}).UnMarshalFile("file.csv",&infos)

custom parseter

Just like enum,we need implement our own parster. The example is shown as follows.

type NetProtocol uint32
const (
NetProtocol_TCP NetProtocol = iota
NetProtocol_UDP
NetProtocol_DCCP
NetProtocol_SCTP
)

type ServiceInfo struct{
Host string
Port string
Protocol NetProtocol
}

It's inconvenient to edit a csv file with the custome enum type. It's greate to convert top or TCP to NetProtocol_TCP automatically.Just to implement the CsvMarshal interface

type CsvMarshal interface {
    FromString(string) error
}

As the case above, the simple solution is this.

func (p *NetProtocol)FromString(protocol string) error{
switch strings.ToLower(protocol){
case "tcp":
*p = NetProtocol_TCP
case "udp":
*p = NetProtocol_UDP
case "dccp":
*p = NetProtocol_DCCP
case "sctp":
*p = NetProtocol_SCTP
default:
return fmt.Errorf("unknown protocoal:%s", protocol)
}
return nil
}

There is another exampler you can refer to TestCustom

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ToSnake

func ToSnake(s string, screaming bool) string

Types

type CsvMarshal

type CsvMarshal interface {
	FromString(string) error
}

type Decoder

type Decoder struct {
	// contains filtered or unexported fields
}

func New

func New() *Decoder

func (*Decoder) UnMarshal

func (d *Decoder) UnMarshal(reader *csv.Reader, bean interface{}) error

func (*Decoder) UnMarshalBytes

func (d *Decoder) UnMarshalBytes(body []byte, bean interface{}) error

func (*Decoder) UnMarshalFile

func (d *Decoder) UnMarshalFile(path string, bean interface{}) error

func (*Decoder) WithCheck

func (d *Decoder) WithCheck(keys []string) *Decoder

func (*Decoder) WithHeader

func (d *Decoder) WithHeader(header []string) *Decoder

Jump to

Keyboard shortcuts

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