Documentation ¶
Overview ¶
Package csvstruct allows scanning of string slice obtained from a csv.Reader.Read call into a struct type.
It supports scanning values to string, integer, float, boolean struct fields, and fields with the types implementing encoding.TextUnmarshaler or Value interfaces.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Scanner ¶ added in v0.2.0
Scanner is a function that scans CSV row to dst, which must be a pointer to a struct type. Scanner must be called on the same type it was created from by the NewScanner call.
Example ¶
package main import ( "encoding/csv" "fmt" "io" "log" "strings" ) type Person struct { FirstName string `csv:"first_name"` LastName string `csv:"last_name"` } const Table = `first_name,last_name,username "Rob","Pike",rob Ken,Thompson,ken "Robert","Griesemer","gri" ` func main() { r := csv.NewReader(strings.NewReader(Table)) header, err := r.Read() if err != nil { log.Fatal(err) } scan, err := NewScanner(header, &Person{}) if err != nil { log.Fatal(err) } for { record, err := r.Read() if err == io.EOF { break } if err != nil { log.Fatal(err) } var person Person if err := scan(record, &person); err != nil { log.Fatal(err) } fmt.Println(person.FirstName, person.LastName) } }
Output: Rob Pike Ken Thompson Robert Griesemer
func NewScanner ¶ added in v0.2.0
NewScanner takes CSV header and dst which must be a pointer to a struct type with struct "csv" tags mapped to header names, and returns a Scanner function for this type and field ordering. It does not modify dst.
Only exported fields are processed.
type Value
deprecated
added in
v0.2.0
Value is the interface implemented by types that can convert a string representation to themselves.
Deprecated: Please consider using encoding.TextUnmarshaler interface instead.
Example ¶
package main import ( "encoding/csv" "fmt" "io" "log" "strings" "time" ) type Event struct { Name string `csv:"name"` Time time.Time `csv:"timestamp"` // see https://pkg.go.dev/time#Time.UnmarshalText } const EventsTable = `name,timestamp login,2020-08-23T10:57:27Z logout,2020-08-23T11:07:09Z ` func main() { r := csv.NewReader(strings.NewReader(EventsTable)) header, err := r.Read() if err != nil { log.Fatal(err) } scan, err := NewScanner(header, &Event{}) if err != nil { log.Fatal(err) } for { record, err := r.Read() if err == io.EOF { break } if err != nil { log.Fatal(err) } var event Event if err := scan(record, &event); err != nil { log.Fatal(err) } fmt.Printf("%s: %s\n", event.Name, event.Time.Format("2006-01-02 15:04:05 MST")) } }
Output: login: 2020-08-23 10:57:27 UTC logout: 2020-08-23 11:07:09 UTC