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 *receiver, Functor &&slot)
void clearMissingHandler()
Rule *route(const QString &pathPattern, QHttpServerRequest::Methods method, const QObject *receiver, 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 *receiver, Functor &&slot)
QHttpServerRouter *router()
const QHttpServerRouter *router() const
void setMissingHandler(const QObject *receiver, Functor &&slot)

Detailed Description

QHttpServer allows to create a simple Http server by setting a range of request handlers.

The route function can be used to conveniently add rules to the servers QHttpServerRouter. To register a handler to be called after every request use addAfterRequestHandler and 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.get())) {
    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 *receiver, Functor &&slot)

Register a receiver and slot to be called after every 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 copiable callable with const call operator. In that case the receiver will be a context object and the handler will be valid until the context object is destroyed.

Example:

QHttpServer server;
server.addAfterRequestHandler(&server, [] (const QHttpServerRequest &req, QHttpServerResponse &resp) {
    resp.write(req.body(), "text/plain"_ba);
}

Note: These handlers won't be called for requests, processed by handlers with QHttpServerResponder& argument.

void QHttpServer::clearMissingHandler()

Resets the handler to the default one that produces replies with status 404 Not Found.

template <typename Rule = QHttpServerRouterRule, typename Functor> Rule *QHttpServer::route(const QString &pathPattern, QHttpServerRequest::Methods method, const QObject *receiver, Functor &&slot)

This is a convenience method to add a new Rule to the server's QHttpServerRouter. The Rule template parameter can be any custom class derived from QHttpServerRouterRule.

This function takes a pathPattern and a method that represent a set of requests and creates a new QHttpServerRouterRule (or custom Rule if specified in the template parameters) that forwards all respective requests to the provided receiver and slot. The rule is added to the router. For details on valid patterns in pathPattern, see the QHttpServerRouterRule documentation.

slot can be a member function pointer of receiver. It can also be a function pointer, a non-mutable lambda, or any other copiable callable with const call operator. In that case receiver has to be a QObject pointer. The rule will be valid for the lifetime duration of the receiver. The receiver 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. 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 last function argument QHttpServerResponder& can be provided on which the response has to be written. If the response is written to a QHttpServerResponder& the function must return void.

server.route("/test2", this, [] (QHttpServerResponder &responder) {
                                responder.write(QHttpServerResponder::StatusCode::Forbidden); });

The slot can further have a const QHttpServerRequest& as a second to last parameter to get detailed information on the request

server.route("/test3", this, [] (const QHttpServerRequest &request,
                                QHttpServerResponder &responder) {
                                responder.write(req.body(), "text/plain"_ba);});

Finally, the callback can contain an arbitrary amount of copiable parameters that are registered with the QHttpServerRouter::converters. By default, these are most integer types, float, double, QString, QByteArray, and QUrl. Additional converters can be registered, see QHttpServerRouter::addConverter. These parameters must have a corresponding placeholder in the pathPattern. For details on placeholders and pathPattern see QHttpServerRouterRule.

QHttpServer server;
server.route("/test/<arg>", this, [] (const int page) { return ""; });

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>("/test", this, [] () {return "";});
rule->setParameter("test");

. This function must not be called from any route callback.

Note: If a request was processed by a handler 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 asynchronous processing is desired:

server.route("/feature/", [] (int id) {
    return QtConcurrent::run([] () {
        return QHttpServerResponse("the future is coming");
    });
});

The body of QFuture is executed asynchronously, but all the network communication is executed sequentially in the thread the QHttpServer belongs to. The QHttpServerResponder& special argument is not available for routes returning a QFuture.

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 copiable 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 copiable 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 *receiver, Functor &&slot)

This is an overloaded function.

Overload of QHttpServer::route to create a Rule for pathPattern and QHttpServerRequest::Method::AnyKnown. All requests are forwarded to receiver 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 *receiver, Functor &&slot)

Set a handler for unhandled requests.

All unhandled requests will be forwarded to the receiver'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 copiable callable with const call operator. In that case the receiver will be a context object. The handler will be valid until the receiver object is destroyed.

The default handler replies with status 404: Not Found.

© 2024 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.