-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttpserver.cpp
More file actions
60 lines (51 loc) · 1.99 KB
/
httpserver.cpp
File metadata and controls
60 lines (51 loc) · 1.99 KB
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
#include <QFile>
#include <QMimeDatabase>
#include <QDebug>
//own
#include "httpserver.h"
AHttpServer::AHttpServer(QObject *parent)
: QTcpServer(parent)
{
}
void AHttpServer::incomingConnection(qintptr socketDescriptor) {
QTcpSocket *socket = new QTcpSocket(this);
connect(socket, &QTcpSocket::readyRead, this, [this, socket]() {
handleRequest(socket);
});
connect(socket, &QTcpSocket::disconnected, socket, &QTcpSocket::deleteLater);
socket->setSocketDescriptor(socketDescriptor);
}
void AHttpServer::handleRequest(QTcpSocket *socket) {
QByteArray request = socket->readAll();
QStringList tokens = QString(request).split(QRegularExpression("[ \r\n][ \r\n]*"));
if (tokens.size() < 2) return;
QString method = tokens[0];
QString path = tokens[1];
if (path == "/" || path == "/index.html") {
serveFile(socket, ":/web_content/index.html", "text/html");
} else {
serveFile(socket, ":/web_content" + path, "");
}
}
void AHttpServer::serveFile(QTcpSocket *socket, const QString &filePath, const QString &contentType) {
QFile file(filePath);
if (file.open(QIODevice::ReadOnly)) {
QByteArray content = file.readAll();
QMimeDatabase mimeDb;
QString mimeType = contentType.isEmpty() ?
mimeDb.mimeTypeForFile(filePath).name() : contentType;
QByteArray response = "HTTP/1.1 200 OK\r\n";
response += "Content-Type: " + mimeType.toUtf8() + "\r\n";
response += "Content-Length: " + QByteArray::number(content.size()) + "\r\n";
response += "Connection: close\r\n\r\n";
response += content;
socket->write(response);
} else {
QByteArray response = "HTTP/1.1 404 Not Found\r\n"
"Content-Type: text/plain\r\n"
"Connection: close\r\n\r\n"
"File not found: " + filePath.toUtf8();
socket->write(response);
}
socket->disconnectFromHost();
}