doushang2571
2018-08-16 22:08
浏览 60
已采纳

如何确定golang中连接的确切字节长度?

I have the following code:

var buf []byte
read_len, err := conn.Read(buf)
if err != nil {
    fmt.Println("Error reading:", err.Error())
}
buffer := make([]byte, read_len)
_, err = conn.Read(buffer)
if err != nil {
    fmt.Println("Error reading:", err.Error())
}

The intention was to determine read_len with the first buf, then create a second buffer which is the exact length of an incoming json request. This just results in an error

unexpected end of JSON input

When I try to unmarshal

var request Device_Type_Request_Struct
err = json.Unmarshal(buffer, &request)

I'm assuming that this error occurs because the conn.Read(buffer) is returning nothing because another buffer has already read it (not sure though). How should I go about determining the length of json request while also being able to read it into a buffer (of the exact same length)?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douwen3083 2018-08-16 22:22
    已采纳

    Read returns the number of bytes read to the buffer. Because the length of the buffer passed to the first call to conn.Read is zero, the first call to conn.Read always returns zero.

    There is no way to determine how much data a peer has sent without reading the data.

    The easy solution to this problem is to use the JSON decoder:

    d := json.NewDecoder(conn)
    var request Device_Type_Request_Struct
    if err := d.Decode(&request); err != nil {
        // handle error
    }
    

    The decoder reads and decodes JSON values from a stream.

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题