Skip to content
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
6 changes: 5 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -350,7 +350,11 @@ async function fastifyStatic (fastify, opts) {
break
}
case 'file': {
reply.code(statusCode)
// reply.raw.statusCode by default 200
// when ever the user changed it, we respect the status code
// otherwise use send provided status code
const newStatusCode = reply.statusCode !== 200 ? reply.statusCode : statusCode
reply.code(newStatusCode)
if (setHeaders !== undefined) {
setHeaders(reply.raw, metadata.path, metadata.stat)
}
Expand Down
38 changes: 38 additions & 0 deletions test/static.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4023,3 +4023,41 @@ t.test('content-length in head route should not return zero when using wildcard'
})
})
})

t.test('respect the .code when using with sendFile', t => {
t.plan(6)

const pluginOptions = {
root: path.join(__dirname, '/static')
}
const fastify = Fastify()

fastify.register(fastifyStatic, pluginOptions)

fastify.get('/custom', (_, reply) => {
return reply.code(404).type('text/html').sendFile('foo.html')
})

t.teardown(fastify.close.bind(fastify))

fastify.listen({ port: 0 }, err => {
t.error(err)

fastify.server.unref()

const file = fs.readFileSync(path.join(__dirname, '/static/foo.html'))
const contentLength = Buffer.byteLength(file).toString()

simple.concat({
method: 'HEAD',
url: 'http://localhost:' + fastify.server.address().port + '/custom',
followRedirect: false
}, (err, response, body) => {
t.error(err)
t.equal(response.statusCode, 404)
t.equal(response.headers['content-type'], 'text/html; charset=UTF-8')
t.equal(response.headers['content-length'], contentLength)
t.equal(body.toString(), '')
})
})
})