QHttpServerRouterRule Class

The QHttpServerRouterRule is the base class for QHttpServerRouter 规则。 更多...

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

公共函数

QHttpServerRouterRule (const QString & pathPattern , const QHttpServerRequest::Methods methods , const QObject * receiver , Functor && slot )
QHttpServerRouterRule (const QString & pathPattern , const QObject * receiver , Functor && slot )
virtual ~QHttpServerRouterRule ()
const QObject * contextObject () const

静态公共成员

typename ViewTraits::BindableType bindCaptured (QObject * receiver , Functor && slot , const QRegularExpressionMatch & match )

保护函数

bool exec (const QHttpServerRequest & request , QHttpServerResponder & responder ) const
bool hasValidMethods () const
virtual bool matches (const QHttpServerRequest & request , QRegularExpressionMatch * match ) const

详细描述

QHttpServerRouterRule defines the relationship between a request path, an HTTP method, and the corresponding handler callback. A QHttpServerRouter is a collection of these rules, executing the appropriate handler when a request matches both the path and method. The handler is responsible for generating the response.

Paths and Patterns

Each QHttpServerRouterRule includes a path or pattern that determines which requests it can handle. Paths may contain placeholders that are passed to the handler. The examples below illustrate path patterns using the QHttpServer::route () convenience method, though they can also be set using the QHttpServerRouterRule constructor.

In the simplest case the path is a string with a leading "/" :

QHttpServer server;
server.route("/user", [] () { return "hello user"; } );
					

This path pattern defines a rule that directs all requests to "/user" to the specified handler, which in this case is a simple lambda function. (Note that when using QHttpServerRouterRule directly, the handler syntax differs—see below.)

A trailing "/" in the path pattern allows the rule to match additional paths with arguments after the "/" . When using the QHttpServer::route () convenience method, the argument is automatically passed to the lambda function:

server.route("/user/", [] ( qint64 id ) { return "hello user"; } );
					

This would match request paths such as "/user/1" , "/user/2" , and so on.

Capturing Arguments in the Path

You can place arguments anywhere in the path pattern using the "<arg>" placeholders, and multiple of them are supported in the path:

server.route("/user/<arg>/history", [] (qint64 id){ return "hello user"; } );
server.route("/user/<arg>/history/", [] (qint64 id, qint64 page){ return "hello user"; } );
					

For example, this would match a request like "/user/1/history/2" . Any data type registered in QHttpServerRouter::converters () can be used in both the callback function and the corresponding placeholders in the path.

Request Method

The request method corresponds to one of the values in QHttpServerRequest::Method . If no method is specified when constructing a rule, it will match requests of any known method.

Handler Signature

A handler is a callback function with the following signature:

void (*)(const QRegularExpressionMatch &, const QHttpServerRequest &, QHttpServerResponder &);
					
  • The first argument receives any matched capture groups from the path.
  • The second argument contains request details.
  • The third argument is used to send the response.

Adding Rules to QHttpServerRouter

The example below demonstrates how to create and register a new rule with a handler in QHttpServerRouter :

template<typename ViewHandler>
void route(const char *path, const QHttpServerRequest::Methods methods, ViewHandler &&viewHandler)
{
    auto rule = std::make_unique<QHttpServerRouterRule>(
            path, methods, [this, viewHandler = std::forward<ViewHandler>(viewHandler)]
                                            (QRegularExpressionMatch &match,
                                             const QHttpServerRequest &request,
                                             QHttpServerResponder &responder) mutable {
        auto boundViewHandler = QHttpServerRouterRule::bindCaptured<ViewHandler>(
                this, std::move(viewHandler), match);
        boundViewHandler(); // Execute the handler
    });
    // Add rule to the router
    router.addRule<ViewHandler>(std::move(rule));
}
// Valid:
route("/user/", [] (qint64 id) { } );                            // Matches "/user/1", "/user/3", etc.
route("/user/<arg>/history", [] (qint64 id) { } );               // Matches "/user/1/history", "/user/2/history"
route("/user/<arg>/history/", [] (qint64 id, qint64 page) { } ); // Matches "/user/1/history/1", "/user/2/history/2"
					

注意: This is a low-level API. For higher-level alternatives, see QHttpServer .

注意: Regular expressions are not supported in path patterns, but you can use QHttpServerRouter::addConverter () to match "<arg>" to a specific type.

成员函数文档编制

template <typename Functor> QHttpServerRouterRule:: QHttpServerRouterRule (const QString & pathPattern , const QHttpServerRequest::Methods methods , const QObject * receiver , Functor && slot )

Creates a routing rule for pathPattern and methods , connecting it to the specified receiver and slot .

  • The slot can be a function pointer, non-mutable lambda, or any other copyable callable with const call operator.
  • slot is callable, receiver acts as its context object.
  • The handler remains valid until the receiver 被销毁。

The rule can handle any combination of available HTTP methods.

另请参阅 QHttpServerRequest::Methods .

template <typename Functor> QHttpServerRouterRule:: QHttpServerRouterRule (const QString & pathPattern , const QObject * receiver , Functor && slot )

This overload constructs a routing rule for pathPattern and associates it with receiver and slot .

  • It defaults to QHttpServerRequest::Method::AnyKnown , meaning it will match any recognized HTTP method.
  • The slot can be a function pointer, non-mutable lambda, or any other copyable callable with const call operator.
  • slot is callable, receiver acts as its context object.
  • The handler remains valid until the receiver 被销毁。

这是重载函数。

[virtual noexcept] QHttpServerRouterRule:: ~QHttpServerRouterRule ()

销毁 QHttpServerRouterRule .

[static] template <typename Functor, typename ViewTraits = QHttpServerRouterViewTraits<Functor>> typename ViewTraits::BindableType QHttpServerRouterRule:: bindCaptured ( QObject * receiver , Functor && slot , const QRegularExpressionMatch & match )

Binds the given receiver and slot with arguments extracted from the URL. The function returns a bound callable that takes any remaining arguments required by the handler, supplying them to slot after the URL-derived values.

Each captured value from the URL (as a string) is converted to the corresponding parameter type in the handler based on its position, ensuring it can be passed as match .

QHttpServerRouter router;
auto pageView = [] (const QString &page, const quint32 num) {
    qDebug("page: %s, num: %d", qPrintable(page), num);
};
using ViewHandler = decltype(pageView);
auto rule = std::make_unique<QHttpServerRouterRule>(
    "/<arg>/<arg>/log",
    [&router, &pageView] (QRegularExpressionMatch &match,
                          const QHttpServerRequest &request,
                          QHttpServerResponder &&responder) {
    // Bind and call viewHandler with match's captured string and quint32:
    QHttpServerRouterRule::bindCaptured(pageView, match)();
});
router.addRule<ViewHandler>(std::move(rule));
					

const QObject *QHttpServerRouterRule:: contextObject () const

Retrieves the context object associated with this rule. This object serves as the receiver responsible for handling the request.

[protected] bool QHttpServerRouterRule:: exec (const QHttpServerRequest & request , QHttpServerResponder & responder ) const

Executes the rule. Processes the given request by checking if it matches this rule.

  • 此函数被调用通过 QHttpServerRouter when a new request is received.
  • request matches the rule, it handles the request by sending a response through the provided responder 并返回 true .
  • If there is no match, it returns false .

[protected] bool QHttpServerRouterRule:: hasValidMethods () const

Validates the Request Method. Returns true if the specified HTTP method is valid.

[virtual protected] bool QHttpServerRouterRule:: 匹配 (const QHttpServerRequest & request , QRegularExpressionMatch * match ) const

Determines whether the provided request meets the conditions of this rule.

  • 此虚函数被调用由 exec () to evaluate the request .
  • If the request matches, the details are stored in match (which 不必 be nullptr ), and the function returns true .
  • Otherwise, it returns false .