diff --git a/src/conninfo.ts b/src/conninfo.ts index eccb662..b396fb9 100644 --- a/src/conninfo.ts +++ b/src/conninfo.ts @@ -1,5 +1,4 @@ import type { GetConnInfo } from 'hono/conninfo' -import type { AddressInfo } from 'net' import type { HttpBindings } from './types' /** @@ -10,20 +9,15 @@ import type { HttpBindings } from './types' export const getConnInfo: GetConnInfo = (c) => { const bindings = (c.env.server ? c.env.server : c.env) as HttpBindings - const address = bindings.incoming.socket.address() as AddressInfo - - if (!('address' in address)) { - return { - remote: {}, - } - } + const address = bindings.incoming.socket.remoteAddress + const port = bindings.incoming.socket.remotePort + const family = bindings.incoming.socket.remoteFamily return { remote: { - address: address.address, - addressType: - address.family === 'IPv4' ? 'IPv4' : address.family === 'IPv6' ? 'IPv6' : 'unknown', - port: address.port, + address, + port, + addressType: family === 'IPv4' ? 'IPv4' : family === 'IPv6' ? 'IPv6' : void 0, }, } } diff --git a/test/conninfo.test.ts b/test/conninfo.test.ts index 02b8038..090ebef 100644 --- a/test/conninfo.test.ts +++ b/test/conninfo.test.ts @@ -1,16 +1,15 @@ import { Hono } from 'hono' import type { AddressType, ConnInfo } from 'hono/conninfo' -import type { AddressInfo } from 'net' import { getConnInfo } from '../src/conninfo' describe('ConnInfo', () => { it('Should works', async () => { const app = new Hono().get('/', (c) => c.json(getConnInfo(c))) - const address: AddressInfo = { - address: '0.0.0.0', - family: 'IPv4', - port: 3030, + const socket = { + remoteAddress: '0.0.0.0', + remoteFamily: 'IPv4', + remotePort: 3030, } expect( await ( @@ -19,18 +18,16 @@ describe('ConnInfo', () => { {}, { incoming: { - socket: { - address: () => address, - }, + socket, }, } ) ).json() ).toEqual({ remote: { - address: address.address, - addressType: address.family as AddressType, - port: address.port, + address: socket.remoteAddress, + addressType: socket.remoteFamily as AddressType, + port: socket.remotePort, }, } satisfies ConnInfo) })