gpt4 book ai didi

go - 当请求被取消或超时时如何从 http 处理程序返回

转载 作者:IT王子 更新时间:2023-10-29 02:20:39 24 4
gpt4 key购买 nike

我在做sse ,重要的代码是:

   var clientes=new(sync.Map)
type canalesStruct struct{
sender chan []byte
close chan bool
}
func (broker *brokerStruct) ServeHTTP(w http.ResponseWriter, r *http.Request) {
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "Streaming unsupported!", http.StatusInternalServerError)
return
}

w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
var ID string
//Get the ID somehow
canales:=new(canalesStruct)
canales.sender=make(chan []byte)
canales.close=make(chan bool)
clientes.store(ID,canales)
notify := w.(http.CloseNotifier).CloseNotify()
defer func() {
clientes.Delete(ID)
}()
for {
select {
case <-notify:
return
case <-canales.close:
return
case data:= <-canales.sender:
fmt.Fprintf(w, "data: %s\n\n",data)
flusher.Flush()
}
}
}

func sendDataToChanelID(ID string,data []byte){
canalesRaw,_:=clientes.Load(ID)
canales,_:=canalRaw(*canalesStruct)
canales.sender <-data
}

所以我有两个问题:

  1. 如果在接收数据时连接断开,fmt.Fprintf继续无休止地等待还是它会立即返回?
  2. 如果它立即返回,则没有问题,但如果它继续等待,我如何包装“fmt.Fprintf”以便在超时时返回?

最佳答案

我相信当底层 HTTP 请求关闭时,对 fmt.Fprintf() 的调用将会失败。

这里的“失败”意味着它将返回一个非零错误。

因此,要正确处理 HTTP 请求被关闭的情况,检查fmt.Fprintf()的错误返回,如

_, err := fmt.Fprintf(w, ...)
if err != nil {
// We have failed to write to the underlying connection
}

关于go - 当请求被取消或超时时如何从 http 处理程序返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51303528/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com