[ Golang HTTP框架之Hertz | 青训营笔记]

178 阅读3分钟

这是我参与「第五届青训营 」伴学笔记创作活动的第 7 天

Hertz介绍

  1. Hertz是基于字节跳动内部自研网络库 Netpoll 开发内部Http框架,在面对企业级需求时,有更好的性能及稳定性表现
  2. Hertz 采用了 4 层分层设计
  3. Hertz 从上到下分为:应用层、路由层、协议层和传输层,同时公共能力被统一抽象到公共层
  4. Hz 脚手架能够协助使用者快速搭建出项目核心骨架以及提供实用的构建工具链,Hz 支持了 Thrift 和 Protobuf 两种 IDL 定义
  5. Hertz 除了提供 Server 的中间件能力,还提供了 Client 中间件能力
  6. Server 的中间件分成了两种类型
    • 不在同一个函数调用栈:该中间件调用完后返回,由上一个中间件调用下一个中间件
    • 在同一个函数调用栈:该中间件调用完后由该中间件继续调用下一个中间件
  7. Hertz 支持了 Server 和 Client 的流式处理

Hertz实践

  1. 定义IDL,支持Thrift和Protobuf

  2. 使用 Hz 生成代码,并整理和拉取依赖

    # idl/demo.thrift为idl文件路径
    hz new -idl idl/demo.thrift -mod Demo
    go mod tidy && go mod verify
    
  3. 生成代码目录

    ├── biz                                // business 层,存放业务逻辑相关流程
    │   ├── handler                        // 存放 handler 文件
    │   │   ├── hello                      // hello/example 对应 thrift idl 中定义的 namespace;而对于 protobuf idl,则是对应 go_package 的最后一级
    │   │   │   └── example
    │   │   │       ├── hello_service.go   // handler 文件,用户在该文件里实现 IDL service 定义的方法,update 时会查找 当前文件已有的 handler 在尾部追加新的 handler
    │   │   │       └── new_service.go     // 同上,idl 中定义的每一个 service 对应一个文件
    │   │   └── ping.go                    // 默认携带的 ping handler,用于生成代码快速调试,无其他特殊含义
    │   ├── model                          // IDL 内容相关的生成代码
    │   │   └── hello                      // hello/example 对应 thrift idl 中定义的 namespace;而对于 protobuf idl,则是对应 go_package
    │   │     └── example
    │   │         └── hello.go             // thriftgo 的产物,包含 hello.thrift 定义的内容的 go 代码,update 时会重新生成
    │   └── router                         // idl 中定义的路由相关生成代码
    │       ├── hello                      // hello/example 对应 thrift idl 中定义的namespace;而对于 protobuf idl,则是对应 go_package 的最后一级
    │       │   └── example
    │       │       ├── hello.go           // hz 为 hello.thrift 中定义的路由生成的路由注册代码;每次 update 相关 idl 会重新生成该文件
    │       │       └── middleware.go      // 默认中间件函数,hz 为每一个生成的路由组都默认加了一个中间件;update 时会查找当前文件已有的 middleware 在尾部追加新的 middleware
    │       └── register.go                // 调用注册每一个 idl 文件中的路由定义;当有新的 idl 加入,在更新的时候会自动插入其路由注册的调用;勿动
    ├── go.mod                             // go.mod 文件,如不在命令行指定,则默认使用相对于GOPATH的相对路径作为 module 名
    ├── idl                                // 用户定义的idl,位置可任意
    │   └── hello.thrift
    ├── main.go                            // 程序入口
    ├── router.go                          // 用户自定义除 idl 外的路由方法
    └── router_gen.go                      // hz 生成的路由注册代码,用于调用用户自定义的路由以及 hz 生成的路由
    
  4. 如需在已有项目的基础上增加接口

    • 更新IDL文件

    • 切换至idl目录,重新生成

      hz update -idl idl/hello.thrift
      
  5. 编译运行

参考资料

字节跳动开源 Go HTTP 框架 Hertz 设计实践 - 掘金 (juejin.cn)

快速开始 | CloudWeGo

hertz-examples/hz/thrift at main · cloudwego/hertz-examples (github.com)

‌⁡⁤⁢⁣⁡⁢⁢⁣⁡⁡‍⁣⁢⁣⁣‬‬‌⁢⁤⁢⁣⁣⁣‌‬‬‍⁡‌‍‍‬Go 框架三件套详解.pptx - 飞书云文档 (feishu.cn)

hz 命令行工具使用 | CloudWeGo