paulmach / orb

Types and utilities for working with 2d geometry in Golang
MIT License
886 stars 103 forks source link

JSON Unmarshalling panics if the geojson object is null #144

Closed GneyHabub closed 7 months ago

GneyHabub commented 7 months ago

I am trying to unmarshall a json string into a struct that has a field of type geojson.Feature. If this field is present in the json object, but is null, then the orb package panics when trying to unmarshall it. Here is the error message:

2024/01/16 11:15:35 http: panic serving [::1]:37010: runtime error: invalid memory address or nil pointer dereference
goroutine 76 [running]:
net/http.(*conn).serve.func1()
    /usr/local/go/src/net/http/server.go:1868 +0xb9
panic({0xab4d60?, 0x10d7710?})
    /usr/local/go/src/runtime/panic.go:920 +0x270
github.com/paulmach/orb/geojson.featureUnmarshalFinish(0xc00017e60b?, 0xaebb60?)
    /home/unmanned/go/pkg/mod/github.com/paulmach/orb@v0.11.0/geojson/feature.go:103 +0x1a
github.com/paulmach/orb/geojson.(*Feature).UnmarshalJSON(0xb2baa0?, {0xc00017e60b, 0x4, 0x1f5})
    /home/unmanned/go/pkg/mod/github.com/paulmach/orb@v0.11.0/geojson/feature.go:88 +0xa5
encoding/json.(*decodeState).literalStore(0xc0004fa750, {0xc00017e60b, 0x4, 0x1f5}, {0xb2baa0?, 0xc0003de050?, 0x0?}, 0x0)
    /usr/local/go/src/encoding/json/decode.go:852 +0x21a5
encoding/json.(*decodeState).value(0xc0004fa750, {0xb2baa0?, 0xc0003de050?, 0x7?})
    /usr/local/go/src/encoding/json/decode.go:388 +0x115
encoding/json.(*decodeState).object(0xc0004fa750, {0xa67f20?, 0xc0003de050?, 0xb94b56?})
    /usr/local/go/src/encoding/json/decode.go:755 +0xd08
encoding/json.(*decodeState).value(0xc0004fa750, {0xa67f20?, 0xc0003de050?, 0x7fc90c459f18?})
    /usr/local/go/src/encoding/json/decode.go:374 +0x3e
encoding/json.(*decodeState).unmarshal(0xc0004fa750, {0xa67f20?, 0xc0003de050?})
    /usr/local/go/src/encoding/json/decode.go:181 +0x133
encoding/json.Unmarshal({0xc00017e600, 0x10, 0x200}, {0xa67f20, 0xc0003de050})
    /usr/local/go/src/encoding/json/decode.go:108 +0x111

The struct I was trying to unmarshall the json into is the following:

type SetSiteGeocageRequest struct {
    Geocage geojson.Feature `json:"geocage"`
}

And the json string looked like this:

{
    "geocage": null
}
paulmach commented 7 months ago

The the JSON value can be null, the struct should have a pointer to the geojson.Feature

type SetSiteGeocageRequest struct {
    Geocage *geojson.Feature `json:"geocage"`
}

I can update to support this as I'm dealing with a similar problem at work right now and it's super annoying, but in the mean-time you can do the above.