Skip to content

Commit

Permalink
Merge e98270f into d452501
Browse files Browse the repository at this point in the history
  • Loading branch information
lemiffe committed Nov 9, 2015
2 parents d452501 + e98270f commit 54905f1
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 1 deletion.
8 changes: 8 additions & 0 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,14 @@ app.use(function *(){
app.use(function *(){
yield send(this, 'path/to/my.js');
})
```

To serve files with custom headers:

```js
app.use(function *(){
yield send(this, 'path/to/my.js', {'headers': {'Content-Type': 'text/plain'}});
})
```

## Example
Expand Down
14 changes: 13 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@ function send(ctx, path, opts) {
var hidden = opts.hidden || false;
var format = opts.format === false ? false : true;
var gzip = opts.gzip === false ? false : true;
var headers = [];
if (opts.hasOwnProperty('headers')) {
headers = Object.keys(opts.headers);
}

var encoding = ctx.acceptsEncodings('gzip', 'deflate', 'identity');

Expand Down Expand Up @@ -94,10 +98,18 @@ function send(ctx, path, opts) {
throw err;
}

// stream
// Set default headers
ctx.set('Last-Modified', stats.mtime.toUTCString());
ctx.set('Content-Length', stats.size);
ctx.set('Cache-Control', 'max-age=' + (maxage / 1000 | 0));

// Set optional headers
headers.forEach(function(key) {
if (opts.headers.hasOwnProperty(key)) {
ctx.set(key, opts.headers[key]);
}
});

ctx.type = type(path);
ctx.body = fs.createReadStream(path);

Expand Down
13 changes: 13 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -441,6 +441,19 @@ describe('send(ctx, file)', function(){
.end(done);
})

it('should set a custom header', function(done){
var app = koa();

app.use(function *(){
yield send(this, '/test/fixtures/user.json', {'headers': {'X-XSS-Protection': '1; mode=block'}});
});

request(app.listen())
.get('/')
.expect('X-XSS-Protection', '1; mode=block')
.end(done);
})

it('should set the Content-Length', function(done){
var app = koa();

Expand Down

0 comments on commit 54905f1

Please sign in to comment.