Go Flush() doesn't work

試著忘記壹切 提交于 2019-12-08 11:55:57

问题


Please, check this gist and tell me, what's wrong?
Why I don't see my messages?
The gist: https://gist.github.com/cnaize/895f61b762a9f5ee074c

If simple, I have two functions:

func send(param martini.Params, r render.Render) {
    Ct.Msgs <- param["msg"]

    fmt.Printf("Sent: %v", param["msg"])

    r.JSON(http.StatusOK, Response{"status": "ok"})
}

And watch function:

func watch(rw http.ResponseWriter, r render.Render) {
    var msg string
    ok := true
    for ok {
        select {
        case msg, ok = <-Ct.Msgs:
            rw.Write([]byte(msg))
            fmt.Printf("Wrote: %v", msg)
            f, ok := rw.(http.Flusher)
            if ok {
                f.Flush()
                fmt.Println("Flushed")
            } else {
                r.JSON(http.StatusOK, Response{"status": "error", "descr": "CANT_FLUSH"})
                return
            }
        }
    }

    r.JSON(http.StatusOK, Response{"status": "ok", "descr": "finished"})
}

Why it doesn't work?

EDITED:

I've updated my gist. Now where are:

if i, err := rw.Write([]byte(msg)); err != nil {
    r.JSON(http.StatusOK, Response{"status": "error", "descr": err.Error()})
    return
} else {
    fmt.Printf("i: %v", i)
}

And I have in logs:

 Sent: hello
 i: 5
 Wrote: hello
 Flushed

But I see nothing.

Any ideas?


回答1:


The flush is working. The issue is that Chrome's plain text renderer waits for the complete response body before displaying anything. Force the content type to html to see the incremental response:

func watch(rw http.ResponseWriter, r render.Render) {
    rw.Header().Set("Content-Type", "text/html")
    // same code as before
}


来源:https://stackoverflow.com/questions/26335228/go-flush-doesnt-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!