1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
|
// Copyright (C) 2018 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QHttpServer>
#include <QHttpServerResponse>
#if QT_CONFIG(ssl)
# include <QSslCertificate>
# include <QSslKey>
# include <QSslServer>
#endif
#include <QCoreApplication>
#include <QFile>
#include <QJsonObject>
#include <QString>
#include <QTcpServer>
using namespace Qt::StringLiterals;
static inline QString host(const QHttpServerRequest &request)
{
return QString::fromLatin1(request.value("Host"));
}
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
QHttpServer httpServer;
httpServer.route("/", []() {
return "Hello world";
});
httpServer.route("/query", [] (const QHttpServerRequest &request) {
return host(request) + u"/query/"_s;
});
httpServer.route("/query/", [] (qint32 id, const QHttpServerRequest &request) {
return u"%1/query/%2"_s.arg(host(request)).arg(id);
});
httpServer.route("/query/<arg>/log", [] (qint32 id, const QHttpServerRequest &request) {
return u"%1/query/%2/log"_s.arg(host(request)).arg(id);
});
httpServer.route("/query/<arg>/log/", [] (qint32 id, float threshold,
const QHttpServerRequest &request) {
return u"%1/query/%2/log/%3"_s.arg(host(request)).arg(id).arg(threshold);
});
httpServer.route("/user/", [] (const qint32 id) {
return u"User "_s + QString::number(id);
});
httpServer.route("/user/<arg>/detail", [] (const qint32 id) {
return u"User %1 detail"_s.arg(id);
});
httpServer.route("/user/<arg>/detail/", [] (const qint32 id, const qint32 year) {
return u"User %1 detail year - %2"_s.arg(id).arg(year);
});
httpServer.route("/json/", [] {
return QJsonObject{
{
{"key1", "1"},
{"key2", "2"},
{"key3", "3"}
}
};
});
httpServer.route("/assets/<arg>", [] (const QUrl &url) {
return QHttpServerResponse::fromFile(u":/assets/"_s + url.path());
});
httpServer.route("/remote_address", [](const QHttpServerRequest &request) {
return request.remoteAddress().toString();
});
// Basic authentication example (RFC 7617)
httpServer.route("/auth", [](const QHttpServerRequest &request) {
auto auth = request.value("authorization").simplified();
if (auth.size() > 6 && auth.first(6).toLower() == "basic ") {
auto token = auth.sliced(6);
auto userPass = QByteArray::fromBase64(token);
if (auto colon = userPass.indexOf(':'); colon > 0) {
auto userId = userPass.first(colon);
auto password = userPass.sliced(colon + 1);
if (userId == "Aladdin" && password == "open sesame")
return QHttpServerResponse("text/plain", "Success\n");
}
}
QHttpServerResponse resp("text/plain", "Authentication required\n",
QHttpServerResponse::StatusCode::Unauthorized);
auto h = resp.headers();
h.append(QHttpHeaders::WellKnownHeader::WWWAuthenticate,
R"(Basic realm="Simple example", charset="UTF-8")");
resp.setHeaders(std::move(h));
return std::move(resp);
});
//! [Using addAfterRequestHandler()]
httpServer.addAfterRequestHandler(&httpServer, [](const QHttpServerRequest &, QHttpServerResponse &resp) {
auto h = resp.headers();
h.append(QHttpHeaders::WellKnownHeader::Server, "Qt HTTP Server");
resp.setHeaders(std::move(h));
});
//! [Using addAfterRequestHandler()]
auto tcpserver = std::make_unique<QTcpServer>();
if (!tcpserver->listen() || !httpServer.bind(tcpserver.get())) {
qWarning() << QCoreApplication::translate("QHttpServerExample",
"Server failed to listen on a port.");
return -1;
}
quint16 port = tcpserver->serverPort();
tcpserver.release();
#if QT_CONFIG(ssl)
//! [HTTPS Configuration example]
QSslConfiguration conf = QSslConfiguration::defaultConfiguration();
const auto sslCertificateChain =
QSslCertificate::fromPath(QStringLiteral(":/assets/certificate.crt"));
if (sslCertificateChain.empty()) {
qWarning() << QCoreApplication::translate("QHttpServerExample",
"Couldn't retrieve SSL certificate from file.");
return -1;
}
QFile privateKeyFile(QStringLiteral(":/assets/private.key"));
if (!privateKeyFile.open(QIODevice::ReadOnly)) {
qWarning() << QCoreApplication::translate("QHttpServerExample",
"Couldn't open file for reading: %1")
.arg(privateKeyFile.errorString());
return -1;
}
conf.setLocalCertificate(sslCertificateChain.front());
conf.setPrivateKey(QSslKey(&privateKeyFile, QSsl::Rsa));
privateKeyFile.close();
auto sslserver = std::make_unique<QSslServer>();
sslserver->setSslConfiguration(conf);
if (!sslserver->listen() || !httpServer.bind(sslserver.get())) {
qWarning() << QCoreApplication::translate("QHttpServerExample",
"Server failed to listen on a port.");
return -1;
}
quint16 sslPort = sslserver->serverPort();
sslserver.release();
//! [HTTPS Configuration example]
qInfo().noquote()
<< QCoreApplication::translate("QHttpServerExample",
"Running on http://127.0.0.1:%1/ and "
"https://127.0.0.1:%2/ (Press CTRL+C to quit)")
.arg(port).arg(sslPort);
#else
qInfo().noquote()
<< QCoreApplication::translate("QHttpServerExample",
"Running on http://127.0.0.1:%1/"
"(Press CTRL+C to quit)").arg(port);
#endif
return app.exec();
}
|