Show Progress while processing post request in golang webapp

huangapple go评论129阅读模式
英文:

Show Progress while processing post request in golang webapp

问题

收到POST请求后,发布的数据会经过几个函数处理,处理完成后会显示适当的网页。问题在于,由于处理数据的函数需要一些时间,所以会有一点延迟。

有没有办法可以向客户端显示数据处理的进度?基本上,当数据被发布时,我希望显示一些消息,例如:

正在加载数据(完成xyz转换)
正在加载数据(xyz已添加到流中)

我在后端使用的是Go语言和julienschmidt的httprouter。

英文:

On receiving the post request, the posted data passes through several functions and when the processing is done, it displays a suitable web page. The problem is that there is a bit of delay since the functions for processing data are somewhat time taking.

Is there a way I can show clients the progress of data processing? Essentially, when a data is posted, I want some messages to be dislayed like

Loading data (xyz conversion done)
Loading data (xyz added to stream)

I am using golang for my backend and julienschmidt's httprouter .

答案1

得分: 1

在你的处理程序中,func(w ResponseWriter, r *Request)中的w ResponseWriter很可能实现了http.Flusher接口。因此,你可以在所有工作完成之前向客户端刷新数据。

io.WriteString(w, "Loading data (xyz conversion done)")
w.(http.Flusher).Flush() //你必须断言它实现了Flusher接口
io.WriteString(w, payload)

在掌握更多控制权的情况下,你甚至可以劫持连接。

conn, bufrw, err := w.(http.Hijacker).Hijack()
defer conn.Close()
bufrw.WriteString("Loading data (xyz conversion done)")
bufrw.Flush()
bufrw.WriteString("Loading data (xyz added to stream)")
bufrw.Flush()

并进行原始的TCP通信。

英文:

w ResponseWriter in your Handlers func(w ResponseWriter,r *Request) most likely implements http.Flusher interface. So you can

io.WriteString(w, "Loading data (xyz conversion done)")
w.(http.Flusher).Flush() //you must assert it implements
io.WriteString(w, payload)

flush to client before all work done.
To take more control you even can hijack connection

conn, bufrw, err :=w.(http.Hijacker).Hijack()
defer conn.Close()
bufrw.WriteString("Loading data (xyz conversion done)")
bufrw.Flush()
bufrw.WriteString("Loading data (xyz added to stream)")
bufrw.Flush()

and speak raw TCP.

答案2

得分: 1

显示进度指示器是客户端代码的工作(在进行异步调用时)。

HTTP是一种请求-响应协议。响应具有标准格式(包括状态行、头部和消息体)。它们不会分部分发送。

你所建议的可能与TCP连接相关,但与HTTP无关。

英文:

Showing a progress indicator is the job of your client-side code (while making an asynchronous call).

HTTP is a request–response protocol. Responses have a standard format (including a status line, headers, message body). They are not sent in parts.

What you are suggesting would be relevant to a TCP connection but not HTTP.

huangapple
  • 本文由 发表于 2017年1月28日 17:22:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/41908171.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定