-
Notifications
You must be signed in to change notification settings - Fork 0
/
header.go
53 lines (46 loc) · 963 Bytes
/
header.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
package csvutil
import (
"io"
"strconv"
"github.com/pkg/errors"
)
// HeaderOption is option holder for Header.
type HeaderOption struct {
// Encoding of source file. (default utf8)
Encoding string
// Encoding for output.
OutputEncoding string
// Print index
Index bool
// Index origin number
IndexOrigin int
}
func (o HeaderOption) outputEncoding() string {
if o.OutputEncoding != "" {
return o.OutputEncoding
}
return o.Encoding
}
// Header print headers of CSV.
func Header(r io.Reader, w io.Writer, o HeaderOption) error {
cr, bom := reader(r, o.Encoding)
cw := writer(w, bom, o.outputEncoding())
cw.Comma = '\t'
defer cw.Flush()
hdr, err := cr.Read()
if err != nil {
if err == io.EOF {
return nil
}
return errors.Wrap(err, "cannot read csv header")
}
for i, h := range hdr {
if o.Index {
idx := strconv.Itoa(o.IndexOrigin + i)
cw.Write([]string{idx, h})
continue
}
cw.Write([]string{h})
}
return nil
}