Skip to content

Commit bd22e11

Browse files
committed
fix(doc): add an example)
1 parent 6dec2e1 commit bd22e11

1 file changed

Lines changed: 39 additions & 1 deletion

File tree

README.md

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,4 +30,42 @@ It's tedious because the `csv:"Phone"` tag doesn´t match the header
3030
The goal of this library is to make processing of CSV files with "variable"
3131
headers simpler.
3232

33-
## U
33+
## Usage
34+
In order to use this library, one needs to have a `csv.Reader` already.
35+
36+
The next requirement is to have a list of the header mappings, as a map.
37+
These go from the file to the `struct`.
38+
In our example above, the header replacemenent would be:
39+
```go
40+
headerReplacements := map[string]string{
41+
"Nom": "NAME",
42+
"Numéro": "PHONE NUMBER",
43+
}
44+
```
45+
Finally, we can build a replacer with:
46+
```go
47+
replacer := csvheaders.NewReplacer(csvReader, headerReplacements)
48+
```
49+
This `replacer` can be fed to csv parsing libraries such as `gocsv`
50+
or `goflat`:
51+
52+
```go
53+
file, err := os.Open("phone_directory.csv")
54+
if err != nil {
55+
...
56+
}
57+
defer file.Close()
58+
59+
csvReader := csvheaders.NewReplacer(
60+
csv.NewReader(file),
61+
map[string]string{
62+
"Nom": "NAME",
63+
"Numéro": "PHONE NUMBER",
64+
})
65+
66+
var rows []*Person
67+
err := gocsv.UnmarshalCSV(csvReader, &rows)
68+
if err != nil {
69+
...
70+
}
71+
```

0 commit comments

Comments
 (0)