QHttpServer Class
QHttpServer is a simplified API for QAbstractHttpServer and QHttpServerRouter. More...
Header: | #include <QHttpServer> |
CMake: | find_package(Qt6 REQUIRED COMPONENTS HttpServer) target_link_libraries(mytarget PRIVATE Qt6::HttpServer) |
qmake: | QT += httpserver |
Since: | Qt 6.4 |
Inherits: | QAbstractHttpServer |
Public Functions
QHttpServer(QObject *parent = nullptr) | |
virtual | ~QHttpServer() override |
void | addAfterRequestHandler(const QObject *context, Functor &&slot) |
void | clearMissingHandler() |
Rule * | route(const QString &pathPattern, QHttpServerRequest::Methods method, const QObject *context, Functor &&slot) |
Rule * | route(const QString &pathPattern, Functor &&handler) |
Rule * | route(const QString &pathPattern, QHttpServerRequest::Methods method, Functor &&handler) |
Rule * | route(const QString &pathPattern, const QObject *context, Functor &&slot) |
QHttpServerRouter * | router() |
const QHttpServerRouter * | router() const |
void | setMissingHandler(const QObject *context, Functor &&slot) |
Detailed Description
QHttpServer is used to create a simple HTTP server by registering a range of request handlers.
The route function can be used to conveniently add rules to the server's QHttpServerRouter. To register a handler that is called after every request to further process the response use addAfterRequestHandler, but this mechanism only works for routes returning QHttpServerResponse or QFuture<QHttpServerResponse>
. To register a handler for all unhandled requests use setMissingHandler.
Minimal example:
QHttpServer server; server.route("/", [] () { return "hello world"; }); auto tcpserver = new QTcpServer(); if (!tcpserver->listen() || !server.bind(tcpserver)) { delete tcpserver; return -1; } qDebug() << "Listening on port" << tcpserver->serverPort();
Member Function Documentation
[explicit]
QHttpServer::QHttpServer(QObject *parent = nullptr)
Creates an instance of QHttpServer with parent parent.
[override virtual noexcept]
QHttpServer::~QHttpServer()
Destroys a QHttpServer.
template <typename Functor> void QHttpServer::addAfterRequestHandler(const QObject *context, Functor &&slot)
Register a context and slot to be called after each request is handled.
The slot has to implement the signature void (*)(const QHttpServerRequest &, QHttpServerResponse &)
.
The slot can also be a function pointer, non-mutable lambda, or any other copyable callable with const call operator. In that case the context will be a context object and the handler will be valid until the context object is destroyed.
Example:
server.addAfterRequestHandler(&server, [] (const QHttpServerRequest &req, QHttpServerResponse &resp) { auto h = resp.headers(); h.append(QHttpHeaders::WellKnownHeader::Cookie, "PollyWants=Cracker"); resp.setHeaders(std::move(h)); }
Note: These handlers will only be called for requests that are processed by route handlers that either return QHttpServerResponse or QFuture<QHttpServerResponse>, and therefore do not take a QHttpServerResponder argument.
void QHttpServer::clearMissingHandler()
Resets the handler to the default one that produces replies with status 404 Not Found
.
See also setMissingHandler.
template <typename Rule = QHttpServerRouterRule, typename Functor> Rule *QHttpServer::route(const QString &pathPattern, QHttpServerRequest::Methods method, const QObject *context, Functor &&slot)
This method is used to add a new Rule
to the server's QHttpServerRouter member. The Rule
template parameter can be any custom class derived from QHttpServerRouterRule. The parameters are passed to Rule
. When handling the incoming HTTP requests, the QHttpServerRouter matches the Rule
to the incoming HTTP request using the URL and HTTP method, and the first match of both is executed. The pathPattern parameter is compared with the path() of the URL of the incoming request. The method parameter is compared with the HTTP method of the incoming request.
The slot parameter can be a member function pointer of context. It can also be a function pointer, a non-mutable lambda, or any other copyable callable with const call operator. The rule will be valid for the lifetime duration of context. The context must share the same thread affinity as the QHttpServer for the registration to be successful and for the rule to be executed.
The slot can express its response with a return statement. In that case the function has to return QHttpServerResponse or any type that can be converted to QHttpServerResponse. A large range of conversion constructors are available, see QHttpServerResponse.
QHttpServer server; server.route("/test/", this, [] () { return ""; });
Alternatively, an optional QHttpServerResponder& argument can be provided, in which case the response has to be written using it and the function must return void
.
server.route("/test2", this, [] (QHttpServerResponder &responder) { responder.write(QHttpServerResponder::StatusCode::Forbidden); });
The slot can also have const
QHttpServerRequest& as the last parameter, or as the second to last if the QHttpServerResponder& is the last parameter. It contains detailed information on the request.
server.route("/test3", QHttpServerRequest::Method::Post, this, [] (const QHttpServerRequest &request, QHttpServerResponder &responder) { responder.write(request.body(), "text/plain"_ba); });
The slot can also take any amount of copyable parameters that can have the types available from QHttpServerRouter::converters(). By default, these are most integer types, float, double, QString, QByteArray, and QUrl. Converters for additional types can be added by calling QHttpServerRouter::addConverter().
The pathPattern can contain a number of "<arg>"
substrings that are matched with the parameters of slot from left to right. The converters are chosen based on the types of these parameters.
Each registered type has an associated regex that is used to match and convert occurrences of "<arg>"
in the pathPattern. These regex patterns are combined to construct a parser for the entire path. The resulting parser is then used to verify if the path matches the pattern. If parsing succeeds, the corresponding function is called with the converted parameters. If parsing fails, the next registered callback is attempted.
In the example below, the value in the request path replacing "<arg>"
is converted to an int
because the lambda expects an int
parameter. When an HTTP request matches the route, the converted value is passed to the lambda's page
argument:
QHttpServer server; server.route("/showpage/<arg>", this, [] (const int page) { return getPage(page); });
This function returns, if successful, a pointer to the newly created Rule, otherwise a nullptr
. The pointer can be used to set parameters on any custom QHttpServerRouter class:
auto rule = server.route<MyRule>("/test4", this, [] () {return "";}); rule->setParameter("test");
Note: This function, route, must not be called from slot, so no route handlers can register other route handlers.
Note: If a request was processed by a slot accepting QHttpServerResponder& as an argument, none of the after request handlers (see addAfterRequestHandler) will be called.
Requests are processed sequentially inside the QHttpServer's thread by default. The request handler may return QFuture<QHttpServerResponse>
if concurrent processing is desired:
server.route("/feature/<arg>", [] (int ms) { return QtConcurrent::run([ms] () { QThread::msleep(ms); return QHttpServerResponse("the future is coming"); }); });
The lambda of the QtConcurrent::run() is executed concurrently, but all the network communication is executed sequentially in the thread the QHttpServer
belongs to after the QFuture is done. Be aware that any QHttpServerRequest object is passed by reference to the callback. Extract all needed content before QtConcurrent::run() is called.
The QHttpServerResponder& special argument is only available for routes returning void
. When using a responder object the response is returned using it.
See also QHttpServerRouter::addRule and addAfterRequestHandler.
template <typename Rule = QHttpServerRouterRule, typename Functor> Rule *QHttpServer::route(const QString &pathPattern, Functor &&handler)
This is an overloaded function.
Overload of QHttpServer::route to create a Rule for pathPattern and QHttpServerRequest::Method::AnyKnown. All requests are forwarded to handler, which can be a function pointer, a non-mutable lambda, or any other copyable callable with const call operator. The rule will be valid until the QHttpServer is destroyed.
template <typename Rule = QHttpServerRouterRule, typename Functor> Rule *QHttpServer::route(const QString &pathPattern, QHttpServerRequest::Methods method, Functor &&handler)
This is an overloaded function.
Overload of QHttpServer::route to create a Rule for pathPattern and method. All requests are forwarded to handler, which can be a function pointer, a non-mutable lambda, or any other copyable callable with const call operator. The rule will be valid until the QHttpServer is destroyed.
template <typename Rule = QHttpServerRouterRule, typename Functor> Rule *QHttpServer::route(const QString &pathPattern, const QObject *context, Functor &&slot)
This is an overloaded function.
Overload of QHttpServer::route to create a Rule for pathPattern and the method QHttpServerRequest::Method::AnyKnown. All requests are forwarded to context and slot.
QHttpServerRouter *QHttpServer::router()
Returns a pointer to the router object.
const QHttpServerRouter *QHttpServer::router() const
Returns a pointer to the constant router object.
template <typename Functor> void QHttpServer::setMissingHandler(const QObject *context, Functor &&slot)
Set a handler for unhandled requests.
All unhandled requests will be forwarded to the context's slot.
The slot has to implement the signature void (*)(const QHttpServerRequest &, QHttpServerResponder &)
. The slot can also be a function pointer, non-mutable lambda, or any other copyable callable with const call operator. In that case the context will be a context object. The handler will be valid until the context object is destroyed.
The default handler replies with status 404 Not Found
.
See also clearMissingHandler.
© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.