Go框架三件套详解(Web/RPC/ORM)2 | 青训营笔记

35 阅读2分钟

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

2.三件套的使用

2.2 Kitex的使用

安装Kitex
go install github.com/cloudwego/kitex/tool/cmd/kitex@latest
安装thriftgo
go install github.com/cloudwego/thriftgo@latest

定义IDL

namespace go echo

struct Request {
    1: string Msg
}

struct Response {
    1: string Msg
}

service EchoService {
    Response Echo(1: Request req); // pingpong method
    oneway void VisitOneway(1: Request req); // oneway method
}

Kitex生成代码

# 若当前目录不在 $GOPATH/src 下,需要加上 -module 参数,一般为 go.mod 下的名字  
kitex -module "your_module_name" -service a.b.c hello.thrift

Kitex基本使用 服务默认监听8888端口

package main
import(
  "context"
  "example/kitex_gen/api"
)
type EchoImpl struct{}
func (s *EchoImpl) Echb(ctx context.Context, req *api.Request)(resp *api.Response, err error){
   return
}

Kitex发起请求
创建Client

c,err := echo.NewClient("example",client.WithHostPorts("0.0.0.0:8888"))
if err != nil{
    log.Fatal(err)
}

发起请求

req:=&api.Request{Message:"my request"}
resp, err:=c.Echo(context.Background(),req,callopt.WithRPCTimeout(3*time.second))
if err!=nil{
    log.Fatal(err)
}
log.Println(resp)

2.3 Hertz的使用

安装Hertz

  • go install github.com/cloudwego/hertz/cmd/hz@latest
  • GO111MODULE=on 的情况下 go install github.com/cloudwego/thriftgo@latest
  • 可以使用 hz new 来生成测试代码

定义IDL

namespace go hello.example

struct HelloReq {
    1: string Name (api.query="name"); // 添加 api 注解为方便进行参数绑定
}

struct HelloResp {
    1: string RespBody;
}


service HelloService {
    HelloResp HelloMethod(1: HelloReq request) (api.get="/hello");
}

service NewService {
    HelloResp NewMethod(1: HelloReq request) (api.get="/new");
}

这里要用管理员权限来执行这条命令,如果使用Goland来运行的话,可以在toolbox(或者其方式也可以),将Goland改为以管理员身份运行。同时,thrift 的路径要写对,否则还是会给你生成,生成的是 hz new 的那个pingpong框架。

Hertz基本使用

  • 用法有点像gin,支持Restful风格的api接口与路由组的设计,路由的优先级:静态路由 > 命名路由 > 通配路由
  • Hertz 支持使用 :name 这样的命名参数设置路由
  • 使用 *path 这样的通配参数设置路由,并且通配参数会匹配所有内容。

Middleware

// server 级别
h := server.Default()
h.Use(GlobalMiddleware())

// 路由级别
group := h.Group("/group")
group.Use(GroupMiddleware())
  • Abort():终止后续调用
  • AbortWithMsg(msg string, statusCode int):终止后续调用,并设置 response中body,和状态码
  • AbortWithStatus(code int):终止后续调用,并设置状态码

日志

logger := hertzzap.NewLogger()
hlog.SetLogger(logger)
// ....
hlog.Infof("hello %s", "hertz")

服务注册与服务发现

    h := server.Default(
        server.WithHostPorts(addr),
        server.WithRegistry(r, &registry.Info{
            ServiceName: "hertz.test.demo",
            Addr:        utils.NewNetAddr("tcp", addr),
            Weight:      10,
            Tags:        nil,
        }))