From 04f4d72692a5132d026debc79fe080e56c13aebe Mon Sep 17 00:00:00 2001 From: TJ Holowaychuk Date: Sat, 14 Sep 2013 14:48:33 -0700 Subject: [PATCH] add charset support to ctx.type= --- docs/api.md | 6 +++++- lib/context.js | 7 ++++++- test/application.js | 2 +- 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/docs/api.md b/docs/api.md index 2657061..68b926a 100644 --- a/docs/api.md +++ b/docs/api.md @@ -275,12 +275,16 @@ var ct = this.type; Set response `Content-Type` via mime string or file extension. ```js +this.type = 'text/plain; charset=utf-8'; this.type = 'image/png'; this.type = '.png'; this.type = 'png'; ``` - __NOTE__: when `ctx.body` is an object the content-type is set for you. + Note: when appropriate a `charset` is selected for you, for + example `ctx.type = 'html'` will default to "utf-8", however + when explicitly defined in full as `ctx.type = 'text/html'` + no charset is assigned. ### ctx.url diff --git a/lib/context.js b/lib/context.js index ef0de98..fcf882a 100644 --- a/lib/context.js +++ b/lib/context.js @@ -743,7 +743,12 @@ module.exports = { */ set type(type){ - if (!~type.indexOf('/')) type = mime.lookup(type); + if (!~type.indexOf('/')) { + type = mime.lookup(type); + var cs = mime.charsets.lookup(type); + if (cs) type += '; charset=' + cs.toLowerCase(); + } + this.set('Content-Type', type); }, diff --git a/test/application.js b/test/application.js index 73b336b..57ff6ca 100644 --- a/test/application.js +++ b/test/application.js @@ -177,7 +177,7 @@ describe('app.respond', function(){ request(server) .get('/') - .expect('Content-Type', 'text/plain') + .expect('Content-Type', 'text/plain; charset=utf-8') .expect(404) .end(done); })