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
?
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/json
for 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 ", whateverDecodedFromTheConnection)
to see what the decoder gets for your struct when the connection is closed.
For example, in my case, where the encoding/gob
decoder is used to decode a message from a tcp connection into a struct defined as:
type MessageType struct {
Type uint8
}
When the connection is closed, decoder.Decode(&buffer)
returns {0}
. This might not be a common situation, but something needed to be watched out.
Please have a look at the docs at http://golang.org/pkg/net/http/
An http Get will return a Response struct, which will have a Body of type io.ReadCloser
.
You can then use ioutil.ReadAll to read the entire response to a byte array.
resp, err := http.Get("http://example.com/")
if err != nil {
// handle error
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)