Skip to content

服务器计时中间件

🌐 Server-Timing Middleware

Server-Timing 中间件在响应头中提供性能指标。

🌐 The Server-Timing Middleware provides performance metrics in the response headers.

INFO

注意:在 Cloudflare Workers 上,计时器指标可能不准确,因为计时器只显示最后一次 I/O 的时间

导入

🌐 Import

npm
ts
import { Hono } from 'hono'
import {
  timing,
  setMetric,
  startTime,
  endTime,
  wrapTime,
} from 'hono/timing'
import type { TimingVariables } from 'hono/timing'

用法

🌐 Usage

js
// Specify the variable types to infer the `c.get('metric')`:
type Variables = TimingVariables

const app = new Hono<{ Variables: Variables }>()

// add the middleware to your router
app.use(timing());

app.get('/', async (c) => {

  // add custom metrics
  setMetric(c, 'region', 'europe-west3')

  // add custom metrics with timing, must be in milliseconds
  setMetric(c, 'custom', 23.8, 'My custom Metric')

  // start a new timer
  startTime(c, 'db');
  const data = await db.findMany(...);

  // end the timer
  endTime(c, 'db');

  // ...or you can also just wrap a Promise using this function:
  const data = await wrapTime(c, 'db', db.findMany(...));

  return c.json({ response: data });
});

有条件启用

🌐 Conditionally enabled

ts
const app = new Hono()

app.use(
  '*',
  timing({
    // c: Context of the request
    enabled: (c) => c.req.method === 'POST',
  })
)

结果

🌐 Result

选项

🌐 Options

optional 总计: boolean

显示总响应时间。默认值是 true

🌐 Show the total response time. The default is true.

optional 已启用:boolean | (c: Context) => boolean

是否应该将时间添加到标题中。默认值是 true

🌐 Whether timings should be added to the headers or not. The default is true.

optional 总描述: boolean

总响应时间的说明。默认值是 Total Response Time

🌐 Description for the total response time. The default is Total Response Time.

optional 自动结束: boolean

如果 startTime() 应在请求结束时自动结束。 如果禁用,则未手动结束的计时器将不会显示。

🌐 If startTime() should end automatically at the end of the request. If disabled, not manually ended timers will not be shown.

optional crossOrigin: boolean | string | (c: Context) => boolean | string

此计时标头的来源应可读。

🌐 The origin this timings header should be readable.

  • 如果为 false,则仅来自当前来源。
  • 如果为真,则来自所有来源。
  • 如果是字符串,来自这个域名(多个域名必须用逗号分隔)。

默认值是 false。查看更多 文档

🌐 The default is false. See more docs.

Hono 中文网 - 粤ICP备13048890号