Skip to content

Commit

Permalink
Avoid using chunked encoding for HTTPServerResponse.writeJsonBody by …
Browse files Browse the repository at this point in the history
…default. Fixes #619.
  • Loading branch information
s-ludwig committed Jul 30, 2014
1 parent b85fe2e commit 0ecd891
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 13 deletions.
13 changes: 1 addition & 12 deletions source/vibe/db/redis/redis.d
Expand Up @@ -841,6 +841,7 @@ private final class RedisConnection {
{
static if (is(ARG == string)) return arg.length;
else {
import vibe.internal.rangeutil;
long length;
auto rangeCnt = RangeCounter(&length);
rangeCnt.formattedWrite("%s", arg);
Expand All @@ -849,18 +850,6 @@ private final class RedisConnection {
}
}

private struct RangeCounter {
import std.utf;
long* length;

this(long* _captureLength) {
length = _captureLength;
}

void put(dchar ch) { *length += codeLength!char(ch); }
void put(string str) { *length += str.length; }
}

private void _request_void(ARGS...)(RedisConnection conn, string command, ARGS args)
{
import vibe.stream.wrapper;
Expand Down
12 changes: 11 additions & 1 deletion source/vibe/http/server.d
Expand Up @@ -815,7 +815,7 @@ final class HTTPServerResponse : HTTPResponse {
}

/// Writes a JSON message with the specified status
void writeJsonBody(T)(T data, int status = HTTPStatus.OK, string content_type = "application/json; charset=UTF-8")
void writeJsonBody(T)(T data, int status = HTTPStatus.OK, string content_type = "application/json; charset=UTF-8", bool allow_chunked = false)
{
import std.traits;
import vibe.stream.wrapper;
Expand All @@ -826,6 +826,16 @@ final class HTTPServerResponse : HTTPResponse {

statusCode = status;
headers["Content-Type"] = content_type;

// set an explicit content-length field if chunked encoding is not allowed
if (!allow_chunked) {
import vibe.internal.rangeutil;
long length = 0;
auto counter = RangeCounter(&length);
serializeToJson(counter, data);
headers["Content-Length"] = formatAlloc(m_requestAlloc, "%d", length);
}

auto rng = StreamOutputRange(bodyWriter);
serializeToJson(&rng, data);
}
Expand Down
13 changes: 13 additions & 0 deletions source/vibe/internal/rangeutil.d
@@ -0,0 +1,13 @@
module vibe.internal.rangeutil;

struct RangeCounter {
import std.utf;
long* length;

this(long* _captureLength) {
length = _captureLength;
}

void put(dchar ch) { *length += codeLength!char(ch); }
void put(string str) { *length += str.length; }
}

0 comments on commit 0ecd891

Please sign in to comment.