Golang http写入响应没有等待完成 [英] Golang http write response without waiting to finish

查看:363
本文介绍了Golang http写入响应没有等待完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个构建pdf文件的应用程序,并在收到请求时将其返回给客户端。



由于其中一些pdf文件可能需要一些时间才能生成,因此我希望在运行时定期向客户端发送某种状态更新。



完成pdf文件的生成后,它应该返回给客户端。



类似于:

  func buildReport(writer http.ResponseWriter,request * http.Request){
// build pdf build pdf file
for {//仅用于
writer.Write([] byte(building。Please wait。))
}
pdf.OutputFileAndClose(report.pdf )
//将标题设置为pdf,以便客户端知道它是PDF
writer.Header()。Set(Content-Type,application / pdf)
http.ServeFile (作者,请求,report.pdf)
}

func main(){
http.HandleFunc(/,buildReport)
http.ListenAndServe (:8081,无)
}

设置标题可能不起作用,因为Ť他的作者只能有一个头文件。

TL; DR就是说它不能这样实现。您需要


  1. 请求创建PDF的API。这使PDF创建作业在任务队列中排队(这样太多的PDF创建请求不会影响HTTP服务器工作池) 提供一个API,允许您检查PDF渲染(我假设这项工作可以提供临时统计)。这将定期由客户端进行轮询。

  2. 一旦API准备好就可以使用该API。

希望这对您的项目有所帮助,祝您好运。


I'm building an application that builds a pdf file and returns it to the client whenever it receives a request.

Since some of these pdf files might take some time to generate, I would like to periodically send some sort of status update back to client while it is running.

When it's finished building the pdf file, it should be returned to the client as well.

Something akin to:

func buildReport(writer http.ResponseWriter, request *http.Request){
    //build pdf build pdf file
    for { //for example purposes only
        writer.Write([]byte("building. Please wait."))
    }
    pdf.OutputFileAndClose("report.pdf")
    //set header to pdf so that the client knows it's a PDF
    writer.Header().Set("Content-Type", "application/pdf")
    http.ServeFile(writer, request, "report.pdf")
}

func main() {
    http.HandleFunc("/", buildReport)
    http.ListenAndServe(":8081", nil)
}

Setting the header might not work, as the writer can only have one header.

解决方案

TL;DR is that it cannot be implemented that way. You need to

  1. An API that requests the PDF creation. That queues PDF creation job in a task queue (so that too many PDF creation requests won't blow the HTTP server worker pool)
  2. Provide an API that allows you to check where are you with the PDF rendering (I am assuming that the job can provide interim stats). This is going to be polled by the client on a regular basis.
  3. An API to pull the PDF once it is ready.

Hope this helps and best of luck with your project.

这篇关于Golang http写入响应没有等待完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆