golang csv file to parse struct

golang csv file to parse struct

install

go get github.com/zhnxin/csvreader

usage

Simple usage

Note

By default, CSV first line of the file will be treated as header processing.

file.csv

hosname,ip
redis,172.17.0.2
mariadb,172.17.0.3

go

type Info struct{
    Hostname string
    IP string
}

//struct 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))

Note

If the csv file the first line does not contain a header, you can use WithHeader ([] string) to specify the header.
_ = csvreader.New().WithHeader([]string{"hostname","ip"}).UnMarshalFile("file.csv",&infos)

Custom parster

As enumerated types (enum), occasionally encounter such a need to implement a custom conversion process conditions. Examples are 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 works directly with native types to edit csv file, very inconvenient. Then you need to implement a custom parser.

Tip

type CsvMarshal interface {
    FromString(string) error
}
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
}

Another example TestCustom

Reproduced in: https: //my.oschina.net/u/3703365/blog/3058322

Guess you like

Origin blog.csdn.net/weixin_34101784/article/details/92400802