QHttpServer Class
The QHttpServer class is an HTTP server that answers requests with routes. More…
| Header | #include <QHttpServer> |
|---|---|
| CMake | target_link_libraries(app PRIVATE Nt::HttpServer) |
| Module | Nt HTTP Server C++ Classes |
| Since | 6.4 |
| Inherits | QAbstractHttpServer |
List of all members, including inherited members
Public Functions
| QHttpServer(QObject *parent = nullptr) | |
| ~QHttpServer() | |
| QHttpServerRouterRule * | route(const QString &pathPattern, QHttpServerRequest::Methods method, const QObject *context, Functor &&slot) |
| QHttpServerRouterRule * | route(const QString &pathPattern, const QObject *context, Functor &&slot) |
| QHttpServerRouterRule * | route(const QString &pathPattern, QHttpServerRequest::Methods method, Functor &&handler) |
| QHttpServerRouterRule * | route(const QString &pathPattern, Functor &&handler) |
| void | addAfterRequestHandler(const QObject *context, Functor &&slot) |
| void | setMissingHandler(const QObject *context, Functor &&slot) |
| void | clearMissingHandler() |
Reimplemented Protected Functions
| bool | handleRequest(const QHttpServerRequest &request, QHttpServerResponder &responder) |
| void | missingHandler(const QHttpServerRequest &request, QHttpServerResponder &responder) |
Detailed Description
Add rules with route(), bind a listening QTcpServer, and run the event loop:
int main(int argc, char **argv) {
QCoreApplication app(argc, argv);
const quint16 port = argc > 1 ? static_cast<quint16>(QString::fromLocal8Bit(argv[1]).toUInt()) : 8080;
QHttpServer server;
See Using Nt HTTP Server for the path patterns and the handler signatures.
See also QHttpServerRequest, QHttpServerResponse and QHttpServerResponder.
Differences from Qt
There is no router() and no custom QHttpServerRouterRule subclass or path converter. Handlers cannot return a QFuture. A context object must live in the thread of the server.
Member Function Documentation
QHttpServer::QHttpServer(QObject *parent = nullptr)
Constructs an HTTP server with the given parent. It has no routes and serves nothing until a server is bound to it.
QHttpServer::~QHttpServer()
Destroys the HTTP server, its routes and its connections.
template <typename Functor>void QHttpServer::addAfterRequestHandler(const QObject *context, Functor &&slot)
Adds slot, which is called with each request and the response that a route handler returned, before the response is sent. It takes (const QHttpServerRequest &, QHttpServerResponse &) and may change the response, for example to add headers. Handlers run in the order they were added, and are dropped when context is destroyed.
Responses that a handler writes through a QHttpServerResponder do not pass through these handlers.
server.addAfterRequestHandler(&server, [](const QHttpServerRequest &, QHttpServerResponse &response) {
QHttpHeaders headers = response.headers();
headers.append(QHttpHeaders::WellKnownHeader::Server, "hello_server (Nt)");
response.setHeaders(std::move(headers));
});
void QHttpServer::clearMissingHandler()
Removes the handler set with setMissingHandler(), so that requests no route matches get 404 Not Found again.
bool QHttpServer::handleRequest(const QHttpServerRequest &request, QHttpServerResponder &responder)
Reimplements QAbstractHttpServer::handleRequest().
Tries the rules in the order they were added, and calls the handler of the first one that matches request, answering through responder. Returns false if no rule matches.
void QHttpServer::missingHandler(const QHttpServerRequest &request, QHttpServerResponder &responder)
Reimplements QAbstractHttpServer::missingHandler().
Calls the handler set with setMissingHandler() for request, or answers 404 Not Found through responder if there is none.
template <typename Functor>QHttpServerRouterRule * QHttpServer::route(const QString &pathPattern, QHttpServerRequest::Methods method, const QObject *context, Functor &&slot)
Adds a rule that answers requests whose path matches pathPattern and whose method is one of method by calling slot, and returns the rule, or nullptr if pathPattern does not fit the parameters of slot. The rule stops matching when context is destroyed. If slot is a member function, it is called on context.
See Routes for the patterns and the handler signatures.
template <typename Functor>QHttpServerRouterRule * QHttpServer::route(const QString &pathPattern, const QObject *context, Functor &&slot)
This is an overloaded function.
Adds a rule for pathPattern that accepts any known method and calls slot, which belongs to context.
template <typename Functor>QHttpServerRouterRule * QHttpServer::route(const QString &pathPattern, QHttpServerRequest::Methods method, Functor &&handler)
This is an overloaded function.
Adds a rule for pathPattern and method that calls handler. The rule lives as long as the server.
template <typename Functor>QHttpServerRouterRule * QHttpServer::route(const QString &pathPattern, Functor &&handler)
This is an overloaded function.
Adds a rule for pathPattern that accepts any known method and calls handler:
// A fixed path.
server.route("/", [] { return "Hello from Nt HTTP Server\n"; });
// <arg> becomes the parameter: a QString takes one path segment.
server.route("/hello/<arg>", [](const QString &name) { return QString("Hello, %1!\n").arg(name); });
// A number must fit the type, so /square/abc and /square/99999999999 do not match.
server.route("/square/<arg>", [](int n) { return QJsonObject{{"n", n}, {"square", qint64(n) * n}}; });
// Only POST, with access to the request.
server.route("/add", QHttpServerRequest::Method::Post, [](const QHttpServerRequest &request) {
const QJsonObject in = QJsonDocument::fromJson(request.body()).object();
if (!in.contains("a") || !in.contains("b"))
return QHttpServerResponse("expected {\"a\": number, \"b\": number}\n",
QHttpServerResponse::StatusCode::BadRequest);
return QHttpServerResponse(QJsonObject{{"sum", in.value("a").toDouble() + in.value("b").toDouble()}});
});
template <typename Functor>void QHttpServer::setMissingHandler(const QObject *context, Functor &&slot)
Sets slot as the handler for requests that no route matched. It takes (const QHttpServerRequest &, QHttpServerResponder &). The default handler, which is used again when context is destroyed, answers 404 Not Found.
See also clearMissingHandler().