Documentation
¶
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type CustomDecoderFunc ¶
type CustomEncoderFunc ¶
type Decoder ¶
type Decoder struct {
FieldsMap map[string]int
NullText string
BoolTrueText, BoolFalseText []string
CustomDecoderMap map[string]CustomDecoderFunc
}
Example ¶
// setup types. Note "csv" field tag.
type targetType struct {
Name string `csv:"name"`
Age *int `csv:"age"`
}
fields := []string{"name", "age"}
decoder := NewDecoder(fields)
csvData := bytes.NewBufferString("John Smith,40\nJane Doe,")
var results []*targetType
// use stdlib csv reader to read line by line []string slices
reader := csv.NewReader(csvData)
for {
valueStrings, err := reader.Read()
if err != nil {
if err == io.EOF {
break
}
// unexpected error
panic(err)
}
target := new(targetType)
err = decoder.Decode(valueStrings, target)
if err != nil {
panic(err)
}
results = append(results, target)
}
fmt.Printf("Found %d results\n", len(results))
for _, result := range results {
age := "nil"
if result.Age != nil {
age = fmt.Sprintf("%d", *result.Age)
}
fmt.Printf("%s: %s\n", result.Name, age)
}
Output: Found 2 results John Smith: 40 Jane Doe: nil
func NewDecoder ¶
type Encoder ¶
type Encoder struct {
FieldsMap map[string]int
FloatFmt byte
NullText string
BoolTrueText, BoolFalseText string
// map[csv tag name]encoder func
CustomEncoderMap map[string]CustomEncoderFunc
}
Example ¶
type objectType struct {
ID int64 `csv:"id"`
Name string `csv:"name"`
Height float64 `csv:"height"`
}
obj := objectType{
ID: 123,
Name: "Test 987",
Height: 1.567,
}
encoder := NewEncoder([]string{"id", "name", "height"})
fields, err := encoder.Encode(obj)
if err != nil {
panic(err)
}
w := csv.NewWriter(os.Stdout)
err = w.Write(fields)
if err != nil {
panic(err)
}
w.Flush()
err = w.Error()
if err != nil {
panic(err)
}
Output: 123,Test 987,1.567
func NewEncoder ¶
Click to show internal directories.
Click to hide internal directories.