go - 在 go http 处理程序中使用 goroutine 和 channel 使 ResponseWriter 被阻塞

标签 go channel goroutine

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

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/

相关文章:

Leverice 中的 Jira channel 状态

time - 戈朗 : throttle (time delay) function is not working in goroutine (works fine in main thread)

go - 关于goroutine无限循环和内存分配的问题

pdf - 在 goPdf 中使用 Google Noto 字体

Go-直径 : how to determine data variable in NewAVP of TGPPUserLocationInfo to get desired value in Wireshark dump

arrays - 如何使用 Golang 将数据放入结构中?

go - 在不同的结构中声明多个* sync.Mutex变量

linux - 来自 TCP 套接字的 HTTP 服务器(在 Go 中)

java - Netty - 无法在注册时写入 channel (channelRegistered 事件)

go - 如何终止从 goroutine 调用的函数