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条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵