【Golang】go中如何在浏览器上实时显示cmd控制台的输出(流式传输)
生活随笔
收集整理的這篇文章主要介紹了
【Golang】go中如何在浏览器上实时显示cmd控制台的输出(流式传输)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
靈感來(lái)自于:Print the console log to the screen of a webpage continuously using Go Routines
廢話不多說(shuō),直接上代碼(功能:每1秒輸出一個(gè)數(shù),逐漸遞增):
package mainimport ("bufio""fmt""io""log""net/http""os""os/exec""github.com/nbari/violetear" )func stream(w http.ResponseWriter, r *http.Request) {// 使瀏覽器頁(yè)面的滾動(dòng)條始終置于底部scroll := ` <body style="word-wrap: break-word; white-space: pre-wrap;"><script>// https://stackoverflow.com/questions/14866775/detect-document-height-change// Purpose: Make sure the scroll bar is always at the bottom of the page as the page continues to output.// create an Observer instanceconst resizeObserver = new ResizeObserver(() =>window.scrollTo(0, document.body.scrollHeight))// start observing a DOM noderesizeObserver.observe(document.body) </script></body> `fmt.Fprint(w, scroll)ctx := r.Context()ch := make(chan struct{})// 每1秒輸出一個(gè)數(shù),逐漸遞增cmd := exec.CommandContext(ctx, "python", "-c", "exec(\"import sys\\nimport time\\nfor i in range(100): print(i);sys.stdout.flush();time.sleep(0.1)\")")rPipe, wPipe, err := os.Pipe()if err != nil {log.Fatal(err)}cmd.Stdout = wPipecmd.Stderr = wPipeif err := cmd.Start(); err != nil {log.Fatal(err)}go writeOutput(w, rPipe)go func(ch chan struct{}) {cmd.Wait()wPipe.Close()ch <- struct{}{}}(ch)select {case <-ch:case <-ctx.Done():err := ctx.Err()log.Printf("Client disconnected: %s\n", err)} }func writeOutput(w http.ResponseWriter, input io.ReadCloser) {flusher, ok := w.(http.Flusher)if !ok {http.Error(w, "Streaming not supported", http.StatusInternalServerError)return}// Important to make it work in browsersw.Header().Set("Content-Type", "text/event-stream")w.Header().Set("Cache-Control", "no-cache")w.Header().Set("Connection", "keep-alive")in := bufio.NewScanner(input)for in.Scan() {data := in.Text()log.Printf("data: %s\n", data)fmt.Fprintf(w, "data: %s\n", data)flusher.Flush()}input.Close() }func main() {router := violetear.New()router.HandleFunc("/", stream, "GET")log.Fatal(http.ListenAndServe(":8080", router)) }編譯運(yùn)行后直接在瀏覽器上輸入http://localhost:8080/就能看到輸出結(jié)果:
可以看到在瀏覽器端實(shí)現(xiàn)了cmd的實(shí)時(shí)顯示,流式傳輸。
總結(jié)
以上是生活随笔為你收集整理的【Golang】go中如何在浏览器上实时显示cmd控制台的输出(流式传输)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 单细胞基因可视化之UMAP图修饰
- 下一篇: Postgresql修改时区