Skip to content

Commit

Permalink
fix: Workaround Go Inet marshal bug (#410)
Browse files Browse the repository at this point in the history
Fix nasty bug triggered by Go bug

golang/go#35727

@shimonp21  can you please confirm this solves the bug triggered by the k8s cidr plugin.
  • Loading branch information
yevgenypats committed Nov 15, 2022
1 parent 1a59171 commit bd7718c
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 0 deletions.
6 changes: 6 additions & 0 deletions schema/cidr.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package schema

import "encoding/json"

type CIDR Inet

type CIDRTransformer interface {
Expand Down Expand Up @@ -36,3 +38,7 @@ func (dst *CIDR) Set(src interface{}) error {
func (dst CIDR) Get() interface{} {
return (Inet)(dst).Get()
}

func (dst *CIDR) UnmarshalJSON(b []byte) error {
return json.Unmarshal(b, (*Inet)(dst))
}
23 changes: 23 additions & 0 deletions schema/inet.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package schema

import (
"encoding"
"encoding/json"
"fmt"
"net"
"strings"
Expand All @@ -12,6 +13,12 @@ type InetTransformer interface {
TransformInet(*Inet) interface{}
}

// workaround this Golang bug: https://github.com/golang/go/issues/35727
type inetWrapper struct {
IPNet *net.IPNet
Status Status
}

// Inet represents both inet and cidr PostgreSQL types.
type Inet struct {
IPNet *net.IPNet
Expand Down Expand Up @@ -146,6 +153,22 @@ func maybeGetIPv4(input string, ip net.IP) net.IP {
return ip.To4()
}

// workaround this Golang bug: https://github.com/golang/go/issues/35727
func (dst *Inet) UnmarshalJSON(b []byte) error {
tmp := inetWrapper{}
if err := json.Unmarshal(b, &tmp); err != nil {
return err
}
*dst = Inet{Status: tmp.Status}
if dst.Status == Present {
if err := dst.Set(tmp.IPNet.String()); err != nil {
return err
}
}

return nil
}

func (dst Inet) Get() interface{} {
switch dst.Status {
case Present:
Expand Down
31 changes: 31 additions & 0 deletions schema/inet_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package schema

import (
"bytes"
"encoding/json"
"fmt"
"net"
"strings"
Expand Down Expand Up @@ -59,3 +61,32 @@ func TestInetSet(t *testing.T) {
}
}
}

func TestInetMarshalUnmarshal(t *testing.T) {
var r Inet
err := r.Set("10.244.0.0/24")
if err != nil {
t.Fatal(err)
}
b, err := json.Marshal(r)
if err != nil {
t.Fatal(err)
}
var r2 Inet
err = json.Unmarshal(b, &r2)
if err != nil {
t.Fatal(err)
}
if !r.Equal(&r2) {
t.Errorf("%v != %v", r, r2)
}

// workaround this Golang bug: https://github.com/golang/go/issues/35727
if !bytes.Equal(r.IPNet.Mask, r2.IPNet.Mask) {
t.Errorf("%v != %v", r.IPNet.Mask, r2.IPNet.Mask)
}
//nolint:all
if !bytes.Equal(r.IPNet.IP, r2.IPNet.IP) {
t.Errorf("%v != %v", r.IPNet.IP, r2.IPNet.IP)
}
}

0 comments on commit bd7718c

Please sign in to comment.