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을 직접 사용하는 경우 핸들러 구문이 다릅니다. 아래 참조).

경로 패턴에 "/" 을 사용하면 규칙이 "/" 뒤에 인수를 사용하여 추가 경로를 일치시킬 수 있습니다. QHttpServer::route() 편의 메서드를 사용하는 경우 인수는 자동으로 람다 함수에 전달됩니다:

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

예를 들어 "/user/1", "/user/2" 등과 같은 요청 경로를 일치시킬 수 있습니다.

경로에서 인자 캡처하기

"<arg>" 자리 표시자를 사용하여 경로 패턴의 어느 곳에나 인수를 배치할 수 있으며, 경로에서 여러 개의 인수가 지원됩니다:

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

예를 들어 "/user/1/history/2" 와 같은 요청과 일치합니다. QHttpServerRouter::converters ()에 등록된 모든 데이터 유형은 콜백 함수와 경로의 해당 플레이스홀더 모두에서 사용할 수 있습니다.

요청 메서드

요청 메서드는 QHttpServerRequest::Method 의 값 중 하나에 해당합니다. 규칙을 구성할 때 메서드를 지정하지 않으면 알려진 메서드의 요청과 일치합니다.

핸들러 서명

핸들러는 다음과 같은 서명을 가진 콜백 함수입니다:

  • 첫 번째 인수는 경로에서 일치하는 모든 캡처 그룹을 받습니다.
  • 두 번째 인수는 요청 세부 정보를 포함합니다.
  • 세 번째 인수는 응답을 전송하는 데 사용됩니다.

QHttpServerRouter에 규칙 추가하기

아래 예는 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"

참고: 이것은 저수준 API입니다. 더 높은 수준의 대안은 QHttpServer 을 참조하세요.

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

멤버 함수 문서

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

pathPatternmethods 에 대한 라우팅 규칙을 생성하여 지정된 receiverslot 에 연결합니다.

  • slot 은 함수 포인터, 변경 불가능한 람다 또는 const 호출 연산자를 사용하는 기타 복사 가능한 호출 가능 객체일 수 있습니다.
  • slot 가 호출 가능한 경우 receiver 이 해당 컨텍스트 객체로 작동합니다.
  • 이 핸들러는 receiver 가 파괴될 때까지 유효합니다.

이 규칙은 사용 가능한 모든 HTTP 메서드 조합을 처리할 수 있습니다.

QHttpServerRequest::Methods참조하세요 .

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

이 오버로드는 pathPattern 에 대한 라우팅 규칙을 구성하고 receiverslot 와 연결합니다.

  • 기본값은 QHttpServerRequest::Method::AnyKnown 이며, 이는 인식된 모든 HTTP 메서드와 일치한다는 의미입니다.
  • slot 은 함수 포인터, 변경 불가능한 람다 또는 const 호출 연산자를 사용하는 기타 복사 가능한 호출 가능 항목일 수 있습니다.
  • slot 가 호출 가능한 경우 receiver 이 해당 컨텍스트 객체로 작동합니다.
  • 이 핸들러는 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)

URL에서 추출한 인수를 사용하여 주어진 receiverslot 을 바인딩합니다. 이 함수는 핸들러에 필요한 나머지 인수를 취하는 바인딩된 콜러블을 반환하여 URL 파생 값 뒤에 slot 에 전달합니다.

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 이 규칙과 일치하는지 확인하여 처리합니다.

  • 이 함수는 request 새 요청이 수신되면 QHttpServerRouter 에서 호출됩니다.
  • request 이 규칙과 일치하면 제공된 responder 을 통해 응답을 전송하여 요청을 처리하고 true 을 반환합니다.
  • 일치하지 않으면 false 을 반환합니다.

[protected] bool QHttpServerRouterRule::hasValidMethods() const

요청 메소드의 유효성을 검사합니다. 지정된 HTTP 메서드가 유효하면 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.