Whether Golang can realize browser output line by line

whether Golang can achieve buffer output similar to PHP

I am now using beego for Web development, and I want to achieve a similar function:

The

page prints numbers from 1 to 10000000, operates using a loop, and then outputs the current number each time it loops.

if the operation is normal, then when the page is displayed, all the numbers have been displayed, so that the effect I want will not be achieved.

is there a way for me to open the page and start to execute a loop, each time a number is output in the page, instead of displaying the page after all the loops and output is complete?

PHP can be implemented with functions such as ob_flush , but golang is not quite clear how to implement it.

Apr.05,2021

package main

import (
    "fmt"
    "net/http"
    "log"
    "time"
)


func handler(res http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(res, "<body>")
    for i := 0; i < 1000; iPP {
        fmt.Fprint(res, "<script>document.body.innerHTML = ''</script>")
        fmt.Fprintf(res, "%d", i)
        if f, ok := res.(http.Flusher); ok {
            f.Flush()
        } else {
            log.Println("Damn, no flush");
        }
        time.Sleep(1000 * time.Millisecond)
    }

    fmt.Fprintln(res, "</body>")
}

func main() {
    http.HandleFunc("/", handler)
    log.Fatal(http.ListenAndServe(":8080", nil))
}
Menu