跳到主要内容

Hertz 心智模型

Hertz 的两件工具各管什么?​

  • Hertz: CloudWeGo 的 HTTP 框架; Engine 管寻址、中间件与生命周期;
  • hz: 读 Thrift 或 protobuf IDL;
  • 生成: 模型、路由、Handler 骨架与工程布局;
  • Thrift IDL: 只描述 HTTP 接口, 并驱动 hz 生成;
  • 边界: 不改变 HTTP 传输;

一个最小 Hertz 服务由哪几部分组成?​

  • 建 Engine: server.Default;
  • 挂路由: h.GET;
  • Handler: 取输入, 调 Service, 映射响应;
  • 运行: h.Spin 阻塞;
func main() {
h := server.Default(
server.WithHostPorts(":8888"),
server.WithMaxRequestBodySize(1<<20), // 请求体上限 1 MiB
)
handler := &ArticleHandler{svc: svc}
h.GET("/articles/:id", handler.Get)
h.Spin()
}

func (h *ArticleHandler) Get(ctx context.Context, c *app.RequestContext) {
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
c.JSON(consts.StatusBadRequest, map[string]string{"code": "INVALID_ARGUMENT"})
return
}
article, err := h.svc.Get(ctx, id)
if err != nil {
c.JSON(consts.StatusInternalServerError, map[string]string{"code": "INTERNAL"})
return
}
c.JSON(consts.StatusOK, article)
}

server.Default 与 New 有什么差别?​

  • server.Default(): 自带 recovery.Recovery() 的 Engine;
  • 默认端口: :8888;
  • WithMaxRequestBodySize(1<<20): 中间件形式的开关;

body 上限与路由怎么挂?​

  • 效果: 超过 1 MiB 在解析前被拒;
  • h.GET: 把路径绑到 Handler;
  • Handler 只做三件事: 取输入、调 Service、映射响应;

Handler 里怎么写请求与响应?​

  • c.JSON: 设状态码与 Content-Type 后序列化;
  • ctx 是取消与 deadline 的来源, 一路传给 Service 与下游;
  • h.Spin(): 阻塞运行, 收到 SIGINT/SIGTERM 后走优雅退出;

新增一个接口按什么顺序推进?​

  1. 定 HTTP 方法、路径、请求字段、成功状态与错误响应, 写 IDL;
  2. hz 生成模型、路由与 Handler 骨架;
  3. 写 Handler、Service、Repository;
  4. 跑测试(ut.PerformRequest);
  5. 补中间件与配置;
  6. 补退出、探针与观测后上线;