이 페이지에서

QHttpServerRouterRule Class

QHttpServerRouterRule은 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 은 이러한 규칙들의 모음으로, 요청이 경로와 메서드 모두에 일치할 때 적절한 핸들러를 실행합니다. 핸들러는 응답을 생성하는 역할을 담당합니다.

경로 및 패턴

각 QHttpServerRouterRule에는 처리할 수 있는 요청을 결정하는 경로 또는 패턴이 포함됩니다. 경로에는 핸들러로 전달되는 자리 표시자가 포함될 수 있습니다. 아래 예제는 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)

pathPattern 및 methods 에 대한 라우팅 규칙을 생성하여, 이를 지정된 receiver 및 slot 에 연결합니다.

  • slot 는 함수 포인터, 변경 불가능한 람다, 또는 const 호출 연산자를 갖는 복사 가능한 호출 가능 객체일 수 있습니다.
  • slot 가 호출 가능한 경우, receiver 는 해당 컨텍스트 객체 역할을 합니다.
  • receiver 가 소멸될 때까지 핸들러는 유효한 상태를 유지합니다.

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

QHttpServerRequest::Methods도 참조하십시오 .

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

이 오버로드는 pathPattern 에 대한 라우팅 규칙을 생성하고, 이를 receiver 및 slot 에 연결합니다.

  • 기본값은 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)

지정된 receiver 및 slot 를 URL에서 추출한 인자와 바인딩합니다. 이 함수는 핸들러에 필요한 나머지 인자를 모두 받아, URL에서 파생된 값 다음에 slot 에 전달하는 바인딩된 호출 가능 객체를 반환합니다.

URL에서 캡처된 각 값(문자열 형식)은 위치에 따라 핸들러 내의 해당 매개변수 유형으로 변환되며, 이를 통해 ` 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) {
    // 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 을 반환합니다.

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