Skip to content

Commit

Permalink
geojson: return error for missing as well as invalid geometry
Browse files Browse the repository at this point in the history
  • Loading branch information
paulmach committed Oct 30, 2019
1 parent b9f02db commit f23a705
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
4 changes: 4 additions & 0 deletions geojson/feature.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,10 @@ func (f *Feature) UnmarshalJSON(data []byte) error {
return fmt.Errorf("geojson: not a feature: type=%s", jf.Type)
}

if jf.Geometry == nil || jf.Geometry.Coordinates == nil {
return ErrInvalidGeometry
}

*f = Feature{
ID: jf.ID,
Type: jf.Type,
Expand Down
20 changes: 20 additions & 0 deletions geojson/feature_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,26 @@ func TestUnmarshalFeature(t *testing.T) {
}
}

func TestUnmarshalFeature_missingGeometry(t *testing.T) {
t.Run("empty geometry", func(t *testing.T) {
rawJSON := `{ "type": "Feature", "geometry": {} }`

_, err := UnmarshalFeature([]byte(rawJSON))
if err != ErrInvalidGeometry {
t.Fatalf("incorrect unmarshal error: %v", err)
}
})

t.Run("missing geometry", func(t *testing.T) {
rawJSON := `{ "type": "Feature" }`

_, err := UnmarshalFeature([]byte(rawJSON))
if err != ErrInvalidGeometry {
t.Fatalf("incorrect unmarshal error: %v", err)
}
})
}

func TestUnmarshalFeature_BBox(t *testing.T) {
rawJSON := `
{ "type": "Feature",
Expand Down
8 changes: 6 additions & 2 deletions geojson/geometry.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ import (
"github.com/paulmach/orb"
)

// ErrInvalidGeometry will be returned if a the json of the geometry is invalid.
var ErrInvalidGeometry = errors.New("geojson: invalid geometry")

// A Geometry matches the structure of a GeoJSON Geometry.
type Geometry struct {
Type string `json:"type"`
Expand Down Expand Up @@ -105,6 +108,7 @@ func (g *Geometry) UnmarshalJSON(data []byte) error {
if err != nil {
return err
}

switch jg.Type {
case "Point":
p := orb.Point{}
Expand Down Expand Up @@ -133,10 +137,10 @@ func (g *Geometry) UnmarshalJSON(data []byte) error {
case "GeometryCollection":
g.Geometries = jg.Geometries
default:
return errors.New("geojson: invalid geometry")
return ErrInvalidGeometry
}

return err
return nil
}

// A Point is a helper type that will marshal to/from a GeoJSON Point geometry.
Expand Down

0 comments on commit f23a705

Please sign in to comment.