package main
import (
"fmt"
"net/http"
"time"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
)
func main() {
s := g.Server()
s.BindHandler("/", func(r *ghttp.Request) {
rw := r.Response.RawWriter()
flusher, ok := rw.(http.Flusher)
if !ok {
http.Error(rw, "Streaming unsupported!", http.StatusInternalServerError)
return
}
r.Response.Header().Set("Content-Type", "text/event-stream")
r.Response.Header().Set("Cache-Control", "no-cache")
r.Response.Header().Set("Connection", "keep-alive")
for i := 0; i < 100; i++ {
_, err := fmt.Fprintf(rw, "data: %d\n", i)
if err != nil {
panic(err)
}
flusher.Flush()
time.Sleep(time.Millisecond * 200)
}
})
s.SetPort(8999)
s.Run()
}
3 Comments
吴萌野
郭强 2.4 之后改进后的代码应该是这样
zhangyaokun
2.4版本,如果有前置统一输入输出处理的中间件,请将该方法放置于中间件作用域之外,或者使用
r.ExitAll()
方法跳出中间件控制。不使用
data: 97 data: 98 data: 99 {"code":0,"message":"","data":null}r.ExitAll()
,流式响应生效,但是最终会返回统一结构体r.ExitAll()或者r.ExitA()
不能使用流式响应,直接返回统一响应,ae86
https://www.ruanyifeng.com/blog/2017/05/server-sent_events.html 推荐看一下,适合服务端单向推送~