Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support asterisk in accept-encoding header #7

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ Currently the following headers are supported:
- `'deflate'`
- `'gzip'`
- `'br'`
- `'*'`

If the `'accept-encoding'` header specifies no preferred encoding with an asterisk `*` the payload will be compressed with `gzip`.

If an unsupported encoding is received, it will automatically return a `406` error, if the `'accept-encoding'` header is missing, it will return a `400` error.

Expand Down
3 changes: 3 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,9 @@ function getEncodingHeader (request) {
if (supportedEncodings.indexOf(acceptEncodings[i]) > -1) {
return acceptEncodings[i]
}
if (acceptEncodings[i].indexOf('*') > -1) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this can be faster.
If a user puts * as accepted encodings, there will not be other stuff there.
if so, we can just check it the header value is equal to *.

Does it make sense?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, we cannot do that. Something like 'gzip;q=1.0, *;q=0.5' is valid and might occur. This would mean use gzip if possible and else use any other encoding.

return 'gzip'
}
}
return null
}
Expand Down
23 changes: 23 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,29 @@ test('should send a gzipped data', t => {
})
})

test('should send a gzipped data for * header', t => {
t.plan(2)
const fastify = Fastify()
fastify.register(compressPlugin, { global: false })

fastify.get('/', (req, reply) => {
reply.type('text/plain').compress(createReadStream('./package.json'))
})

fastify.inject({
url: '/',
method: 'GET',
headers: {
'accept-encoding': '*'
}
}, res => {
t.strictEqual(res.headers['content-encoding'], 'gzip')
const file = readFileSync('./package.json', 'utf8')
const payload = zlib.gunzipSync(res.rawPayload)
t.strictEqual(payload.toString('utf-8'), file)
})
})

test('should send a brotli data', t => {
t.plan(2)
const fastify = Fastify()
Expand Down