forked from cbrake/influxdbhelper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencode.go
114 lines (90 loc) · 2.4 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
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
}
func encodetime(d interface{}, timeField *usingValue, t1 time.Time) (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
}
// TODO, aaahm, well, todo
t = t1
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
}