company facts simple read out of xls works
This commit is contained in:
@@ -3,16 +3,37 @@ package set
|
||||
import (
|
||||
"errors"
|
||||
"reflect"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func Field(dst interface{}, fieldName string, value interface{}) error {
|
||||
var (
|
||||
ErrTypeConvert = errors.New("cannot convert input")
|
||||
)
|
||||
|
||||
func Field(dst interface{}, fieldName string, value string) error {
|
||||
|
||||
valDst := reflect.ValueOf(dst).Elem()
|
||||
dstField := valDst.FieldByName(fieldName)
|
||||
|
||||
val := reflect.ValueOf(value)
|
||||
if dstField.Kind() != val.Kind() {
|
||||
return errors.New("value-Type does not match to field")
|
||||
// try to convert
|
||||
switch dstField.Kind() {
|
||||
case reflect.Int:
|
||||
d, err := strconv.Atoi(value)
|
||||
if err != nil {
|
||||
return ErrTypeConvert
|
||||
}
|
||||
val = reflect.ValueOf(d)
|
||||
case reflect.Float64:
|
||||
f, err := strconv.ParseFloat(value, 64)
|
||||
if err != nil {
|
||||
return ErrTypeConvert
|
||||
}
|
||||
val = reflect.ValueOf(f)
|
||||
default:
|
||||
return ErrTypeConvert
|
||||
}
|
||||
}
|
||||
|
||||
dstField.Set(val)
|
||||
|
||||
@@ -6,6 +6,7 @@ func TestField(t *testing.T) {
|
||||
input := struct {
|
||||
MyString string
|
||||
MyInt int
|
||||
MyFloat float64
|
||||
MyBool bool
|
||||
}{}
|
||||
value := "abc"
|
||||
@@ -13,15 +14,21 @@ func TestField(t *testing.T) {
|
||||
if input.MyString != value {
|
||||
t.Errorf("got: %s; want: %s", input.MyString, value)
|
||||
}
|
||||
vInt := 2
|
||||
Field(&input, "MyInt", vInt)
|
||||
if input.MyInt != vInt {
|
||||
t.Errorf("MyInt: %d, want: %d", input.MyInt, vInt)
|
||||
err := Field(&input, "MyFloat", "3.14")
|
||||
if err != nil {
|
||||
t.Error("expect no error, when can be converted")
|
||||
}
|
||||
err := Field(&input, "MyInt", "vInt")
|
||||
if input.MyFloat != 3.14 {
|
||||
t.Errorf("MyFloat is not 3.14. Got: %#v", input.MyFloat)
|
||||
}
|
||||
err = Field(&input, "MyInt", "vInt")
|
||||
if err == nil {
|
||||
t.Error("expect error, when wrong value-Type")
|
||||
}
|
||||
err = Field(&input, "MyInt", "3")
|
||||
if err != nil {
|
||||
t.Error("expect no error, when can be converted")
|
||||
}
|
||||
err = Field(&input, "NoField", "jjj")
|
||||
if err == nil {
|
||||
t.Error("expect error, when field not exists")
|
||||
|
||||
Reference in New Issue
Block a user