跳至內容

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 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 許可下發布。