douhua1890 2017-10-23 12:56
浏览 365
已采纳

Golang http写响应而无需等待完成

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.

  • 写回答

3条回答 默认 最新

  • doo58088 2017-10-23 13:08
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥200 csgo2的viewmatrix值是否还有别的获取方式
  • ¥15 Stable Diffusion,用Ebsynth utility在视频选帧图重绘,第一步报错,蒙版和帧图没法生成,怎么处理啊
  • ¥15 请把下列每一行代码完整地读懂并注释出来
  • ¥15 pycharm运行main文件,显示没有conda环境
  • ¥15 寻找公式识别开发,自动识别整页文档、图像公式的软件
  • ¥15 为什么eclipse不能再下载了?
  • ¥15 编辑cmake lists 明明写了project项目名,但是还是报错怎么回事
  • ¥15 关于#计算机视觉#的问题:求一份高质量桥梁多病害数据集
  • ¥15 特定网页无法访问,已排除网页问题
  • ¥50 如何将脑的图像投影到颅骨上