| 21 | /////////////////////////////////////////////////////////////////////////////// |
| 22 | |
| 23 | void runServer(const QString& portOrPath) { |
| 24 | using namespace qhttp::server; |
| 25 | |
| 26 | QHttpServer server(qApp); |
| 27 | // listening tcp port or Unix path |
| 28 | server.listen(portOrPath, [](QHttpRequest* req, QHttpResponse* res) { |
| 29 | req->collectData(); |
| 30 | |
| 31 | req->onEnd([req, res](){ |
| 32 | res->setStatusCode(qhttp::ESTATUS_OK); // status 200 |
| 33 | res->addHeader("connection", "close"); // optional(default) header |
| 34 | |
| 35 | int size = req->collectedData().size(); |
| 36 | auto message = [size]() -> QByteArray { |
| 37 | if ( size == 0 ) |
| 38 | return "Hello World!\n"; |
| 39 | |
| 40 | char buffer[65] = {0}; |
| 41 | qsnprintf(buffer, 64, "Hello!\nyou've sent me %d bytes!\n", size); |
| 42 | return buffer; |
| 43 | }; |
| 44 | |
| 45 | res->end(message()); // reponse body data |
| 46 | }); |
| 47 | |
| 48 | const auto& h = req->headers(); |
| 49 | // optionally let the clients to shut down the server |
| 50 | if ( h.keyHasValue("command", "quit") ) { |
| 51 | printf("a client sends a quit command.\nserver quits.\n"); |
| 52 | QCoreApplication::quit(); |
| 53 | return; |
| 54 | } |
| 55 | |
| 56 | // just for fun! print meta information: |
| 57 | qDebug("\n--> %s : %s", |
| 58 | qhttp::Stringify::toString(req->method()), |
| 59 | qPrintable(req->url().toString().toUtf8()) |
| 60 | ); |
| 61 | qDebug("[Headers (%d)]", h.size()); |
| 62 | h.forEach([](auto iter) { |
| 63 | qDebug(" %s : %s", |
| 64 | iter.key().constData(), |
| 65 | iter.value().constData() |
| 66 | ); |
| 67 | }); |
| 68 | }); |
| 69 | |
| 70 | if ( !server.isListening() ) { |
| 71 | fprintf(stderr, "failed. can not listen at port %s!\n", qPrintable(portOrPath)); |
| 72 | return; |
| 73 | } |
| 74 | |
| 75 | qApp->exec(); // application's main event loop |
| 76 | } |
| 77 | |
| 78 | #if defined(QHTTP_HAS_CLIENT) |
| 79 |
no test coverage detected