Skip to content

Commit dafbba9

Browse files
authored
Merge pull request #9 from phoops/feature/safe_casting_entity_attributes
Add safe casting for attribute field retrieving
2 parents 1b5308d + e370bb1 commit dafbba9

File tree

1 file changed

+18
-4
lines changed

1 file changed

+18
-4
lines changed

model/model.go

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package model
22

33
import (
44
"encoding/json"
5+
"errors"
56
"fmt"
67
"reflect"
78
"strconv"
@@ -12,6 +13,8 @@ import (
1213
geojson "github.com/paulmach/go.geojson"
1314
)
1415

16+
var ErrInvalidCastingAttributeEntity = errors.New("could not cast the attribute of the entity")
17+
1518
// Entity is a context entity, i.e. a thing in the NGSI model.
1619
type Entity struct {
1720
Id string `json:"id"`
@@ -684,7 +687,11 @@ func (a *Attribute) GetAsString() (string, error) {
684687
if a.Type != StringType && a.Type != TextType {
685688
return "", fmt.Errorf("Attribute is nor String or Text, but %s", a.Type)
686689
}
687-
return a.Value.(string), nil
690+
rawString, ok := a.Value.(string)
691+
if !ok {
692+
return "", ErrInvalidCastingAttributeEntity
693+
}
694+
return rawString, nil
688695
}
689696

690697
func (a *Attribute) GetAsInteger() (int, error) {
@@ -697,21 +704,28 @@ func (a *Attribute) GetAsInteger() (int, error) {
697704
} else {
698705
return int(fValue), nil
699706
}
700-
return int(a.Value.(float64)), nil
701707
}
702708

703709
func (a *Attribute) GetAsFloat() (float64, error) {
704710
if a.Type != FloatType && a.Type != NumberType {
705711
return 0, fmt.Errorf("Attribute is nor Float or Number, but %s", a.Type)
706712
}
707-
return a.Value.(float64), nil
713+
rawFloat, ok := a.Value.(float64)
714+
if !ok {
715+
return 0, ErrInvalidCastingAttributeEntity
716+
}
717+
return rawFloat, nil
708718
}
709719

710720
func (a *Attribute) GetAsBoolean() (bool, error) {
711721
if a.Type != BooleanType {
712722
return false, fmt.Errorf("Attribute is not Boolean, but %s", a.Type)
713723
}
714-
return a.Value.(bool), nil
724+
rawBool, ok := a.Value.(bool)
725+
if !ok {
726+
return false, ErrInvalidCastingAttributeEntity
727+
}
728+
return rawBool, nil
715729
}
716730

717731
func (a *Attribute) GetAsDateTime() (time.Time, error) {

0 commit comments

Comments
 (0)