客户端的例子也结束了,今天学一下 hz 这个工具的使用。
使用 hz 与 thrift 生成服务端代码的示例
生成项目
创建 idl 文件夹然后把 hello.thrift 放进去,这个文件的内容如下:
namespace go hello.example
struct HelloReq {
1: string Name (api.query="name");
}
struct HelloResp {
1: string RespBody;
}
service HelloService {
HelloResp HelloMethod(1: HelloReq request) (api.get="/hello");
}
然后再回到上一级文件夹创建项目:
hz new -idl idl/hello.thrift
go mod tidy
然后往 handler 里面添加自己的逻辑。这个代码在 biz/handler/hello/example/hello_service.go 里,其中 hello/example 是 thrift idl 的 namespace,hello_service.go 是 thrift idl 中 service 的名字,所有 service 定义的方法都会生成在这个文件中。
// HelloMethod .
// @router /hello [GET]
func HelloMethod(ctx context.Context, c *app.RequestContext) {
var err error
var req example.HelloReq
err = c.BindAndValidate(&req)
if err != nil {
c.String(400, err.Error())
return
}
resp := new(example.HelloResp)
// 你可以修改整个函数的逻辑,而不仅仅局限于当前模板
resp.RespBody = "hello," + req.Name // 添加的逻辑
c.JSON(200, resp)
}
编译项目:
go build
运行一下当前文件夹里面的那个可执行文件,然后测试 curl --location --request GET 'http://127.0.0.1:8888/hello?name=hertz',如果有 {"RespBody":"hello,hertz"},证明接口调通了。