Golang中使用http.Flusher将缓冲区数据发送给客户端

发表时间: 2024-05-19 22:39

http.Flusher

案例1:

package mainimport (    "fmt"    "log"    "net/http"    "time")func handler(res http.ResponseWriter, r *http.Request) {    fmt.Fprintln(res, "<body>")    for i := 0; i < 1000; i++ {        fmt.Fprint(res, "<script>document.body.innerHTML = ''</script>")        fmt.Fprintf(res, "%d", i)        if f, ok := res.(http.Flusher); ok {            f.Flush() // 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))}

案例2:

package mainimport ("bytes""crypto/rand""encoding/binary""fmt""net/http""time")func main() {    http.HandleFunc("/", httpHandle)    http.ListenAndServe("localhost:8081", nil)}func httpHandle(w http.ResponseWriter, r *http.Request) {    randId, err := randUint32()    if err != nil {    w.WriteHeader(http.StatusInternalServerError)    w.Write([]byte(http.StatusText(http.StatusInternalServerError)))    return		}    s1 := fmt.Sprintf("你好<%d>: %s\n", randId, time.Now().Format("15:04:05"))    w.Write([]byte(s1))    if f, ok := w.(http.Flusher); ok {    		f.Flush() // Flush将缓冲中的所有数据发送到客户端		}    time.Sleep(2 * time.Second)    s2 := fmt.Sprintf("世界<%d>: %s\n", randId, time.Now().Format("15:04:05"))    w.Write([]byte(s2))    if f, ok := w.(http.Flusher); ok {    		f.Flush() // Flush将缓冲中的所有数据发送到客户端    }}// 唯一随机数func randUint32() (uint32, error) {    b1 := make([]byte, 4)    _, err := rand.Read(b1)    if err != nil {        return 0, err    }    var res uint32    b2 := bytes.NewBuffer(b1)    err = binary.Read(b2, binary.LittleEndian, &res)    if err != nil {        return 0, err    }    return res, nil}
> # go run main.go浏览器访问: http://localhost:8081/你好<1481809071>: 16:01:25世界<1481809071>: 16:01:27

http.ResponseWriter.Write 写入的数据会被缓存, 直到函数返回时才会被flush到底层的connection http.Fluhser.Flush则可以将数据收到刷新至底层, 从而实现流的输出