In questa pagina

QHttpServerRouter Class

Fornisce funzioni per associare un percorso a un elemento di tipo “ ViewHandler ”. Altro...

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

Funzioni pubbliche

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)

Descrizione dettagliata

QHttpServerRouter è un sistema basato su regole che indirizza le richieste HTTP agli handler appropriati. È possibile aggiungere istanze di ` QHttpServerRouterRule `, che definiscono un percorso di richiesta e il relativo handler.

Le parti variabili nel percorso possono essere specificate con segnaposto ("<arg>") nel percorso della richiesta, ma non è necessario inserirli alla fine. Il gestore riceve i valori corrispondenti come QRegularExpressionMatch. Gli argomenti possono essere di qualsiasi tipo per cui sia disponibile un converter. La creazione del gestore può essere semplificata con QHttpServerRouterRule::bindCaptured().

Nota: un'istanza di `QHttpServerRouter` non deve essere modificata dalle sue regole.

Nota: Si tratta di un’API di routing di basso livello per un server HTTP.

Esempio minimale:

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

QHttpServerRouter router;

// registra la callback pageView sulla richiesta "/page/<numero>"
// ad esempio: "/page/10", "/page/15"
router.addRule<ViewHandler>(
    new QHttpServerRouterRule("/page/", [=] (QRegularExpressionMatch&match,
                                             const QHttpServerRequest&,
                                             QHttpServerResponder&&) {
    auto boundView = QHttpServerRouterRule::bindCaptured(pageView, match);

    // chiama pageView
    boundView();
}));

Documentazione delle funzioni membro

QHttpServerRouter::QHttpServerRouter(QAbstractHttpServer *server)

Crea un oggetto QHttpServerRouter con i convertitori predefiniti.

Vedi anche converters.

[noexcept] QHttpServerRouter::~QHttpServerRouter()

Elimina un QHttpServerRouter.

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

Aggiunge un nuovo convertitore per il tipo “Type” che può essere analizzato con “ regexp ” e restituisce “ true ” in caso di esito positivo, altrimenti restituisce “ false ”. In caso di esito positivo, il tipo registrato può essere utilizzato come argomento negli handler per “ QHttpServerRouterRule ”. L’espressione regolare verrà utilizzata per analizzare il modello di percorso della regola.

Se esiste già un convertitore di tipo Type, l’espressione regolare di quel convertitore viene sostituita con regexp.

I convertitori personalizzati possono estendere le conversioni di tipo disponibili tramite il sistema QMetaType.

Definire una classe con un costruttore ` QString `:

struct CustomArg {
    int data = 10;

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

Per utilizzare un tipo personalizzato con l’ HTTP server, registrarlo utilizzando questa funzione e definire un gestore route utilizzando il nuovo tipo:

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

Vedi anche converters e clearConverters.

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

Aggiunge un nuovo convertitore per metaType che può essere analizzato con regexp. La presenza di un convertitore per metaType consente di utilizzare questo tipo in un pattern di percorso di QHttpServerRouterRule. L'espressione regolare viene utilizzata per analizzare i parametri di tipo metaType dal pattern di percorso.

Se è già presente un convertitore di tipo metaType, l'espressione regolare di quel convertitore viene sostituita con regexp.

Vedi anche converters e clearConverters.

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

Aggiunge una nuova regola di tipo " rule " al router.

Restituisce un puntatore alla nuova regola in caso di esito positivo; altrimenti restituisce ` nullptr`.

All’interno di `addRule`, determiniamo gli argomenti di `ViewHandler` e generiamo un elenco dei relativi ID ` QMetaType::Type `. Quindi analizziamo il percorso e sostituiamo ogni ` "<arg>" ` con un’espressione regolare corrispondente al suo tipo presente nell’elenco.

L’ rule fornito non deve modificare l’istanza di 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()

Rimuove tutti i convertitori.

Nota: clearConverters () non configura i convertitori predefiniti.

Vedi anche converters e addConverter.

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

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

Restituisce una mappa dei tipi di convertitori e delle espressioni regolari registrati in questo QHttpServerRouter. Questi sono i tipi che possono essere utilizzati nei modelli di percorso di QHttpServerRouterRules.

I seguenti convertitori sono disponibili per impostazione predefinita:

CostanteDescrizione
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::VoidUn convertitore vuoto.

Vedi anche addConverter e clearConverters.

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

Gestisce ogni nuovo request per il server HTTP utilizzando responder.

Esamina l'elenco delle regole per individuare la prima che corrisponde, quindi esegue tale regola, restituendo true. Restituisce false se nessuna regola corrisponde alla richiesta.

void QHttpServerRouter::removeConverter(QMetaType metaType)

Rimuove il convertitore per il tipo metaType.

Vedi anche 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.