- Qt 6.10
- Qt HTTP Server
- C++ Classes
- QHttpServerRouter
- Qt 6.10.2 Reference Documentation

# QHttpServerRouter Class

Provides functions to bind a path to a `ViewHandler`. More...

Header: | `#include <QHttpServerRouter>`
CMake: | `find_package(Qt6 REQUIRED COMPONENTS HttpServer)` `target_link_libraries(mytarget PRIVATE Qt6::HttpServer)`
qmake: | `QT += httpserver`
Since: | Qt 6.4

- List of all members, including inherited members

## Public Functions

| QHttpServerRouter(QAbstractHttpServer *server)
| ~QHttpServerRouter()
bool | addConverter(QAnyStringView regexp)
void | addConverter(QMetaType metaType, QAnyStringView regexp)
QHttpServerRouterRule * | addRule(std::unique_ptr<QHttpServerRouterRule> rule)
void | clearConverters()
QHash<QMetaType, QString> | converters() &&
const QHash<QMetaType, QString> & | converters() const &
bool | handleRequest(const QHttpServerRequest &request, QHttpServerResponder &responder) const
void | removeConverter(QMetaType metaType)

## Detailed Description

QHttpServerRouter is a rule-based system for routing HTTP requests to their appropriate handlers. You can add QHttpServerRouterRule instances, which define a request path and its corresponding handler.

Variable parts in the route can be specified with placeholders (`"<arg>"`) in the request path, but it is not needed at the end. The handler receives the matched values as a QRegularExpressionMatch. The arguments can be of any type for which a converter is available. The handler creation can be simplified with QHttpServerRouterRule::bindCaptured().

Note: A QHttpServerRouter instance must not be modifed by its rules.

Note: This is a low-level routing API for an HTTP server.

Minimal example:

     auto pageView = [] (const quint64 page) {
         qDebug() << "page" << page;
     };
     using ViewHandler = decltype(pageView);

     QHttpServerRouter router;

     // register callback pageView on request "/page/<number>"
     // for example: "/page/10", "/page/15"
     router.addRule<ViewHandler>(
         new QHttpServerRouterRule("/page/", [=] (QRegularExpressionMatch &match,
                                                  const QHttpServerRequest &,
                                                  QHttpServerResponder &&) {
         auto boundView = QHttpServerRouterRule::bindCaptured(pageView, match);

         // it calls pageView
         boundView();
     }));

## Member Function Documentation

### QHash<QMetaType, QString> QHttpServerRouter::converters() &&

### const QHash<QMetaType, QString> &QHttpServerRouter::converters() const &

Returns a map of converter types and regular expressions that are registered with this QHttpServerRouter. These are the types that can be used in path patterns of QHttpServerRouterRules.

The following converters are available by default:

Constant | Description
--- | ---
`QMetaType::Int` |
`QMetaType::Long` |
`QMetaType::LongLong` |
`QMetaType::Short` |
`QMetaType::UInt` |
`QMetaType::ULong` |
`QMetaType::ULongLong` |
`QMetaType::UShort` |
`QMetaType::Double` |
`QMetaType::Float` |
`QMetaType::QString` |
`QMetaType::QByteArray` |
`QMetaType::QUrl` |
`QMetaType::Void` | An empty converter.

See also addConverter and clearConverters.

### QHttpServerRouter::QHttpServerRouter(QAbstractHttpServer *server)

Creates a QHttpServerRouter object with default converters.

See also converters.

### `[noexcept]` QHttpServerRouter::~QHttpServerRouter()

Destroys a QHttpServerRouter.

### template <typename Type> bool QHttpServerRouter::addConverter(QAnyStringView regexp)

Adds a new converter for Type that can be parsed with regexp, and returns `true` if this was successful, otherwise returns `false`. If successful, the registered type can be used as argument in handlers for QHttpServerRouterRule. The regular expression will be used to parse the path pattern of the rule.

If there is already a converter of type Type, that converter's regexp is replaced with regexp.

Custom converters can extend the available type conversions through the QMetaType system.

Define a class with a QString constructor:

     struct CustomArg {
         int data = 10;

         CustomArg() {} ;
         CustomArg(const QString &urlArg) : data(urlArg.toInt()) {}
     };

To use a custom type with the HTTP server, register it using this function and define a route handler using the new type:

     server.router()->addConverter<CustomArg>(u"[+-]?\\d+");
     server.route("/customTest/<arg>", [] (const CustomArg custom) { return QString::number(custom.data); });

See also converters and clearConverters.

### void QHttpServerRouter::addConverter(QMetaType metaType, QAnyStringView regexp)

Adds a new converter for metaType that can be parsed with regexp. Having a converter for a metaType enables to use this type in a path pattern of a QHttpServerRouterRule. The regular expression is used to parse parameters of type metaType from the path pattern.

If there is already a converter of type metaType, that converter's regexp is replaced with regexp.

See also converters and clearConverters.

### template <typename ViewHandler, typename ViewTraits = QHttpServerRouterViewTraits<ViewHandler>> QHttpServerRouterRule *QHttpServerRouter::addRule(std::unique_ptr<QHttpServerRouterRule> rule)

Adds a new rule to the router.

Returns a pointer to the new rule if successful; otherwise returns `nullptr`.

Inside addRule, we determine ViewHandler arguments and generate a list of their QMetaType::Type ids. Then we parse the path and replace each `"<arg>"` with a regexp for its type from the list.

The provided rule must not modify the QHttpServerRouter instance.

     QHttpServerRouter router;

     using ViewHandler = decltype([] (const QString &page, const quint32 num) { });

     auto rule = std::make_unique<QHttpServerRouterRule>(
         "/<arg>/<arg>/log",
         [] (QRegularExpressionMatch &match,
             const QHttpServerRequest &request,
             QHttpServerResponder &&responder) {
     });

     router.addRule<ViewHandler>(std::move(rule));

### void QHttpServerRouter::clearConverters()

Removes all converters.

Note: clearConverters() does not set up default converters.

See also converters and addConverter.

### bool QHttpServerRouter::handleRequest(const QHttpServerRequest &request, QHttpServerResponder &responder) const

Handles each new request for the HTTP server using responder.

Iterates through the list of rules to find the first that matches, then executes this rule, returning `true`. Returns `false` if no rule matches the request.

### void QHttpServerRouter::removeConverter(QMetaType metaType)

Removes the converter for type metaType.

See also addConverter.