diff --git a/lib/context.js b/lib/context.js index 1eba80d..dbd796e 100644 --- a/lib/context.js +++ b/lib/context.js @@ -163,31 +163,31 @@ module.exports = { return; } - // content-type already set - if (this.responseHeader['content-type']) return; + // set the content-type only if not yet set + var setType = !this.responseHeader['content-type']; // string if ('string' == typeof val) { - this.type = ~val.indexOf('<') ? 'html' : 'text'; + if (setType) this.type = ~val.indexOf('<') ? 'html' : 'text'; this.length = Buffer.byteLength(val); return; } // buffer if (Buffer.isBuffer(val)) { - this.type = 'bin'; + if (setType) this.type = 'bin'; this.length = val.length; return; } // stream if (val instanceof Stream) { - this.type = 'bin'; + if (setType) this.type = 'bin'; return; } // json - this.type = 'json'; + if (setType) this.type = 'json'; }, /** diff --git a/test/context.js b/test/context.js index 60b121c..5365958 100644 --- a/test/context.js +++ b/test/context.js @@ -29,6 +29,13 @@ describe('ctx.body=', function(){ ctx.body = new Buffer('something'); assert('image/png' == ctx.responseHeader['content-type']); }) + + it('should override length', function(){ + var ctx = context(); + ctx.type = 'html'; + ctx.body = 'something'; + assert.equal(ctx.responseLength, 9); + }) }) describe('when a string is given', function(){ @@ -51,6 +58,21 @@ describe('ctx.body=', function(){ ctx.body = '

Tobi

'; assert('text/html; charset=utf-8' == ctx.responseHeader['content-type']); }) + + it('should set length', function(){ + var string = '

Tobi

'; + var ctx = context(); + ctx.body = string; + assert.equal(ctx.responseLength, Buffer.byteLength(string)); + }) + + it('should set length when body is override', function(){ + var string = '

Tobi

'; + var ctx = context(); + ctx.body = string; + ctx.body = string + string; + assert.equal(ctx.responseLength, 2 * Buffer.byteLength(string)); + }) }) describe('when a stream is given', function(){