dongyan4424 2015-08-05 12:18
浏览 70
已采纳

大量内容的go io.copy函数中的一个错误始终一致

This one works consistently.

    _, err = io.Copy(out, resp.Body)
    if err != nil {
        ErrLog.Fatal(err)
    }

This one gives pretty consistent off by one errors (the last byte of the downloaded content is left off, in my case a closing ] in a json response) for large-ish responses (MBs).

    if _, err := io.Copy(out, resp.Body); err != nil {
        ErrLog.Fatal(err)
    }

From the examples on the official golang blog, it looks like this should be valid syntax.

Edit: Some more details and context

This is the error I get with the 2nd version of the code (more compact error handling)

ERROR: 2015/08/05 08:09:31 pull.go:257: unexpected end of JSON input

From this code in another function

err = json.Unmarshal(dat, &all_data)
if err != nil {
    return err
}

I found the off by one issue by looking at the first 10 and last 10 characters of the file in each case. Here are the before and afters:

# Before (with error)
START:  [{"tags":[              END:    ersion":1}
START:  [{"_create              END:    "tags":[]}

# After
START:  [{"tags":[              END:    rsion":1}]
START:  [{"_create              END:    tags":[]}]

The files are 15-20 Mb json strings.

  • 写回答

1条回答 默认 最新

  • duanlachu7344 2015-08-05 21:00
    关注

    It turned out the issue was at least partially the result of a race condition.

    I was not calling .Close() on the file out before exiting the function. After adding that I have not been any more issues.

    Why exactly this was causing just the last byte of the file to get dropped sometimes is a mystery to me.

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

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值