|
| 1 | +/// \file |
| 2 | +/// \ingroup tutorial_http |
| 3 | +/// This macro shows implementation of chunked requests |
| 4 | +/// These are special kind of user-defined requests which let |
| 5 | +/// split large http reply on many chunks so that server do not need to allocate |
| 6 | +/// such memory at once |
| 7 | +/// |
| 8 | +/// After macro started, try to execute request with |
| 9 | +/// ~~~ |
| 10 | +/// wget http://localhost:8080/chunked.txt |
| 11 | +/// ~~~ |
| 12 | +/// |
| 13 | +/// CAUTION: Example is not able to handle multiple requests at the same time |
| 14 | +/// For this one should create counter for each THttpCallArg instance |
| 15 | +/// |
| 16 | +/// \macro_code |
| 17 | +/// |
| 18 | +/// \author Sergey Linev |
| 19 | + |
| 20 | +#include "THttpServer.h" |
| 21 | +#include "THttpCallArg.h" |
| 22 | +#include <cstring> |
| 23 | + |
| 24 | +class TChunkedHttpServer : public THttpServer { |
| 25 | + protected: |
| 26 | + |
| 27 | + int fCounter = 0; |
| 28 | + |
| 29 | + /** process only requests which are not handled by THttpServer itself */ |
| 30 | + void MissedRequest(THttpCallArg *arg) override |
| 31 | + { |
| 32 | + if (strcmp(arg->GetFileName(), "chunked.txt")) |
| 33 | + return; |
| 34 | + |
| 35 | + arg->SetChunked(); |
| 36 | + |
| 37 | + std::string content = "line" + std::to_string(fCounter++) + " "; |
| 38 | + |
| 39 | + for (int n = 0; n < 2000; n++) |
| 40 | + content.append("-"); |
| 41 | + content.append("\n"); |
| 42 | + |
| 43 | + if (fCounter >= 1000) { |
| 44 | + // to stop chunk transfer either provide empty content or clear chunked flag |
| 45 | + fCounter = 0; |
| 46 | + arg->SetChunked(kFALSE); |
| 47 | + } |
| 48 | + |
| 49 | + arg->SetTextContent(std::move(content)); |
| 50 | + } |
| 51 | + |
| 52 | + public: |
| 53 | + TChunkedHttpServer(const char *engine) : THttpServer(engine) {} |
| 54 | + |
| 55 | + ClassDefOverride(TChunkedHttpServer, 0) |
| 56 | +}; |
| 57 | + |
| 58 | +void httpchunked() |
| 59 | +{ |
| 60 | + // start http server |
| 61 | + auto serv = new TChunkedHttpServer("http:8080"); |
| 62 | + |
| 63 | + // reduce to minimum timeout for async requests processing |
| 64 | + serv->SetTimer(1); |
| 65 | +} |
0 commit comments