简介
twirp是一个基于 Google Protobuf 的 RPC 框架。twirp
通过在.proto
文件中定义服务,然后自动生产服务器和客户端的代码。让我们可以将更多的精力放在业务逻辑上。咦?这不就是 gRPC 吗?不同的是,gRPC 自己实现了一套 HTTP 服务器和网络传输层,twirp 使用标准库net/http
。另外 gRPC 只支持 HTTP/2 协议,twirp 还可以运行在 HTTP 1.1 之上。同时 twirp 还可以使用 JSON 格式交互。当然并不是说 twirp 比 gRPC 好,只是多了解一种框架也就多了一个选择????
快速使用
首先需要安装 twirp 的代码生成插件:
$ go get github.com/twitchtv/twirp/protoc-gen-twirp
上面命令会在$GOPATH/bin
目录下生成可执行程序protoc-gen-twirp
。我的习惯是将$GOPATH/bin
放到 PATH 中,所以可在任何地方执行该命令。
接下来安装 protobuf 编译器,直接到 GitHub 上https://github.com/protocolbuffers/protobuf/releases下载编译好的二进制程序放到 PATH 目录即可。
最后是 Go 语言的 protobuf 生成插件:
$ go get github.com/golang/protobuf/protoc-gen-go
同样地,命令protoc-gen-go
会安装到$GOPATH/bin
目录中。
本文代码采用Go Modules。先创建目录,然后初始化:
$ mkdir twirp && cd twirp
$ go mod init github.com/darjun/go-daily-lib/twirp
接下来,我们开始代码编写。先编写.proto
文件:
syntax = "proto3";
option go_package = "proto";
service Echo {
rpc Say(Request) returns (Response);
}
message Request {
string text = 1;
}
message Response {
string text = 2;
}
我们定义一个service
实现echo功能,即发送什么就返回什么。切换到echo.proto
所在目录,使用protoc
命令生成代码:
$ protoc --twirp_out=. --go_out=. ./echo.proto
上面命令会生成echo.pb.go
和echo.twirp.go
两个文件。前一个是 Go Protobuf 文件,后一个文件中包含了twirp
的服务器和客户端代码。
然后我们就可以编写服务器和客户端程序了。服务器:
package main
import (
"context"
"net/http"
"github.com/darjun/go-daily-lib/twirp/get-started/proto"
)
type Server struct{}
func (s *Server) Say(ctx context.Context, request *proto.Request) (*proto.Response, erro