Fix Inet.Set to handle nil net.IP correctly

When nil IP is returned from net.ParseIP, it is accepted into Inet type,
but not properly marked as being Null. That introduces issues later on
when calling for example EncodeBinary, since it does not assume this can
happen.

This commit resolves that by properly detecting zero-length net.IP and
setting status to Null if that is the case.
This commit is contained in:
Tomas Volf 2020-10-13 15:26:09 +02:00
parent 2bc8c67e4a
commit e92478ec70
No known key found for this signature in database
GPG Key ID: CF48DBBD02255E33
2 changed files with 8 additions and 3 deletions

View File

@ -38,9 +38,13 @@ func (dst *Inet) Set(src interface{}) error {
case net.IPNet:
*dst = Inet{IPNet: &value, Status: Present}
case net.IP:
if len(value) == 0 {
*dst = Inet{Status: Null}
} else {
bitCount := len(value) * 8
mask := net.CIDRMask(bitCount, bitCount)
*dst = Inet{IPNet: &net.IPNet{Mask: mask, IP: value}, Status: Present}
}
case string:
_, ipnet, err := net.ParseCIDR(value)
if err != nil {

View File

@ -35,6 +35,7 @@ func TestInetSet(t *testing.T) {
{source: mustParseCIDR(t, "127.0.0.1/32"), result: pgtype.Inet{IPNet: mustParseCIDR(t, "127.0.0.1/32"), Status: pgtype.Present}},
{source: mustParseCIDR(t, "127.0.0.1/32").IP, result: pgtype.Inet{IPNet: mustParseCIDR(t, "127.0.0.1/32"), Status: pgtype.Present}},
{source: "127.0.0.1/32", result: pgtype.Inet{IPNet: mustParseCIDR(t, "127.0.0.1/32"), Status: pgtype.Present}},
{source: net.ParseIP(""), result: pgtype.Inet{Status: pgtype.Null}},
}
for i, tt := range successfulTests {