Skip to content

Commit

Permalink
tmp
Browse files Browse the repository at this point in the history
  • Loading branch information
fengmk2 committed Nov 25, 2015
1 parent 9f80296 commit fa63e25
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 2 deletions.
3 changes: 3 additions & 0 deletions lib/application.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ var Stream = require('stream');
var http = require('http');
var only = require('only');
var co = require('co');
var destroy = require('destroy');

/**
* Application prototype.
Expand Down Expand Up @@ -198,11 +199,13 @@ function respond() {
if (statuses.empty[code]) {
// strip headers
this.body = null;
if (body instanceof Stream) destroy(body);
return res.end();
}

if ('HEAD' == this.method) {
if (isJSON(body)) this.length = Buffer.byteLength(JSON.stringify(body));
if (body instanceof Stream) destroy(body);
return res.end();
}

Expand Down
17 changes: 15 additions & 2 deletions lib/response.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ var destroy = require('destroy');
var assert = require('assert');
var path = require('path');
var vary = require('vary');
var Stream = require('stream');
var extname = path.extname;

/**
Expand Down Expand Up @@ -161,8 +162,20 @@ module.exports = {
}

// stream
if ('function' == typeof val.pipe) {
onFinish(this.res, destroy.bind(null, val));
if (val instanceof Stream) {
if (original instanceof Stream) {
// same stream, do nothing
if (original === val) return;

// destroy original stream
destroy(original);
}

onFinish(this.res, function(err) {
if (err) {
destroy(val);
}
});
ensureErrorHandler(val, this.ctx.onerror);

// overwriting
Expand Down
31 changes: 31 additions & 0 deletions test/application.js
Original file line number Diff line number Diff line change
Expand Up @@ -856,6 +856,20 @@ describe('app.respond', function(){
.expect(204, done);
})

it('should destroy stream when HEAD request', function(done){
var app = koa();

app.use(function *(){
this.body = fs.createReadStream(__filename);
});

var server = app.listen();

request(server)
.head('/')
.expect('')
.expect(200, done);
})

it('should handle all intermediate stream body errors', function(done){
var app = koa();
Expand All @@ -872,6 +886,23 @@ describe('app.respond', function(){
.get('/')
.expect(404, done);
})

it('should ignore set same stream', function(done){
var app = koa();

app.use(function *(){
var stream = fs.createReadStream(__filename);
this.body = stream;
this.body = stream;
this.body = stream;
});

var server = app.listen();

request(server)
.get('/')
.expect(200, done);
})
})

describe('when .body is an Object', function(){
Expand Down

0 comments on commit fa63e25

Please sign in to comment.