douzuanze0486 2018-03-01 17:06
浏览 50
已采纳

退出Go中的空流http json goroutine的解码

I have a long-lived streaming json response that I'm processing in a goroutine as follows. I'm using a quit channel to exit the goroutine periodically. Quitting works great while data's flowing (on the next loop), however, while nothing's being streamed, decoder.Decode holds up execution waiting for the next line of json, which holds up the quit. Suggestions on how to quit gracefully?

quit := make(chan bool)

decoder := json.NewDecoder(response.Body) // response.Body is streaming json

go func() {
  for {
    select {

    case <-quit:
      return

    default:
      decoder.Decode(&myStruct) // this blocks when there's no data 

      process myStruct...

    }
  }
}()

... quit <- true // stop execution as needed
  • 写回答

1条回答 默认 最新

  • dsxz84851 2018-03-01 18:06
    关注

    You can't interrupt a blocking read. If you want to interrupt reading of the response body, you need to cancel the http request. This will close the connection, causing the blocked io.Reader to return io.EOF.

    Create a "cancellable" request using the Request.WithContext method, and provide it with a cancellation context.

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

报告相同问题?

悬赏问题

  • ¥15 关于Lammps建模的描述
  • ¥15 #lingo#请问一下为什么会出现以下情况,是因为l第一个值是0的缘故吗?
  • ¥15 设计格雷码同步八进制计数器
  • ¥100 改写matlab程序(关键词-系统对)
  • ¥15 函数信号发生器仿真电路
  • ¥15 Qt的pixmap和image图片加载都导致程序崩溃怎么办
  • ¥15 Kali木马生成问题求解
  • ¥30 求一下解题思路,完全不懂
  • ¥15 C51单片机串口控制JQ6500语音模块
  • ¥30 想给yolo5模型加一个图片识别界面,但是图片还没有检测出来就闪退了