go-socket.io icon indicating copy to clipboard operation
go-socket.io copied to clipboard

Ack data is marshalled twice

Open uri111 opened this issue 5 years ago • 2 comments

Describe the bug Ack data is marshalled twice, producing a string like the following: "{\"User\":true,\"Name\":\"foo\"}" which throws an error client side

To Reproduce marshal a struct into bytes. convert to string. Return string.

Expected behavior when sending json in an acknowledgment, it should not be remarshalled

uri111 avatar Sep 16 '20 00:09 uri111

Can you include a code sample that can duplicate this issue?

erkie avatar Sep 16 '20 07:09 erkie

Describe the bug Ack data is marshalled twice, producing a string like the following: "{\"User\":true,\"Name\":\"foo\"}" which throws an error client side

To Reproduce marshal a struct into bytes. convert to string. Return string.

Expected behavior when sending json in an acknowledgment, it should not be remarshalled

Rather than convert your struct to bytes and then string, the socket's Emit function allows you send your struct as-is. The Emit function handles serialization of your struct to json which you can automatically consume as json data on the client.

Instead of

m := Model{User: true, Name: "foo"}
marshalled, _ := json.Marshal(m)
s.Emit("ack", string(marshalled))

You should

m := Model{User: true, Name: "foo"}
s.Emit("ack", m)

and on your client

socket.on('ack', function(msg) {
   console.log(msg) // would be {"User":true,"Name":"foo"}
   console.log(msg.User) // true
   console.log(msg.Name) // foo
}

aifaniyi avatar Mar 08 '21 23:03 aifaniyi