QHttpServerRouterRule Class

QHttp서버라우터규칙은 QHttpServerRouter 규칙의 기본 클래스입니다. 더 보기...

헤더: #include <QHttpServerRouterRule>
CMake: find_package(Qt6 REQUIRED COMPONENTS HttpServer)
target_link_libraries(mytarget PRIVATE Qt6::HttpServer)
qmake: QT += httpserver
이후: 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은 요청 경로, HTTP 요청 메서드 및 각 처리기 콜백 간의 연결을 표현합니다. QHttpServerRouter 은 경로와 요청 메서드가 요청과 일치하는 경우 핸들러가 호출되는 이러한 규칙의 모음입니다. 핸들러 콜백은 요청에 대한 응답을 제공해야 합니다.

경로 및 패턴

모든 QHttp서버라우터규칙에는 처리기를 통해 응답을 제공할 수 있는 경로를 정의하는 경로 또는 경로 패턴이 포함되어 있습니다. 경로에는 규칙의 핸들러로 전달되는 자리 표시자가 포함될 수 있습니다. 다음 경로 패턴의 예는 QHttpServer::route 편의 메서드와 함께 표시되지만 QHttpServerRouterRule 생성자에도 제공될 수 있습니다.

가장 간단한 경우 경로는 선행 "/"가 있는 문자열입니다:

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

이 경로 패턴은 "/user"가 포함된 모든 요청을 제공된 핸들러(이 경우 단순 람다)로 전달하는 규칙을 만듭니다(QHttpServerRouterRule을 직접 사용할 경우 핸들러 구문이 다르게 보입니다. 아래 참조).

경로 패턴에 후행 "/"를 추가하여 후행 "/" 뒤에 인수가 있는 경로 컬렉션을 처리하는 규칙을 만들 수도 있습니다. 인수는 규칙에 QRegularExpressionMatch 로 전달됩니다. QHttpServer::route 편의 메서드를 사용하면 인수가 람다로 직접 전달됩니다:

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

이는 "/user/1", "/user/2" 등의 요청 URL과 일치합니다.

인수는 "<arg>" 자리 표시자를 사용하여 경로 패턴으로 자유롭게 배치할 수 있습니다. 이 키워드는 여러 개의 자리 표시자를 허용합니다.

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

예를 들어 요청 URL "/user/1/history/2"와 일치할 수 있습니다. QHttpServerRouter::converters ()에 등록된 모든 유형은 콜백 및 각 플레이스홀더에 사용할 수 있습니다.

요청 방법

요청 메소드는 QHttpServerRequest::Method 중 하나입니다. 규칙 구성의 오버로드에 메소드가 제공되지 않으면 규칙은 모든 요청 메소드와 일치합니다.

핸들러 서명

핸들러는 서명이 있는 콜백입니다.

핸들러 콜백은 일치하는 모든 자리 표시자를 첫 번째 인수로 받습니다. 두 번째 인수는 요청에 대한 세부 정보를 포함하며 응답은 핸들러가 마지막 인수에 작성해야 합니다.

다음 코드 예제는 각 핸들러를 사용하여 새 규칙을 만들고 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);
        // call viewHandler
        boundViewHandler();
    });

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

// Valid:
route("/user/", [] (qint64 id) { } );                            // "/user/1"
                                                                 // "/user/3"
                                                                 //
route("/user/<arg>/history", [] (qint64 id) { } );               // "/user/1/history"
                                                                 // "/user/2/history"
                                                                 //
route("/user/<arg>/history/", [] (qint64 id, qint64 page) { } ); // "/user/1/history/1"
                                                                 // "/user/2/history/2"

참고: 이것은 낮은 수준의 API이며, 더 높은 수준의 대안은 QHttpServer 을 참조하세요.

참고: 경로 패턴의 정규식은 지원되지 않지만 QHttpServerRouter::addConverter()를 사용하여 "<arg>"의 사용을 특정 유형에 일치시키기 위해 등록할 수 있습니다.

멤버 함수 문서

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

pathPattern, methods 에 대한 규칙을 작성하고 receiverslot 에 연결합니다. slot 은 함수 포인터, 변경 불가능한 람다 또는 const 호출 연산자를 사용하여 복사 가능한 다른 호출 가능 객체일 수도 있습니다. 이 경우 receiver 은 컨텍스트 객체가 됩니다. 핸들러는 수신자 객체가 소멸될 때까지 유효합니다.

이 규칙은 사용 가능한 모든 HTTP 메서드 조합을 허용합니다.

QHttpServerRequest::Methods참조하세요 .

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

이 함수는 과부하된 함수입니다.

pathPattern, QHttpServerRequest::Method::AnyKnown 에 대한 규칙을 작성하고 receiverslot 에 연결합니다. slot 은 함수 포인터, 변경 불가능한 람다 또는 const 호출 연산자를 사용하여 복사 가능한 다른 호출 가능 객체일 수도 있습니다. 이 경우 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)

receiverslot 에 URL에서 파생된 인수를 제공합니다. 핸들러가 취할 수 있는 나머지 인수를 모두 받아들이는 바운드 함수를 반환하여 URL에서 파생된 값 뒤에 있는 슬롯에 인수를 제공합니다. URL에 적용된 정규식의 각 일치 항목(문자열)은 해당 위치에서 핸들러의 매개변수 유형으로 변환되어 match 로 전달될 수 있습니다.

QHttpServerRouter 라우터;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) { // match의 캡처된 문자열과 quint32로 viewHandler를 바인딩하고 호출합니다:    QHttpServerRouterRule::bindCaptured(pageView, match)(); }); router.addRule<ViewHandler>(std::move(rule));

const QObject *QHttpServerRouterRule::contextObject() const

이 규칙의 컨텍스트 객체를 반환합니다. 요청을 처리해야 하는 수신자입니다.

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

주어진 request 에 대해 이 규칙을 실행합니다.

이 함수는 새 요청을 받으면 QHttpServerRouter 에서 호출됩니다. 주어진 request 이 이 규칙과 일치하면 이 함수는 주어진 responder 에 응답을 전달하여 요청을 처리한 다음 true 을 반환합니다. 그렇지 않으면 false 을 반환합니다.

[protected] bool QHttpServerRouterRule::hasValidMethods() const

메서드가 유효한 경우 true 를 반환합니다.

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

주어진 request 이 이 규칙과 일치하는지 여부를 결정합니다.

이 가상 함수는 exec()에 의해 호출되어 request 이 이 규칙과 일치하는지 확인합니다. 일치하는 항목이 발견되면 match ( nullptr아니어야 함)가 가리키는 객체에 저장되고 이 함수는 true 을 반환합니다. 그렇지 않으면 false 을 반환합니다.

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