Golang http write response without waiting to finish

后端 未结 3 1665
后悔当初
后悔当初 2021-01-29 08:35

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 g

3条回答
  •  情歌与酒
    2021-01-29 09:32

    Contrary to what others have said, what you want is in fact directly possible but requires fullfillment of the two preconditions:

    • HTTP/1.1 and above.
    • You'll be sending custom content to the clients — not PDF data directly, — and they're prepared to accept and parse it.

    You can then employ the so-called "chunked" payload encoding specifically invented to handle "streamed" downloads where the server does not know how many bytes it's about to send.

    So you may invent some creative kind of payload where you first periodically stream a "no op" / "progress" marker and then the actual payload. Say, while the file is being prepared you periodically send a line of text reading "PROCESSING" + LF then, when a result is ready you send a line of text "READY" SIZE + LF where SIZE is the size, in bytes, of the immediately following PDF document. After the document is streamed, the server signals the end of data.

    Hence the stream would look like

    PROCESSING
    PROCESSING
    …
    PROCESSING
    READY 8388608
    %PDF-1.3
    …
    %%EOF
    

    The clients have to be able to parse this information from the stream they're receiving and have a simple FSM in place to switch from state to state as they fetch your stream.

    The server has to make sure it flushes the stream after each "informational" line otherwise the whole thing would not be "interactive".

    If you have a good idea about the overall state of the processing of the document, each "status update" line could include the percentage of the work done, like in "PROCESSINGNN" + LF.

提交回复
热议问题