读取直到服务器关闭连接

huangapple go评论97阅读模式
英文:

Read until the server closes the connection

问题

我试图从服务器读取一个JSON编码的字节,它将被缩进,但长度不可预测,并且没有明显的终止字节。我想将整个服务器响应读入一个字节中。服务器将关闭连接。是否可以使用net来实现这个?

英文:

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?

答案1

得分: 4

作为对@minikomi的回答的补充,我想补充一点,如果你确定从服务器返回的字节是JSON编码的,那么有一个很好的包encoding/json可以使用。

http://golang.org/pkg/encoding/json/

如果你正在使用解码器直接从连接中解码,有时错误不会被返回。你可能想使用fmt.Printf("%v\n", whateverDecodedFromTheConnection)来查看连接关闭时解码器对你的结构体得到的内容。

例如,在我的情况下,使用encoding/gob解码器将消息从TCP连接解码为一个定义为:

type MessageType struct {
    Type uint8
}

当连接关闭时,decoder.Decode(&buffer)返回{0}。这可能不是一个常见的情况,但需要注意。

英文:

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\n", 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.

答案2

得分: 2

请查看http://golang.org/pkg/net/http/上的文档。

一个http Get将返回一个Response结构体,其中会有一个类型为io.ReadCloser的Body。

然后,您可以使用ioutil.ReadAll将整个响应读取到一个字节数组中。

resp, err := http.Get("http://example.com/")
if err != nil {
    // 处理错误
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
英文:

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)

huangapple
  • 本文由 发表于 2012年11月2日 06:54:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/13186746.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定