Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: conninfo returns server IP #216

Merged
merged 2 commits into from
Nov 11, 2024
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
18 changes: 6 additions & 12 deletions src/conninfo.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import type { GetConnInfo } from 'hono/conninfo'
import type { AddressInfo } from 'net'
import type { HttpBindings } from './types'

/**
Expand All @@ -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,
},
}
}
19 changes: 8 additions & 11 deletions test/conninfo.test.ts
Original file line number Diff line number Diff line change
@@ -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 (
Expand All @@ -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)
})
Expand Down