Skip to content

Commit

Permalink
fix content-type header for precompressed assets (#204)
Browse files Browse the repository at this point in the history
  • Loading branch information
dwickern committed May 17, 2021
1 parent ef4d1e1 commit 6068477
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
13 changes: 13 additions & 0 deletions index.js
Expand Up @@ -124,6 +124,7 @@ async function fastifyStatic (fastify, opts) {
} else {
wrap.on('pipe', function () {
if (encodingExt) {
reply.header('content-type', getContentType(pathname))
reply.header('content-encoding', encodingExt)
}
reply.send(wrap)
Expand Down Expand Up @@ -376,6 +377,18 @@ function checkPath (fastify, rootPath) {

const supportedEncodings = ['br', 'gzip', 'deflate']

function getContentType (path) {
const type = send.mime.lookup(path)
if (!type) {
return
}
const charset = send.mime.charsets.lookup(type)
if (!charset) {
return type
}
return `${type}; charset=${charset}`
}

// Adapted from https://github.com/fastify/fastify-compress/blob/fa5c12a5394285c86d9f438cb39ff44f3d5cde79/index.js#L442
function checkEncodingHeaders (headers, checked) {
if (!('accept-encoding' in headers)) return
Expand Down
7 changes: 7 additions & 0 deletions test/static.test.js
Expand Up @@ -2911,6 +2911,7 @@ t.test(
}
})

genericResponseChecks(t, response)
t.equal(response.headers['content-encoding'], 'br')
t.equal(response.statusCode, 200)
t.same(response.rawPayload, allThreeBr)
Expand Down Expand Up @@ -2940,6 +2941,7 @@ t.test(
}
})

genericResponseChecks(t, response)
t.equal(response.headers['content-encoding'], 'gz')
t.equal(response.statusCode, 200)
t.same(response.rawPayload, gzipOnly)
Expand Down Expand Up @@ -2969,6 +2971,7 @@ t.test(
}
})

genericResponseChecks(t, response)
t.equal(response.headers['content-encoding'], undefined)
t.equal(response.statusCode, 200)
t.equal(response.body, uncompressedStatic)
Expand Down Expand Up @@ -2999,6 +3002,7 @@ t.test(
}
})

genericResponseChecks(t, response)
t.equal(response.headers['content-encoding'], 'br')
t.equal(response.statusCode, 200)
t.same(response.rawPayload, allThreeBr)
Expand Down Expand Up @@ -3029,6 +3033,7 @@ t.test(
}
})

genericResponseChecks(t, response)
t.equal(response.headers['content-encoding'], 'gz')
t.equal(response.statusCode, 200)
t.same(response.rawPayload, gzipOnly)
Expand Down Expand Up @@ -3059,6 +3064,7 @@ t.test(
}
})

genericResponseChecks(t, response)
t.equal(response.headers['content-encoding'], undefined)
t.equal(response.statusCode, 200)
t.equal(response.body, uncompressedStatic)
Expand All @@ -3085,6 +3091,7 @@ t.test(
url: '/static-pre-compressed/uncompressed.html'
})

genericResponseChecks(t, response)
t.equal(response.headers['content-encoding'], undefined)
t.equal(response.statusCode, 200)
t.equal(response.body, uncompressedStatic)
Expand Down

0 comments on commit 6068477

Please sign in to comment.