greeting.cpp 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #include "greeting.h"
  2. #include <QCoreApplication>
  3. #include <QRegExp>
  4. #include <QStringList>
  5. #include <qhttpserver.h>
  6. #include <qhttprequest.h>
  7. #include <qhttpresponse.h>
  8. /// Greeting
  9. Greeting::Greeting()
  10. {
  11. QHttpServer *server = new QHttpServer(this);
  12. connect(server, SIGNAL(newRequest(QHttpRequest*, QHttpResponse*)),
  13. this, SLOT(handleRequest(QHttpRequest*, QHttpResponse*)));
  14. server->listen(QHostAddress::Any, 8080);
  15. }
  16. void Greeting::handleRequest(QHttpRequest *req, QHttpResponse *resp)
  17. {
  18. QRegExp exp("^/user/([a-z]+)$");
  19. if( exp.indexIn(req->path()) != -1 )
  20. {
  21. resp->setHeader("Content-Type", "text/html");
  22. resp->writeHead(200);
  23. QString name = exp.capturedTexts()[1];
  24. QString body = tr("<html><head><title>Greeting App</title></head><body><h1>Hello %1!</h1></body></html>");
  25. resp->end(body.arg(name).toUtf8());
  26. }
  27. else
  28. {
  29. resp->writeHead(403);
  30. resp->end(QByteArray("You aren't allowed here!"));
  31. }
  32. }
  33. /// main
  34. int main(int argc, char **argv)
  35. {
  36. QCoreApplication app(argc, argv);
  37. Greeting greeting;
  38. app.exec();
  39. }