Skip to content

ConnInfo 助手

ConnInfo 助手用于获取连接信息,例如客户端的远程地址等。

导入

ts
import { Hono } from 'hono'
import { getConnInfo } from 'hono/cloudflare-workers'
ts
import { Hono } from 'hono'
import { getConnInfo } from 'hono/deno'
ts
import { Hono } from 'hono'
import { getConnInfo } from 'hono/bun'
ts
import { Hono } from 'hono'
import { getConnInfo } from 'hono/vercel'
ts
import { Hono } from 'hono'
import { getConnInfo } from 'hono/lambda-edge'
ts
import { Hono } from 'hono'
import { getConnInfo } from '@hono/node-server/conninfo'

用法

ts
const app = new Hono()

app.get('/', (c) => {
  const info = getConnInfo(c) // info 类型为 `ConnInfo`
  return c.text(`Your remote address is ${info.remote.address}`)
})

类型定义

getConnInfo() 返回值的类型定义如下:

ts
type AddressType = 'IPv6' | 'IPv4' | undefined

type NetAddrInfo = {
  /**
   * 传输协议类型
   */
  transport?: 'tcp' | 'udp'
  /**
   * 传输端口号
   */
  port?: number

  address?: string
  addressType?: AddressType
} & (
  | {
      /**
       * 主机名(如 IP 地址)
       */
      address: string

      /**
       * 主机名类型
       */
      addressType: AddressType
    }
  | {}
)

/**
 * HTTP 连接信息
 */
interface ConnInfo {
  /**
   * 远端信息
   */
  remote: NetAddrInfo
}

Released under the MIT License.