Cleanup Http::responseGenerator()

Add CRLF definition
Rewrite loop using iterator, slightly more efficient
Rename variables
This commit is contained in:
Chocobo1 2017-04-13 15:44:48 +08:00
parent 6cb2f05a6c
commit 7d36c81949
2 changed files with 24 additions and 12 deletions

View file

@ -42,9 +42,9 @@ QByteArray Http::toByteArray(Response response)
// Also "Content-Encoding: gzip\r\n" is 26 bytes long
// So we only benefit from gzip if the message is bigger than 23+26 = 49
// If the message is smaller than 49 bytes we actually send MORE data if we gzip
QByteArray dest_buf;
if ((response.content.size() > 49) && (Utils::Gzip::compress(response.content, dest_buf)))
response.content = dest_buf;
QByteArray destBuf;
if ((response.content.size() > 49) && (Utils::Gzip::compress(response.content, destBuf)))
response.content = destBuf;
else
response.headers.remove(HEADER_CONTENT_ENCODING);
}
@ -52,19 +52,28 @@ QByteArray Http::toByteArray(Response response)
response.headers[HEADER_CONTENT_LENGTH] = QString::number(response.content.length());
response.headers[HEADER_DATE] = httpDate();
QString ret(QLatin1String("HTTP/1.1 %1 %2\r\n%3\r\n"));
QByteArray buf;
buf.reserve(10 * 1024);
QString header;
foreach (const QString& key, response.headers.keys())
header += QString("%1: %2\r\n").arg(key).arg(response.headers[key]);
// Status Line
buf += QString("HTTP/%1 %2 %3")
.arg("1.1", // TODO: depends on request
QString::number(response.status.code),
response.status.text)
.toLatin1()
.append(CRLF);
ret = ret.arg(response.status.code).arg(response.status.text).arg(header);
// Header Fields
for (auto i = response.headers.constBegin(); i != response.headers.constEnd(); ++i)
buf += QString("%1: %2").arg(i.key(), i.value()).toLatin1().append(CRLF);
// qDebug() << Q_FUNC_INFO;
// qDebug() << "HTTP Response header:";
// qDebug() << ret;
// the first empty line
buf += CRLF;
return ret.toUtf8() + response.content;
// message body // TODO: support HEAD request
buf += response.content;
return buf;
}
QString Http::httpDate()

View file

@ -56,6 +56,9 @@ namespace Http
const char CONTENT_TYPE_PNG[] = "image/png";
const char CONTENT_TYPE_TXT[] = "text/plain; charset=UTF-8";
// portability: "\r\n" doesn't guarantee mapping to the correct value
const char CRLF[] = {0x0D, 0x0A, '\0'};
struct Environment
{
QHostAddress clientAddress;