I'm new-ish to Go and I'm having some trouble putting a gob on the wire. I wrote a quick test that I thought would pass, but the decode call is returning a "DecodeValue of unassignable value" error. Here's the code:
type tester struct {
Payload string
}
func newTester(payload string) *tester {
return &tester {
Payload: payload,
}
}
func TestEncodeDecodeMessage(t *testing.T) {
uri := "localhost:9090"
s := "the lunatics are in my head"
t1 := newTester(s)
go func(){
ln, err := net.Listen("tcp", uri)
assert.NoError(t, err)
conn, err := ln.Accept()
assert.NoError(t, err)
var t2 *tester
decoder := gob.NewDecoder(conn)
err = decoder.Decode(t2)
assert.NoError(t, err)
conn.Close()
assert.NotNil(t, t2)
}()
time.Sleep(time.Millisecond * 100)
conn, err := net.Dial("tcp", uri)
assert.NoError(t, err)
gob.Register(t1)
encoder := gob.NewEncoder(conn)
err = encoder.Encode(t1)
assert.NoError(t, err)
conn.Close()
time.Sleep(time.Millisecond * 100)
}
I suspect I'm missing something stupid here and appreciate any help that you're able to offer.
Had a friend take a look at this and he pointed out that gob doesn't let you assign to a nil pointer. From the gob package docs: "Nil pointers are not permitted, as they have no value." It looks like gob reflects on the fields of the struct that is passed in and attempts to assign values from the encoded stream. Changing this:
var t2 *tester
To this:
t2 := &tester{}
Makes the test pass.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With