Fall back to IPv4 if EAFNOSUPPORT (#24)

If listening to `::` fails, try `0.0.0.0` instead. Addresses #22
This commit is contained in:
Lars Strojny 2022-11-16 22:47:41 +01:00 committed by GitHub
parent f8007b55ca
commit ce8876793d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -26,7 +26,8 @@ function formatCombinedLog(request: FastifyRequest, reply: FastifyReply): string
return `${remoteAddress} - "${request.method} ${request.url} HTTP/${request.raw.httpVersion}" ${reply.statusCode} "${request.protocol}://${request.hostname}" "${userAgent}" "${contentType}"` return `${remoteAddress} - "${request.method} ${request.url} HTTP/${request.raw.httpVersion}" ${reply.statusCode} "${request.protocol}://${request.hostname}" "${userAgent}" "${contentType}"`
} }
function createFastify(server: HttpServer): ReturnType<typeof Fastify> { type FastifyServer = ReturnType<typeof Fastify>
function createFastify(server: HttpServer): FastifyServer {
const config = { logger: false } const config = { logger: false }
if (server.config.tls_cert_file && server.config.tls_key_file) { if (server.config.tls_cert_file && server.config.tls_key_file) {
@ -96,7 +97,7 @@ export const fastifyServe: HttpAdapter = async (server: HttpServer) => {
adaptResponseToReply(server.onMetrics(), reply) adaptResponseToReply(server.onMetrics(), reply)
}) })
await fastify.listen({ port: server.config.port, host: '::' }) await listen(fastify, server.config.port, '::')
return { return {
shutdown() { shutdown() {
@ -104,3 +105,13 @@ export const fastifyServe: HttpAdapter = async (server: HttpServer) => {
}, },
} }
} }
async function listen(fastify: FastifyServer, port: number, host: string): Promise<void> {
try {
await fastify.listen({ port, host })
} catch (e: unknown) {
if (host === '::' && e instanceof Error && (e as Error & { code: string }).code === 'EAFNOSUPPORT') {
await listen(fastify, port, '0.0.0.0')
}
}
}