From 7d36c81949f7c03daa34753aef914ec3936f046e Mon Sep 17 00:00:00 2001 From: Chocobo1 Date: Thu, 13 Apr 2017 15:44:48 +0800 Subject: [PATCH] Cleanup Http::responseGenerator() Add CRLF definition Rewrite loop using iterator, slightly more efficient Rename variables --- src/base/http/responsegenerator.cpp | 33 ++++++++++++++++++----------- src/base/http/types.h | 3 +++ 2 files changed, 24 insertions(+), 12 deletions(-) diff --git a/src/base/http/responsegenerator.cpp b/src/base/http/responsegenerator.cpp index 6b08b5803..e63c2fbcf 100644 --- a/src/base/http/responsegenerator.cpp +++ b/src/base/http/responsegenerator.cpp @@ -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() diff --git a/src/base/http/types.h b/src/base/http/types.h index cdaaaf87b..1fb52fd32 100644 --- a/src/base/http/types.h +++ b/src/base/http/types.h @@ -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;