doushang2571 2018-08-16 22:08
浏览 66


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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?



  • ¥15 UltraScale 系列 Bitslip 技术支持
  • ¥15 一个线程在sleep的时候set一个信号会起作用吗
  • ¥100 需求高精度PT100设计电路和算法
  • ¥15 单片机配网,继电器开关,广播
  • ¥60 Qcustomplot绘制实时动态曲线
  • ¥20 运用matlab画x-y图
  • ¥15 用idea运行项目,运行tomcat报错:断言失败
  • ¥15 Sqlserver查询链接服务器数据问题
  • ¥15 Bibtex4Word 引用中文文献
  • ¥20 用opencv c/c++ 转换成灰度图,然后做一下直方图均衡,输出mp4文件