-
Notifications
You must be signed in to change notification settings - Fork 9
/
encode.go
62 lines (50 loc) · 1.27 KB
/
encode.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
package influxdbhelper
import (
"errors"
"fmt"
"reflect"
"time"
)
func encode(d interface{}, timeField *usingValue) (t time.Time, tags map[string]string, fields map[string]interface{}, measurement string, err error) {
tags = make(map[string]string)
fields = make(map[string]interface{})
dValue := reflect.ValueOf(d)
if dValue.Kind() == reflect.Ptr {
dValue = reflect.Indirect(dValue)
}
if dValue.Kind() != reflect.Struct {
err = errors.New("data must be a struct")
return
}
if timeField == nil {
timeField = &usingValue{"time", false}
}
for i := 0; i < dValue.NumField(); i++ {
f := dValue.Field(i)
structFieldName := dValue.Type().Field(i).Name
if structFieldName == "InfluxMeasurement" {
measurement = f.String()
continue
}
fieldTag := dValue.Type().Field(i).Tag.Get("influx")
fieldData := getInfluxFieldTagData(structFieldName, fieldTag)
if fieldData.fieldName == "-" {
continue
}
if fieldData.fieldName == timeField.value {
// TODO error checking
t = f.Interface().(time.Time)
continue
}
if fieldData.isTag {
tags[fieldData.fieldName] = fmt.Sprintf("%v", f)
}
if fieldData.isField {
fields[fieldData.fieldName] = f.Interface()
}
}
if measurement == "" {
measurement = dValue.Type().Name()
}
return
}