1
0
Fork 0
mirror of https://github.com/imjasonh/csvstruct synced 2026-07-10 20:31:38 +00:00

handle unexported fields

This commit is contained in:
Jason Hall 2014-05-15 10:32:47 -04:00
parent 22a720a148
commit ec6e566ed1
2 changed files with 28 additions and 4 deletions

View file

@ -1,8 +1,10 @@
// TODO: struct tags
// TODO: support DecodeNext(nil) to skip a line
// TODO: NewEncoder/EncodeNext -- header will be fields in first item...
// TODO: Encode/Decode map[string]string
// TODO: Encode/Decode non-string values?
// Package csvstruct provides methods to decode a CSV file into a struct.
package csvstruct
import (
@ -13,6 +15,7 @@ import (
"reflect"
)
// Decoder reads and decodes CSV rows from an input stream.
type Decoder interface {
DecodeNext(v interface{}) error
}
@ -22,12 +25,14 @@ type decoder struct {
r csv.Reader
}
// NewDecoder returns a decoder that reads from r.
func NewDecoder(r io.Reader) Decoder {
return &decoder{
r: *csv.NewReader(r),
}
}
// DecodeNext reads the next CSV-encoded value from its input and stores it in the value pointed to by v.
func (d *decoder) DecodeNext(v interface{}) error {
rv := reflect.ValueOf(v)
if rv.Kind() != reflect.Ptr || rv.IsNil() {
@ -58,7 +63,10 @@ func (d *decoder) DecodeNext(v interface{}) error {
continue
}
strv := line[idx]
rv.FieldByName(n).SetString(strv)
vf := rv.FieldByName(n)
if vf.CanSet() {
vf.SetString(strv)
}
}
return nil
}