Add res.append(field, val) to append headers

master
dead_horse 2015-01-26 01:53:55 +08:00
parent ceacafeb81
commit 5a3f32dfdd
5 changed files with 74 additions and 0 deletions

View File

@ -190,6 +190,7 @@ koa uses [http-assert](https://github.com/jshttp/http-assert) for assertions.
- `ctx.redirect()`
- `ctx.attachment()`
- `ctx.set()`
- `ctx.append()`
- `ctx.remove()`
- `ctx.lastModified=`
- `ctx.etag=`

View File

@ -151,6 +151,13 @@ var etag = this.get('ETag');
this.set('Cache-Control', 'no-cache');
```
### response.append(field, value)
Append additional header `field` with value `val`.
```js
this.append('Link', '<http://127.0.0.1/>');
```
### response.set(fields)
Set several response header `fields` with an object:

View File

@ -147,6 +147,7 @@ delegate(proto, 'response')
.method('remove')
.method('vary')
.method('set')
.method('append')
.access('status')
.access('message')
.access('body')

View File

@ -424,6 +424,33 @@ module.exports = {
}
},
/**
* Append additional header `field` with value `val`.
*
* Examples:
*
* this.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);
* this.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');
* this.append('Warning', '199 Miscellaneous warning');
*
* @param {String} field
* @param {String|Array} val
* @api public
*/
append: function(field, val){
var prev = this.get(field);
var value = val;
if (prev) {
// concat the new and prev vals
value = Array.isArray(prev) ? prev.concat(val)
: Array.isArray(val) ? [prev].concat(val)
: [prev, val];
}
return this.set(field, value);
},
/**
* Remove header `field`.
*

38
test/response/append.js Normal file
View File

@ -0,0 +1,38 @@
var context = require('../context');
describe('ctx.append(name, val)', function(){
it('should append multiple headers', function(){
var ctx = context();
ctx.append('x-foo', 'bar1');
ctx.append('x-foo', 'bar2');
ctx.response.header['x-foo'].should.eql(['bar1', 'bar2']);
})
it('should accept array of values', function (){
var ctx = context();
ctx.append('Set-Cookie', ['foo=bar', 'fizz=buzz']);
ctx.response.header['set-cookie'].should.eql(['foo=bar', 'fizz=buzz']);
})
it('should get reset by res.set(field, val)', function (){
var ctx = context();
ctx.append('Link', '<http://localhost/>');
ctx.append('Link', '<http://localhost:80/>');
ctx.set('Link', '<http://127.0.0.1/>');
ctx.response.header.link.should.equal('<http://127.0.0.1/>');
})
it('should work with res.set(field, val) first', function (){
var ctx = context();
ctx.set('Link', '<http://localhost/>');
ctx.append('Link', '<http://localhost:80/>');
ctx.response.header.link.should.eql(['<http://localhost/>', '<http://localhost:80/>']);
})
})