I’m trying to read a JSON-encoded byte from a server, which will be indented, but of an unpredictable length, and no obvious termination byte. I would like to read the entire server response into a byte. The server will close the connection. Is it possible to do this using net?
I’m trying to read a JSON-encoded byte from a server, which will be indented,
Share
As a supplement to @minikomi ‘s answer, I would like to add that, if you are sure that the bytes returned from the server are JSON encoded, there’s a nice package
encoding/jsonfor this.http://golang.org/pkg/encoding/json/
If you are using a decoder to decode directly from a connection, sometimes the error won’t be returned. You might want to use
fmt.Printf("%v\n", whateverDecodedFromTheConnection)to see what the decoder gets for your struct when the connection is closed.For example, in my case, where the
encoding/gobdecoder is used to decode a message from a tcp connection into a struct defined as:When the connection is closed,
decoder.Decode(&buffer)returns{0}. This might not be a common situation, but something needed to be watched out.