QHttpServerRouter Class
Oferece funções para associar um caminho a um ` ViewHandler`. Mais...
| Cabeçalho: | #include <QHttpServerRouter> |
| CMake: | find_package(Qt6 REQUIRED COMPONENTS HttpServer) target_link_libraries(mytarget PRIVATE Qt6::HttpServer) |
| qmake: | QT += httpserver |
| Desde: | Qt 6.4 |
Funções públicas
| 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) |
Descrição detalhada
O QHttpServerRouter é um sistema baseado em regras para direcionar solicitações HTTP aos manipuladores apropriados. É possível adicionar instâncias d QHttpServerRouterRule, que definem um caminho de solicitação e seu manipulador correspondente.
As partes variáveis na rota podem ser especificadas com placeholders ("<arg>") no caminho da solicitação, mas isso não é necessário no final. O manipulador recebe os valores correspondentes como um objeto ` QRegularExpressionMatch`. Os argumentos podem ser de qualquer tipo para o qual um ` converter ` esteja disponível. A criação do manipulador pode ser simplificada com ` QHttpServerRouterRule::bindCaptured()`.
Observação: uma instância de `QHttpServerRouter` não deve ser modificada por suas regras.
Observação: Esta é uma API de roteamento de baixo nível para um servidor HTTP.
Exemplo mínimo:
auto pageView = [] (const quint64 página) {
qDebug() << "page" << page;
};
using ViewHandler = decltype(pageView);
QHttpServerRouter router;
// registra o callback pageView na solicitação "/page/<número>"
// por exemplo: "/page/10", "/page/15"
router.addRule<ViewHandler>(
new QHttpServerRouterRule("/page/", [=] (QRegularExpressionMatch&match,
const QHttpServerRequest&,
QHttpServerResponder&&) {
auto boundView = QHttpServerRouterRule::bindCaptured(pageView, match);
// chama pageView
boundView();
}));Documentação da função membro
QHttpServerRouter::QHttpServerRouter(QAbstractHttpServer *server)
Cria um objeto QHttpServerRouter com conversores padrão.
Veja também converters.
[noexcept] QHttpServerRouter::~QHttpServerRouter()
Destrói um ` QHttpServerRouter`.
template <typename Type> bool QHttpServerRouter::addConverter(QAnyStringView regexp)
Adiciona um novo conversor para o tipo “Type” que pode ser analisado com regexp e retorna true caso a análise seja bem-sucedida; caso contrário, retorna false. Se for bem-sucedido, o tipo registrado pode ser usado como argumento nos manipuladores de QHttpServerRouterRule. A expressão regular será usada para analisar o padrão de caminho da regra.
Se já houver um conversor do tipo `Type`, a expressão regular desse conversor será substituída por ` regexp`.
Conversores personalizados podem ampliar as conversões de tipo disponíveis por meio do sistema QMetaType.
Defina uma classe com um construtor ` QString `:
struct CustomArg {
int data = 10;
CustomArg() {} ;
CustomArg(const QString &urlArg) : data(urlArg.toInt()) {}
};Para usar um tipo personalizado com o ` HTTP server`, registre-o usando esta função e defina um manipulador ` route ` usando o novo tipo:
server.router()->addConverter<CustomArg>(u"[+-]?\\d+");
server.route("/customTest/<arg>", [] (const CustomArg custom) { return QString::number(custom.data); });Veja também ` converters ` e ` clearConverters`.
void QHttpServerRouter::addConverter(QMetaType metaType, QAnyStringView regexp)
Adiciona um novo conversor para metaType que pode ser analisado com regexp. Ter um conversor para metaType permite usar esse tipo em um padrão de caminho de QHttpServerRouterRule. A expressão regular é usada para analisar parâmetros do tipo metaType a partir do padrão de caminho.
Se já houver um conversor do tipo metaType, a expressão regular desse conversor será substituída por regexp.
Veja também converters e clearConverters.
template <typename ViewHandler, typename ViewTraits = QHttpServerRouterViewTraits<ViewHandler>> QHttpServerRouterRule *QHttpServerRouter::addRule(std::unique_ptr<QHttpServerRouterRule> rule)
Adiciona uma nova regra de rule ao roteador.
Retorna um ponteiro para a nova regra se for bem-sucedido; caso contrário, retorna ` nullptr`.
Dentro do método `addRule`, determinamos os argumentos do `ViewHandler` e geramos uma lista dos IDs de ` QMetaType::Type ` correspondentes. Em seguida, analisamos o caminho e substituímos cada ` "<arg>" ` por uma expressão regular correspondente ao seu tipo na lista.
O ` rule ` fornecido não deve modificar a instância de ` QHttpServerRouter `.
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()
Remove todos os conversores.
Observação: clearConverters () não configura conversores padrão.
Veja também converters e addConverter.
QHash<QMetaType, QString> QHttpServerRouter::converters() &&
const QHash<QMetaType, QString> &QHttpServerRouter::converters() const &
Retorna um mapa com os tipos de conversores e as expressões regulares registradas neste ` QHttpServerRouter`. Esses são os tipos que podem ser usados nos padrões de caminho de ` QHttpServerRouterRules`.
Os seguintes conversores estão disponíveis por padrão:
| Constante | Descrição |
|---|---|
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 | Um conversor vazio. |
Veja também addConverter e clearConverters.
bool QHttpServerRouter::handleRequest(const QHttpServerRequest &request, QHttpServerResponder &responder) const
Processa cada novo ` request ` para o servidor HTTP utilizando ` responder`.
Percorre a lista de regras para encontrar a primeira que corresponda e, em seguida, executa essa regra, retornando true. Retorna false se nenhuma regra corresponder à solicitação.
void QHttpServerRouter::removeConverter(QMetaType metaType)
Remove o conversor para o tipo metaType.
Veja também addConverter.
© 2026 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.