Enable gzip compression in the webui.

This commit is contained in:
sledgehammer999
2013-10-21 00:04:32 +03:00
parent 6598b3266c
commit ec31081927
5 changed files with 101 additions and 3 deletions

View File

@@ -30,6 +30,7 @@
#include "httpresponsegenerator.h"
#include <zlib.h>
void HttpResponseGenerator::setMessage(const QByteArray& message)
{
@@ -64,3 +65,66 @@ void HttpResponseGenerator::setContentTypeByExt(const QString& ext) {
return;
}
}
bool HttpResponseGenerator::gCompress(QByteArray &dest_buffer) {
static const int BUFSIZE = 128 * 1024;
char tmp_buf[BUFSIZE];
int ret;
z_stream strm;
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
strm.next_in = reinterpret_cast<unsigned char*>(m_message.data());
strm.avail_in = m_message.length();
strm.next_out = reinterpret_cast<unsigned char*>(tmp_buf);
strm.avail_out = BUFSIZE;
//windowBits = 15|32 to enable gzip
ret = deflateInit2(&strm, Z_BEST_COMPRESSION, Z_DEFLATED, 15|16, 8, Z_DEFAULT_STRATEGY);
if (ret != Z_OK)
return false;
while (strm.avail_in != 0)
{
ret = deflate(&strm, Z_NO_FLUSH);
if (ret != Z_OK)
return false;
if (strm.avail_out == 0)
{
dest_buffer.append(tmp_buf, BUFSIZE);
strm.next_out = reinterpret_cast<unsigned char*>(tmp_buf);
strm.avail_out = BUFSIZE;
}
}
int deflate_res = Z_OK;
while (deflate_res == Z_OK) {
if (strm.avail_out == 0) {
dest_buffer.append(tmp_buf, BUFSIZE);
strm.next_out = reinterpret_cast<unsigned char*>(tmp_buf);
strm.avail_out = BUFSIZE;
}
deflate_res = deflate(&strm, Z_FINISH);
}
if (deflate_res != Z_STREAM_END)
return false;
dest_buffer.append(tmp_buf, BUFSIZE);
deflateEnd(&strm);
return true;
}
QByteArray HttpResponseGenerator::toByteArray() {
if (m_gzip) {
QByteArray dest_buf;
if (gCompress(dest_buf)) {
setValue("Content-Encoding", "gzip");
m_message.swap(dest_buf);
}
}
return QHttpResponseHeader::toString().toUtf8() + m_message;
}