简介

twirp是一个基于 Google Protobuf 的 RPC 框架。twirp通过在.proto文件中定义服务,然后自动生产服务器和客户端的代码。让我们可以将更多的精力放在业务逻辑上。咦?这不就是 gRPC 吗?不同的是,gRPC 自己实现了一套 HTTP 服务器和网络传输层,twirp 使用标准库net/http。另外 gRPC 只支持 HTTP/2 协议,twirp 还可以运行在 HTTP 1.1 之上。同时 twirp 还可以使用 JSON 格式交互。当然并不是说 twirp 比 gRPC 好,只是多了解一种框架也就多了一个选择😊

快速使用

首先需要安装 twirp 的代码生成插件:

  1. $ 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 生成插件:

  1. $ go get github.com/golang/protobuf/protoc-gen-go

同样地,命令protoc-gen-go会安装到$GOPATH/bin目录中。

本文代码采用Go Modules。先创建目录,然后初始化:

  1. $ mkdir twirp && cd twirp
  2. $ go mod init github.com/go-quiz/go-daily-lib/twirp

接下来,我们开始代码编写。先编写.proto文件:

  1. syntax = "proto3";
  2. option go_package = "proto";
  3. service Echo {
  4. rpc Say(Request) returns (Response);
  5. }
  6. message Request {
  7. string text = 1;
  8. }
  9. message Response {
  10. string text = 2;
  11. }

我们定义一个service实现echo功能,即发送什么就返回什么。切换到echo.proto所在目录,使用protoc命令生成代码:

  1. $ protoc --twirp_out=. --go_out=. ./echo.proto

上面命令会生成echo.pb.goecho.twirp.go两个文件。前一个是 Go Protobuf 文件,后一个文件中包含了twirp的服务器和客户端代码。

然后我们就可以编写服务器和客户端程序了。服务器:

  1. package main
  2. import (
  3. "context"
  4. "net/http"
  5. "github.com/go-quiz/go-daily-lib/twirp/get-started/proto"
  6. )
  7. type Server struct{}
  8. func (s *Server) Say(ctx context.Context, request *proto.Request) (*proto.Response, error) {
  9. return &proto.Response{Text: request.GetText()}, nil
  10. }
  11. func main() {
  12. server := &Server{}
  13. twirpHandler := proto.NewEchoServer(server, nil)
  14. http.ListenAndServe(":8080", twirpHandler)
  15. }

使用自动生成的代码,我们只需要 3 步即可完成一个 RPC 服务器:

  1. 定义一个结构,可以存储一些状态。让它实现我们定义的service接口;
  2. 创建一个该结构的对象,调用生成的New{{ServiceName}}Server方法创建net/http需要的处理器,这里的ServiceName为我们的服务名;
  3. 监听端口。

客户端:

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "log"
  6. "net/http"
  7. "github.com/go-quiz/go-daily-lib/twirp/get-started/proto"
  8. )
  9. func main() {
  10. client := proto.NewEchoProtobufClient("http://localhost:8080", &http.Client{})
  11. response, err := client.Say(context.Background(), &proto.Request{Text: "Hello World"})
  12. if err != nil {
  13. log.Fatal(err)
  14. }
  15. fmt.Printf("response:%s\n", response.GetText())
  16. }

twirp也生成了客户端相关代码,直接调用NewEchoProtobufClient连接到对应的服务器,然后调用rpc请求。

开启两个控制台,分别运行服务器和客户端程序。服务器:

  1. $ cd server && go run main.go

客户端:

  1. $ cd client && go run main.go

正确返回结果:

  1. response:Hello World

为了便于对照,下面列出该程序的目录结构。也可以去我的 GitHub 上查看示例代码:

  1. get-started
  2. ├── client
  3. └── main.go
  4. ├── proto
  5. ├── echo.pb.go
  6. ├── echo.proto
  7. └── echo.twirp.go
  8. └── server
  9. └── main.go

JSON 客户端

除了使用 Protobuf,twirp还支持 JSON 格式的请求。使用也非常简单,只需要在创建Client时将NewEchoProtobufClient改为NewEchoJSONClient即可:

  1. func main() {
  2. client := proto.NewEchoJSONClient("http://localhost:8080", &http.Client{})
  3. response, err := client.Say(context.Background(), &proto.Request{Text: "Hello World"})
  4. if err != nil {
  5. log.Fatal(err)
  6. }
  7. fmt.Printf("response:%s\n", response.GetText())
  8. }

Protobuf Client 发送的请求带有Content-Type: application/protobufHeader,JSON Client 则设置Content-Typeapplication/json。服务器收到请求时根据Content-Type来区分请求类型:

  1. // proto/echo.twirp.go
  2. unc (s *echoServer) serveSay(ctx context.Context, resp http.ResponseWriter, req *http.Request) {
  3. header := req.Header.Get("Content-Type")
  4. i := strings.Index(header, ";")
  5. if i == -1 {
  6. i = len(header)
  7. }
  8. switch strings.TrimSpace(strings.ToLower(header[:i])) {
  9. case "application/json":
  10. s.serveSayJSON(ctx, resp, req)
  11. case "application/protobuf":
  12. s.serveSayProtobuf(ctx, resp, req)
  13. default:
  14. msg := fmt.Sprintf("unexpected Content-Type: %q", req.Header.Get("Content-Type"))
  15. twerr := badRouteError(msg, req.Method, req.URL.Path)
  16. s.writeError(ctx, resp, twerr)
  17. }
  18. }

提供其他 HTTP 服务

实际上,twirpHandler只是一个http的处理器,正如其他千千万万的处理器一样,没什么特殊的。我们当然可以挂载我们自己的处理器或处理器函数(概念有不清楚的可以参见我的《Go Web 编程》系列文章

  1. type Server struct{}
  2. func (s *Server) Say(ctx context.Context, request *proto.Request) (*proto.Response, error) {
  3. return &proto.Response{Text: request.GetText()}, nil
  4. }
  5. func greeting(w http.ResponseWriter, r *http.Request) {
  6. name := r.FormValue("name")
  7. if name == "" {
  8. name = "world"
  9. }
  10. w.Write([]byte("hi," + name))
  11. }
  12. func main() {
  13. server := &Server{}
  14. twirpHandler := proto.NewEchoServer(server, nil)
  15. mux := http.NewServeMux()
  16. mux.Handle(twirpHandler.PathPrefix(), twirpHandler)
  17. mux.HandleFunc("/greeting", greeting)
  18. err := http.ListenAndServe(":8080", mux)
  19. if err != nil {
  20. log.Fatal(err)
  21. }
  22. }

上面程序挂载了一个简单的/greeting请求,可以通过浏览器来请求地址http://localhost:8080/greetingtwirp的请求会挂载到路径twirp/{{ServiceName}}这个路径下,其中ServiceName为服务名。上面程序中的PathPrefix()会返回/twirp/Echo

客户端:

  1. func main() {
  2. client := proto.NewEchoProtobufClient("http://localhost:8080", &http.Client{})
  3. response, _ := client.Say(context.Background(), &proto.Request{Text: "Hello World"})
  4. fmt.Println("echo:", response.GetText())
  5. httpResp, _ := http.Get("http://localhost:8080/greeting")
  6. data, _ := ioutil.ReadAll(httpResp.Body)
  7. httpResp.Body.Close()
  8. fmt.Println("greeting:", string(data))
  9. httpResp, _ = http.Get("http://localhost:8080/greeting?name=dj")
  10. data, _ = ioutil.ReadAll(httpResp.Body)
  11. httpResp.Body.Close()
  12. fmt.Println("greeting:", string(data))
  13. }

先运行服务器,然后执行客户端程序:

  1. $ go run main.go
  2. echo: Hello World
  3. greeting: hi,world
  4. greeting: hi,dj

发送自定义的 Header

默认情况下,twirp实现会发送一些 Header。例如上面介绍的,使用Content-Type辨别客户端使用的协议格式。有时候我们可能需要发送一些自定义的 Header,例如tokentwirp提供了WithHTTPRequestHeaders方法实现这个功能,该方法返回一个context.Context。发送时会将保存在该对象中的 Header 一并发送。类似地,服务器使用WithHTTPResponseHeaders发送自定义 Header。

由于twirp封装了net/http,导致外层拿不到原始的http.Requesthttp.Response对象,所以 Header 的读取有点麻烦。在服务器端,NewEchoServer返回的是一个http.Handler,我们加一层中间件读取http.Request。看下面代码:

  1. type Server struct{}
  2. func (s *Server) Say(ctx context.Context, request *proto.Request) (*proto.Response, error) {
  3. token := ctx.Value("token").(string)
  4. fmt.Println("token:", token)
  5. err := twirp.SetHTTPResponseHeader(ctx, "Token-Lifecycle", "60")
  6. if err != nil {
  7. return nil, twirp.InternalErrorWith(err)
  8. }
  9. return &proto.Response{Text: request.GetText()}, nil
  10. }
  11. func WithTwirpToken(h http.Handler) http.Handler {
  12. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  13. ctx := r.Context()
  14. token := r.Header.Get("Twirp-Token")
  15. ctx = context.WithValue(ctx, "token", token)
  16. r = r.WithContext(ctx)
  17. h.ServeHTTP(w, r)
  18. })
  19. }
  20. func main() {
  21. server := &Server{}
  22. twirpHandler := proto.NewEchoServer(server, nil)
  23. wrapped := WithTwirpToken(twirpHandler)
  24. http.ListenAndServe(":8080", wrapped)
  25. }

上面程序给客户端返回了一个名为Token-Lifecycle的 Header。客户端代码:

  1. func main() {
  2. client := proto.NewEchoProtobufClient("http://localhost:8080", &http.Client{})
  3. header := make(http.Header)
  4. header.Set("Twirp-Token", "test-twirp-token")
  5. ctx := context.Background()
  6. ctx, err := twirp.WithHTTPRequestHeaders(ctx, header)
  7. if err != nil {
  8. log.Fatalf("twirp error setting headers: %v", err)
  9. }
  10. response, err := client.Say(ctx, &proto.Request{Text: "Hello World"})
  11. if err != nil {
  12. log.Fatalf("call say failed: %v", err)
  13. }
  14. fmt.Printf("response:%s\n", response.GetText())
  15. }

运行程序,服务器正确获取客户端传过来的 token。

请求路由

我们前面已经介绍过了,twirpServer实际上也就是一个http.Handler,如果我们知道了它的挂载路径,完全可以通过浏览器或者curl之类的工具去请求。我们启动get-started的服务器,然后用curl命令行工具去请求:

  1. $ curl --request "POST" \
  2. --location "http://localhost:8080/twirp/Echo/Say" \
  3. --header "Content-Type:application/json" \
  4. --data '{"text":"hello world"}'\
  5. --verbose
  6. {"text":"hello world"}

这在调试的时候非常有用。

总结

本文介绍了 Go 的一个基于 Protobuf 生成代码的 RPC 框架,非常简单,小巧,实用。twirp对许多常用的编程语言都提供了支持。可以作为 gRPC 等的备选方案考虑。

大家如果发现好玩、好用的 Go 语言库,欢迎到 Go 每日一库 GitHub 上提交 issue😄

参考

  1. twirp GitHub:https://github.com/twitchtv/twirp
  2. twirp 官方文档:https://twitchtv.github.io/twirp/docs/intro.html
  3. Go 每日一库 GitHub:https://github.com/go-quiz/go-daily-lib