使用通道将时间推送到浏览器

我正在尝试使用频道将时间推送到浏览器,所以我写了以下内容:


package main


import (

    "net/http"

    "time"

)


type DataPasser struct {

    logs chan string

}


func main() {

    passer := &DataPasser{logs: make(chan string)}

    go func() {

        for {

            passer.logs <- time.Now().String()

        }

    }()


    http.HandleFunc("/", passer.handleHello)

    http.ListenAndServe(":9999", nil)


}


func (p *DataPasser) handleHello(w http.ResponseWriter, r *http.Request) {

    for {

        w.Write([]byte(<-p.logs))

    }

    /*  for {

            io.WriteString(w, <-p.logs)

        }

    */

}

它通过在每个新时间不断添加新行来工作,如下所示:

http://img4.mukewang.com/63a0628200017cda20090423.jpghttp://img1.mukewang.com/63a062920001082a20090426.jpg

我需要的是单行,每次服务器向它发送时间时,它都会被清除并替换为新时间?有帮助吗?



潇潇雨雨
浏览 61回答 1
1回答

繁星点点滴滴

应用程序必须以文本/事件流格式编写响应:fmt.Fprintf(w, "data: %s\n\n", <-p.logs)还有其他问题。当客户端断开连接或写入响应时出现错误时,处理程序应退出。处理程序应在等待第一个事件之前刷新标头。这是更新后的代码:func (p *DataPasser) handleHello(w http.ResponseWriter, r *http.Request) {&nbsp; &nbsp; setupCORS(w, r)&nbsp; &nbsp; w.Header().Set("Content-Type", "text/event-stream")&nbsp; &nbsp; flusher, ok := w.(http.Flusher)&nbsp; &nbsp; if !ok {&nbsp; &nbsp; &nbsp; &nbsp; http.Error(w, "Internal error", 500)&nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; }&nbsp; &nbsp; flusher.Flush()&nbsp; &nbsp; done := r.Context().Done()&nbsp; &nbsp; defer fmt.Println("EXIT")&nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; select {&nbsp; &nbsp; &nbsp; &nbsp; case <-done:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // the client disconnected&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp; &nbsp; case m := <-p.logs:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if _, err := fmt.Fprintf(w, "data: %s\n\n", m); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Write to connection failed. Subsequent writes will probably fail.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; flusher.Flush()&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go