bodydata.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #include "bodydata.h"
  2. #include <QCoreApplication>
  3. #include <QRegExp>
  4. #include <QStringList>
  5. #include <QDebug>
  6. #include <qhttpserver.h>
  7. #include <qhttprequest.h>
  8. #include <qhttpresponse.h>
  9. /// BodyData
  10. BodyData::BodyData()
  11. {
  12. QHttpServer *server = new QHttpServer(this);
  13. connect(server, SIGNAL(newRequest(QHttpRequest*, QHttpResponse*)),
  14. this, SLOT(handleRequest(QHttpRequest*, QHttpResponse*)));
  15. server->listen(QHostAddress::Any, 8080);
  16. }
  17. void BodyData::handleRequest(QHttpRequest *req, QHttpResponse *resp)
  18. {
  19. new Responder(req, resp);
  20. }
  21. /// Responder
  22. Responder::Responder(QHttpRequest *req, QHttpResponse *resp)
  23. : m_req(req)
  24. , m_resp(resp)
  25. {
  26. QRegExp exp("^/user/([a-z]+$)");
  27. if (exp.indexIn(req->path()) == -1)
  28. {
  29. resp->writeHead(403);
  30. resp->end(QByteArray("You aren't allowed here!"));
  31. /// @todo There should be a way to tell request to stop streaming data
  32. return;
  33. }
  34. resp->setHeader("Content-Type", "text/html");
  35. resp->writeHead(200);
  36. QString name = exp.capturedTexts()[1];
  37. QString bodyStart = tr("<html><head><title>BodyData App</title></head><body><h1>Hello %1!</h1><p>").arg(name);
  38. resp->write(bodyStart.toUtf8());
  39. connect(req, SIGNAL(data(const QByteArray&)), this, SLOT(accumulate(const QByteArray&)));
  40. connect(req, SIGNAL(end()), this, SLOT(reply()));
  41. connect(m_resp, SIGNAL(done()), this, SLOT(deleteLater()));
  42. }
  43. Responder::~Responder()
  44. {
  45. }
  46. void Responder::accumulate(const QByteArray &data)
  47. {
  48. m_resp->write(data);
  49. }
  50. void Responder::reply()
  51. {
  52. m_resp->end(QByteArray("</p></body></html>"));
  53. }
  54. /// main
  55. int main(int argc, char **argv)
  56. {
  57. QCoreApplication app(argc, argv);
  58. BodyData bodydata;
  59. app.exec();
  60. }