package main
import (
"fmt"
"log"
"net/http"
"time"
)
var ch chan bool
func testTimer1() {
go func() {
log.Println("test timer 1")
ch <- true
}()
}
func timer1() {
timer1 := time.NewTicker(2 * time.Second)
select {
case <-timer1.C:
testTimer1()
}
}
func myhandler(w http.ResponseWriter, r *http.Request) {
for {
go timer1()
a := <-ch
log.Println("get a: ", a)
fmt.Fprintf(w, "hello world!!!!", a)
}
log.Println("test for break")
}
func main() {
ch = make(chan bool)
http.HandleFunc("/", myhandler)
http.ListenAndServe(":8080", nil)
}
我写了上面的代码,把一个channel放到"myhandler"里面,channel就会 当
定时器任务已执行。
然后我从 channel 获取数据并将“hello world”写入http writer
但是我发现客户端收不到“hello world”,作者被屏蔽了!!!!!
有人知道吗?
在我的 cmd 上查看正在运行的图片: enter image description here
最佳答案
for
循环是一个无限循环,因此打印到 ResponseWriter
不是“计划”发生的。如果您想要类似 cometd 的方法(或长轮询 URL),您可能想尝试 this method .
timer1()
中也存在代码泄漏。根据Go Docs :
Stop the ticker to release associated resources.
每次调用 go timer1()
时,您总是会创建一个新的代码,并且代码永远不会关闭,因此每个新的代码都会相加。
关于go - 在 go http 处理程序中使用 goroutine 和 channel 使 ResponseWriter 被阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42979595/