Golang:HTTP页面自动刷新

use*_*472 1 go

我有一个使用 Go 编程语言执行的 HTTP 页面。GO 中的函数如下所示:

func main(){
    ...
    http.HandleFunc("/Page", func(w http.ResponseWriter, r *http.Request) {
        t:=template.New("New template")
        child_template := t.New("New child template")
        _, _ = child_template.Parse(output)  // output is from the omitted code
        t, err = t.ParseFiles("HTML_template.html")
        _ = t.ExecuteTemplate(w, "HTML_template.html", output)
    }
}
Run Code Online (Sandbox Code Playgroud)

如何让 /Page 自行刷新?我已经尝试过以下方法,但它不起作用。

func main(){
    ...
    http.HandleFunc("/Page", func(w http.ResponseWriter, r *http.Request) {
        for{
            t:=template.New("New template")
            child_template := t.New("New child template")
            _, _ = child_template.Parse(output)  // output is from the omitted code
            t, err = t.ParseFiles("HTML_template.html")
            _ = t.ExecuteTemplate(w, "HTML_template.html", output)

            time.Sleep(time.Millisecond*100)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试制作一个动态图来绘制每秒传入数据的数量。如果我继续刷新浏览器,轴也会重新加载,而且看起来很难看。HTML_template.html 看起来像这样

<script type = "text/javascript">
    function plot(){
        ...
        var data = [{{template "New child template"}}];
        ...
    }
    setInterval(func(){plot()},500);
</script>
Run Code Online (Sandbox Code Playgroud)

Ain*_*r-G 6

只需添加刷新元标记,无需 Go、JavaScript、AJAX、SSE 或 Websockets 即可完成此操作。添加

<meta http-equiv="refresh" content="3" />
Run Code Online (Sandbox Code Playgroud)

进入您的页面<head>将导致其每 3 秒刷新一次。