dpsfay2510 2018-06-04 18:31
浏览 99
已采纳

关闭浏览器上的Go服务器

I wrote a small checkbook ledger in Go as a server that runs in localhost and opens the default browser to a small web app front-end (https://bitbucket.org/grkuntzmd/checks-and-balances).

To automatically shut down the server when the browser tab is closed, I have the browser call a "heartbeat" URL every few seconds. If that heartbeat does not arrive, the server uses (*Server) Shutdown to stop running.

Is there any way to do the same thing using contexts (https://golang.org/pkg/context/)? It is my understanding from watching this episode of JustForFunc that a context passed down to a handler will be notified if the client cancels a request.

  • 写回答

2条回答 默认 最新

  • dot_0620 2018-06-04 19:33
    关注

    Instead of sending a "heartbeat" request every so often, you could take advantage of server-sent events.

    Server-sent events is a web technology where the browser makes a HTTP request and keeps the connection open to receive events from the server. This could replace your need for repeated heartbeat requests by having the server shutdown when the connection to the event source is closed.

    Here's a basic server implementation in 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))
    }
    

    See using server-sent events for a guide on the client side.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛