diff --git a/src/QHttpEngine/qobjecthandler.h b/src/QHttpEngine/qobjecthandler.h index c3a8ba1..215f62f 100644 --- a/src/QHttpEngine/qobjecthandler.h +++ b/src/QHttpEngine/qobjecthandler.h @@ -77,6 +77,13 @@ protected: */ virtual void process(QHttpSocket *socket, const QString &path); + /** + * @brief Set the status code for the current request + * + * By default, the status code is set to QHttpSocket::OK. + */ + void setStatusCode(int statusCode); + private: QObjectHandlerPrivate *const d; diff --git a/src/qobjecthandler.cpp b/src/qobjecthandler.cpp index 1dca0f7..5072b28 100644 --- a/src/qobjecthandler.cpp +++ b/src/qobjecthandler.cpp @@ -49,6 +49,8 @@ void QObjectHandlerPrivate::invokeSlot(QHttpSocket *socket, int index, const QVa QGenericArgument secondArgument; QVariantMap parameters; + statusCode = QHttpSocket::OK; + // If this is a POST request, then decode the request body if (socket->method() == MethodPOST) { @@ -78,6 +80,7 @@ void QObjectHandlerPrivate::invokeSlot(QHttpSocket *socket, int index, const QVa // Convert the return value to JSON and write it to the socket QByteArray data = QJsonDocument(QJsonObject::fromVariantMap(retVal)).toJson(); + socket->setStatusCode(statusCode); socket->setHeader("Content-Length", QByteArray::number(data.length())); socket->setHeader("Content-Type", "application/json"); socket->write(data); @@ -146,3 +149,8 @@ void QObjectHandler::process(QHttpSocket *socket, const QString &path) }); } } + +void QObjectHandler::setStatusCode(int statusCode) +{ + d->statusCode = statusCode; +} diff --git a/src/qobjecthandler_p.h b/src/qobjecthandler_p.h index 7c6a782..bd5b48a 100644 --- a/src/qobjecthandler_p.h +++ b/src/qobjecthandler_p.h @@ -39,6 +39,8 @@ public: void invokeSlot(QHttpSocket *socket, int index, const QVariantMap &query); QVariantMap convertQueryString(const QString &query); + int statusCode; + private: QObjectHandler *const q; diff --git a/tests/TestQObjectHandler.cpp b/tests/TestQObjectHandler.cpp index e247dbe..c27865a 100644 --- a/tests/TestQObjectHandler.cpp +++ b/tests/TestQObjectHandler.cpp @@ -43,6 +43,10 @@ private Q_SLOTS: QVariantMap get_validSlot(QVariantMap query) { return query; } + QVariantMap get_statusCode(QVariantMap) { + setStatusCode(QHttpSocket::Found); + return QVariantMap(); + } QVariantMap post_validSlot(QVariantMap, QVariantMap params) { return params; } @@ -94,6 +98,13 @@ void TestQObjectHandler::testRequests_data() << QVariantMap({{"param", "value"}}) << static_cast(QHttpSocket::OK); + QTest::newRow("status code") + << QByteArray("GET") + << QByteArray("statusCode") + << QByteArray("") + << QVariantMap() + << static_cast(QHttpSocket::Found); + QTest::newRow("malformed JSON") << QByteArray("POST") << QByteArray("validSlot")