跳转到正文

ConnInfo 辅助工具 ​

ConnInfo 辅助工具用于获取连接信息。例如,可以轻松获取客户端的远程地址。

导入 ​

各运行时的适配器都是独立的软件包(@hono/cloudflare-workers、@hono/deno、@hono/bun 等)。请安装与你的运行时对应的软件包。

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/aws-lambda'
ts
import { Hono } from 'hono'
import { getConnInfo } from '@hono/netlify'
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 is `ConnInfo`
  return c.text(`Your remote address is ${info.remote.address}`)
})

类型定义 ​

通过 getConnInfo() 获取的值的类型定义如下:

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

type NetAddrInfo = {
  /**
   * Transport protocol type
   */
  transport?: 'tcp' | 'udp'
  /**
   * Transport port number
   */
  port?: number

  address?: string
  addressType?: AddressType
} & (
  | {
      /**
       * Host name such as IP Addr
       */
      address: string

      /**
       * Host name type
       */
      addressType: AddressType
    }
  | {}
)

/**
 * HTTP Connection information
 */
interface ConnInfo {
  /**
   * Remote information
   */
  remote: NetAddrInfo
}

基于 MIT 许可证发布。