-
Notifications
You must be signed in to change notification settings - Fork 0
/
encoder.go
executable file
·80 lines (72 loc) · 1.5 KB
/
encoder.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package csvdata
import (
"encoding/csv"
"errors"
"io"
"reflect"
"strconv"
"strings"
)
//ErrNoField no field error
var ErrNoField error = errors.New("csvdata: no filed for encoder")
//Encoder Encoder description
type Encoder struct {
*csv.Writer
}
//NewEncoder create encoder for csv writer
func NewEncoder(w io.Writer) *Encoder {
enc := &Encoder{csv.NewWriter(w)}
return enc
}
//Encode encode csv item to csv writer
func (enc *Encoder) Encode(item interface{}) error {
rv := reflect.ValueOf(item)
n := rv.NumField()
ss := make([]string, n)
pos := 0
for i := 0; i < n; i++ {
rfield := rv.Field(i)
rftk := rfield.Type().Kind()
switch rftk {
case reflect.Float64, reflect.Float32:
{
fv := rfield.Float()
sv := strconv.FormatFloat(fv, 'E', -1, 64)
ss[pos] = sv
pos++
}
case reflect.String:
{
sv := rfield.String()
sv = strings.TrimSpace(sv)
ss[pos] = sv
pos++
}
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
{
fv := rfield.Int()
sv := strconv.FormatInt(fv, 10)
ss[pos] = sv
pos++
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
{
fv := rfield.Uint()
sv := strconv.FormatUint(fv, 10)
ss[pos] = sv
pos++
}
default:
{
// do nothing
//fmt.Println(rftk)
}
}
}
if pos > 0 {
err := enc.Write(ss)
enc.Flush()
return err
}
return ErrNoField
}