From 2357641a95d688721376da77055ed14e712a9b09 Mon Sep 17 00:00:00 2001 From: sina Date: Thu, 10 Oct 2024 13:30:35 -0700 Subject: [PATCH] fix(serve): support ipv6 by default (#206) * fix(serve): support ipv6 by default For node's server.listen, if no hostname param is specified it'll adaptively pick the unspecified ipv6 address (`::`) when available or the unspecified ipv4 address (`0.0.0.0`) otherwise. This fix gets rid of the behavior where we manually default to `0.0.0.0` and rely on node's underlying handling of this. See here for the docs on node: https://nodejs.org/api/net.html#serverlistenport-host-backlog-callback:~:text=If%20host%20is%20omitted%2C%20the%20server%20will%20accept%20connections%20on%20the%20unspecified%20IPv6%20address%20(%3A%3A)%20when%20IPv6%20is%20available%2C%20or%20the%20unspecified%20IPv4%20address%20(0.0.0.0)%20otherwise. * format --- src/server.ts | 2 +- test/server.test.ts | 18 +++++++++++++++++- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/src/server.ts b/src/server.ts index c02fcc8..8148f8f 100644 --- a/src/server.ts +++ b/src/server.ts @@ -21,7 +21,7 @@ export const serve = ( listeningListener?: (info: AddressInfo) => void ): ServerType => { const server = createAdaptorServer(options) - server.listen(options?.port ?? 3000, options.hostname ?? '0.0.0.0', () => { + server.listen(options?.port ?? 3000, options.hostname, () => { const serverInfo = server.address() as AddressInfo listeningListener && listeningListener(serverInfo) }) diff --git a/test/server.test.ts b/test/server.test.ts index d1cce78..d4e6f82 100644 --- a/test/server.test.ts +++ b/test/server.test.ts @@ -11,7 +11,7 @@ import { createServer as createHttp2Server } from 'node:http2' import { createServer as createHTTPSServer } from 'node:https' import { GlobalRequest, Request as LightweightRequest, getAbortController } from '../src/request' import { GlobalResponse, Response as LightweightResponse } from '../src/response' -import { createAdaptorServer } from '../src/server' +import { createAdaptorServer, serve } from '../src/server' import type { HttpBindings } from '../src/types' describe('Basic', () => { @@ -908,3 +908,19 @@ describe('Memory leak test', () => { expect(counter).toBe(0) }) }) + +describe('serve', () => { + const app = new Hono() + app.get('/', (c) => c.newResponse(null, 200)) + serve(app) + + it('should serve on ipv4', async () => { + const response = await fetch('http://localhost:3000') + expect(response.status).toBe(200) + }) + + it('should serve on ipv6', async () => { + const response = await fetch('http://[::1]:3000') + expect(response.status).toBe(200) + }) +})