golang 解析csv文件到struct

golang 解析csv文件到struct

install

go get github.com/zhnxin/csvreadergit

usage

簡單用法

Notegithub

默認狀況下,csv 文件的首行會被看成header處理。

file.csvgolang

hosname,ip
redis,172.17.0.2
mariadb,172.17.0.3

goredis

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

Notejson

若是 csv 文件首行不包含header,能夠使用 WithHeader([]string) 來指定header。
_ = csvreader.New().WithHeader([]string{"hostname","ip"}).UnMarshalFile("file.csv",&infos)

自定義parster

就像枚舉類型(enum),偶爾會遇到這種須要實現自定義轉換過程的狀況。例子以下tcp

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

type ServiceInfo struct{
    Host string
    Port string
    Protocol NetProtocol
}

直接使用原始的類型來編輯csv文件,十分不便。這時就須要實現自定義parser。ui

Tipspa

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
}

另一個例子 TestCustomcode

相關文章
相關標籤/搜索