Skip to content

Commit

Permalink
fix(serve): support ipv6 by default (#206)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
sinasab authored Oct 10, 2024
1 parent 74e86a2 commit 2357641
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
Expand Down
18 changes: 17 additions & 1 deletion test/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down Expand Up @@ -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)
})
})

0 comments on commit 2357641

Please sign in to comment.