Hertz 学习笔记(31)

261 阅读1分钟

继续学习 hz 生成代码的例子

使用 hz 生成客户端代码的示例

这个例子实际上使用到了 thrift,生成代码用到的文件在 idl 文件夹里,叫 psm.thrift

namespace go toutiao.middleware.hzClient

struct FormReq {
    1: string FormValue (api.form="form1");
    2: string FileValue (api.file_name="file1");
}

struct QueryReq {
    1: string QueryValue (api.query="query1");
}

struct PathReq {
    1: string PathValue (api.path="path1");
}

struct BodyReq {
    1: string BodyValue (api.body="");
    2: string QueryValue (api.query="query2");
}

struct Resp {
    1: string Resp;
}

service Hertz {
    Resp FormMethod(1: FormReq request) (api.post="/form", api.handler_path="post");
    Resp QueryMethod(1: QueryReq request) (api.get="/query", api.handler_path="get");
    Resp PathMethod(1: PathReq request) (api.post="/path:path1", api.handler_path="post");
    Resp BodyMethod(1: BodyReq request) (api.post="/body", api.handler_path="post");
}(
    api.base_domain="http://127.0.0.1:8888";
)

然后根据这个来生成服务端和客户端的代码。回到 idl 文件夹的上一级,创建 serverclient 两个文件夹,然后分别创建代码:

cd server
hz new --idl=../idl/psm.thrift --handler_by_method -t=template=slim
cd ..
cd client
hz client --idl=../idl/psm.thrift --model_dir=hertz_gen -t=template=slim --client_dir=hz_client

然后在 client 文件夹里面创建 main.go 文件,内容如下:

// client/main.go
package main

import (
	"context"
	"fmt"
	"hertz-examples/hz/hz_client/client/hertz_gen/toutiao/middleware/hzClient/hertz"
	"time"

	hzClient "hertz-examples/hz/hz_client/client/hertz_gen/toutiao/middleware/hzClient"
)

func main() {
	idlCli, err := hertz.NewHertzClient("http://127.0.0.1:8888")
	if err != nil {
		fmt.Println(err)
		return
	}

	{
		// query method
		queryReq := hzClient.QueryReq{
			QueryValue: "hello,query",
		}
		resp, rawResp, err := idlCli.QueryMethod(context.Background(), &queryReq)
		if err != nil {
			fmt.Println(err)
			return
		}
		fmt.Println(resp)
		fmt.Println(string(rawResp.Body()))
	}

	time.Sleep(500 * time.Millisecond)

	{
		// form method
		formReq := hzClient.FormReq{
			FormValue: "hello, form",
			FileValue: "./main.go",
		}
		resp, rawResp, err := idlCli.FormMethod(context.Background(), &formReq)
		if err != nil {
			fmt.Println(err)
			return
		}
		fmt.Println(resp)
		fmt.Println(string(rawResp.Body()))
	}

	time.Sleep(500 * time.Millisecond)

	{
		// path method
		pathReq := hzClient.PathReq{
			PathValue: "helloPath",
		}
		resp, rawResp, err := idlCli.PathMethod(context.Background(), &pathReq)
		if err != nil {
			fmt.Println(err)
			return
		}
		fmt.Println(resp)
		fmt.Println(string(rawResp.Body()))
	}

	time.Sleep(500 * time.Millisecond)

	{
		// body method
		bodyReq := hzClient.BodyReq{
			BodyValue:  "hello, body",
			QueryValue: "hello, query & body",
		}
		resp, rawResp, err := idlCli.BodyMethod(context.Background(), &bodyReq)
		if err != nil {
			fmt.Println(err)
			return
		}
		fmt.Println(resp)
		fmt.Println(string(rawResp.Body()))
	}
}

要运行也很简单,先运行服务端:

cd server
go run .

再开一个终端运行客户端:

cd client
go run .