-
Notifications
You must be signed in to change notification settings - Fork 0
/
feeder.go
69 lines (62 loc) · 1.89 KB
/
feeder.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
package donkey
import (
"fmt"
"reflect"
"strconv"
"time"
)
// fieldFeeder this function responsible to put a string value to requested field
func fieldFeeder(field reflect.Value, value string) error {
if !field.CanSet() {
return fmt.Errorf("can not set value for field")
}
if reflect.DeepEqual(field.Kind(), reflect.ValueOf(time.Duration(0)).Kind()) {
// field is a time duration
// check if value all in number make convert it to second
intValue, err := strconv.ParseInt(value, 10, 64)
if err != nil {
// parse string value to integer -> 10s = 10000000000
duration, err := time.ParseDuration(value)
if err != nil {
return fmt.Errorf("failed to parse %s to time.Duration, err: %w", value, err)
}
intValue = duration.Nanoseconds()
}
field.SetInt(intValue)
return nil
}
if reflect.DeepEqual(field.Kind(), reflect.ValueOf(time.Now()).Kind()) {
// field is a time.Time
dateTime, err := time.Parse(DateTimeLayout, value)
if err != nil {
return fmt.Errorf("failed to parse %s with '%s' layout, err: %w", value, DateTimeLayout, err)
}
field.Set(reflect.ValueOf(dateTime))
return nil
}
switch field.Kind() {
case reflect.String:
field.SetString(value)
case reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8, reflect.Int:
intValue, err := strconv.ParseInt(value, 10, 64)
if err != nil {
return fmt.Errorf("invalid value for %s, %w", value, err)
}
field.SetInt(intValue)
case reflect.Float64, reflect.Float32:
floatValue, err := strconv.ParseFloat(value, 64)
if err != nil {
return fmt.Errorf("failed to convert %s to float, err: %w", value, err)
}
field.SetFloat(floatValue)
case reflect.Bool:
boolValue, err := strconv.ParseBool(value)
if err != nil {
return fmt.Errorf("invalid value for %s, %w", value, err)
}
field.SetBool(boolValue)
default:
return fmt.Errorf("unsupported type: %s", field.Type().String())
}
return nil
}