简体   繁体   English

退出空流式传输http json goroutine In Go的解码

[英]Quit decode of empty streaming http json goroutine In Go

I have a long-lived streaming json response that I'm processing in a goroutine as follows. 我有一个长期流媒体json响应,我正在goroutine处理如下。 I'm using a quit channel to exit the goroutine periodically. 我正在使用退出通道定期退出goroutine。 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. 当数据流动时(在下一个循环中),退出工作很好,但是,当没有任何流被传输时,decoder.Decode会阻止执行,等待下一行json,这会阻止退出。 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

You can't interrupt a blocking read. 你不能打断阻塞读取。 If you want to interrupt reading of the response body, you need to cancel the http request. 如果要中断读取响应正文,则需要取消http请求。 This will close the connection, causing the blocked io.Reader to return io.EOF . 这将关闭连接,导致阻塞的io.Reader返回io.EOF

Create a "cancellable" request using the Request.WithContext method, and provide it with a cancellation context . 使用Request.WithContext方法创建“可取消”请求,并为其提供取消 上下文

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM