response.body: fix html content sniffing for strings

closes #214
This commit is contained in:
Jonathan Ong 2014-02-13 18:35:25 -08:00
parent abb5686d5b
commit c7ff0e2ac1
2 changed files with 32 additions and 1 deletions

View file

@ -120,7 +120,7 @@ module.exports = {
// string // string
if ('string' == typeof val) { if ('string' == typeof val) {
if (setType) this.type = ~val.indexOf('<') ? 'html' : 'text'; if (setType) this.type = /^\s*</.test(val) ? 'html' : 'text';
this.length = Buffer.byteLength(val); this.length = Buffer.byteLength(val);
return; return;
} }

View file

@ -44,6 +44,14 @@ describe('res.body=', function(){
res.body = 'Tobi'; res.body = 'Tobi';
assert('4' == res.header['content-length']); assert('4' == res.header['content-length']);
}) })
describe('and contains a non-leading <', function(){
it('should default to text', function(){
var res = response();
res.body = 'aklsdjf < klajsdlfjasd';
assert('text/plain; charset=utf-8' == res.header['content-type']);
})
})
}) })
describe('when an html string is given', function(){ describe('when an html string is given', function(){
@ -67,6 +75,29 @@ describe('res.body=', function(){
res.body = string + string; res.body = string + string;
assert.equal(res.length, 2 * Buffer.byteLength(string)); assert.equal(res.length, 2 * Buffer.byteLength(string));
}) })
describe('when it contains leading whitespace', function(){
it('should default to html', function(){
var res = response();
res.body = ' <h1>Tobi</h1>';
assert('text/html; charset=utf-8' == res.header['content-type']);
})
})
})
describe('when an xml string is given', function(){
it('should default to html', function(){
/**
* This test is to show that we're not going
* to be stricter with the html sniff
* or that we will sniff other string types.
* You should `.type=` if this simple test fails.
*/
var res = response();
res.body = '<?xml version="1.0" encoding="UTF-8"?>\n<俄语>данные</俄语>';
assert('text/html; charset=utf-8' == res.header['content-type']);
})
}) })
describe('when a stream is given', function(){ describe('when a stream is given', function(){