-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample_custom_decoder_test.go
66 lines (53 loc) · 1.42 KB
/
example_custom_decoder_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package csvdecoder_test
import (
"encoding/json"
"fmt"
"strings"
"github.com/stefantds/csvdecoder"
)
type Point struct {
X int
Y int
}
// DecodeField implements the csvdecoder.Interface type
func (p *Point) DecodeField(field string) error {
// the decode code is specific to the way the object is serialized.
// in this example the point is encoded as a JSON array with two values
data := make([]int, 2)
if err := json.NewDecoder(strings.NewReader(field)).Decode(&data); err != nil {
return fmt.Errorf("could not parse %s as JSON array: %w", field, err)
}
(*p).X = data[0]
(*p).Y = data[1]
return nil
}
func Example_custom_decoder() {
// the csv separator is a semicolon in this example
exampleData := strings.NewReader(
`[0, 0];[0, 2];[1, 2]
[-1, 2];[0, -2];[1, 0]
`)
// create a new decoder that will read from the given file
decoder, err := csvdecoder.NewWithConfig(exampleData, csvdecoder.Config{Comma: ';'})
if err != nil {
// handle error
return
}
// iterate over the rows in the file
for decoder.Next() {
var a, b, c Point
// scan the first values to the types
if err := decoder.Scan(&a, &b, &c); err != nil {
// handle error
return
}
fmt.Printf("a: %v, b: %v, c: %v\n", a, b, c)
}
// check if the loop stopped prematurely because of an error
if err = decoder.Err(); err != nil {
// handle error
return
}
// Output: a: {0 0}, b: {0 2}, c: {1 2}
// a: {-1 2}, b: {0 -2}, c: {1 0}
}