我用 Go 编写了一个小型支票簿分类帐,作为在本地主机中运行的服务器,并打开默认浏览器访问小型 Web 应用程序前端 ( https://bitbucket.org/grkuntzmd/checks-and-balances )。
为了在浏览器选项卡关闭时自动关闭服务器,我让浏览器每隔几秒调用一次“心跳”URL。如果该心跳未到达,服务器将使用 (*Server) Shutdown
停止运行。
有没有办法使用上下文( https://golang.org/pkg/context/ )做同样的事情?这是我观看this的理解JustForFunc 的情节是,如果客户端取消请求,则传递给处理程序的上下文将收到通知。
最佳答案
您可以利用server-sent events,而不是经常发送“心跳”请求。 .
服务器发送的事件是一种 Web 技术,浏览器发出 HTTP 请求并保持连接打开以接收来自服务器的事件。这可以通过在与事件源的连接关闭时关闭服务器来取代重复检测信号请求的需要。
这是 Go 中的基本服务器实现:
package main
import (
"fmt"
"log"
"net/http"
"time"
)
func main() {
http.HandleFunc("/heartbeat", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "your browser doesn't support server-sent events")
return
}
// Send a comment every second to prevent connection timeout.
for {
_, err := fmt.Fprint(w, ": ping")
if err != nil {
log.Fatal("client is gone, shutting down")
return
}
flusher.Flush()
time.Sleep(time.Second)
}
})
fmt.Println(http.ListenAndServe(":1323", nil))
}
参见using server-sent events获取客户端指南。
关于go - 在浏览器关闭时关闭 Go 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50686745/