百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

Go 每日一库之 twirp:又一个 RPC 框架

ccwgpt 2024-09-17 12:50 43 浏览 0 评论

简介

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

快速使用

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

nbsp;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 生成插件:

nbsp;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, error) {
  return &proto.Response{Text: request.GetText()}, nil
}

func main() {
  server := &Server{}
  twirpHandler := proto.NewEchoServer(server, nil)

  http.ListenAndServe(":8080", twirpHandler)
}

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

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

客户端:

package main

import (
  "context"
  "fmt"
  "log"
  "net/http"

  "github.com/darjun/go-daily-lib/twirp/get-started/proto"
)

func main() {
  client := proto.NewEchoProtobufClient("http://localhost:8080", &http.Client{})

  response, err := client.Say(context.Background(), &proto.Request{Text: "Hello World"})
  if err != nil {
    log.Fatal(err)
  }
  fmt.Printf("response:%s\n", response.GetText())
}

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

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

$ cd server && go run main.go

客户端:

$ cd client && go run main.go

正确返回结果:

response:Hello World

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

get-started
├── client
│   └── main.go
├── proto
│   ├── echo.pb.go
│   ├── echo.proto
│   └── echo.twirp.go
└── server
    └── main.go

JSON 客户端

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

func main() {
  client := proto.NewEchoJSONClient("http://localhost:8080", &http.Client{})

  response, err := client.Say(context.Background(), &proto.Request{Text: "Hello World"})
  if err != nil {
    log.Fatal(err)
  }
  fmt.Printf("response:%s\n", response.GetText())
}

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

// proto/echo.twirp.go
unc (s *echoServer) serveSay(ctx context.Context, resp http.ResponseWriter, req *http.Request) {
  header := req.Header.Get("Content-Type")
  i := strings.Index(header, ";")
  if i == -1 {
    i = len(header)
  }
  switch strings.TrimSpace(strings.ToLower(header[:i])) {
  case "application/json":
    s.serveSayJSON(ctx, resp, req)
  case "application/protobuf":
    s.serveSayProtobuf(ctx, resp, req)
  default:
    msg := fmt.Sprintf("unexpected Content-Type: %q", req.Header.Get("Content-Type"))
    twerr := badRouteError(msg, req.Method, req.URL.Path)
    s.writeError(ctx, resp, twerr)
  }
}

提供其他 HTTP 服务

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

type Server struct{}

func (s *Server) Say(ctx context.Context, request *proto.Request) (*proto.Response, error) {
  return &proto.Response{Text: request.GetText()}, nil
}

func greeting(w http.ResponseWriter, r *http.Request) {
  name := r.FormValue("name")
  if name == "" {
    name = "world"
  }

  w.Write([]byte("hi," + name))
}

func main() {
  server := &Server{}
  twirpHandler := proto.NewEchoServer(server, nil)

  mux := http.NewServeMux()
  mux.Handle(twirpHandler.PathPrefix(), twirpHandler)
  mux.HandleFunc("/greeting", greeting)

  err := http.ListenAndServe(":8080", mux)
  if err != nil {
    log.Fatal(err)
  }
}

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

客户端:

func main() {
  client := proto.NewEchoProtobufClient("http://localhost:8080", &http.Client{})

  response, _ := client.Say(context.Background(), &proto.Request{Text: "Hello World"})
  fmt.Println("echo:", response.GetText())

  httpResp, _ := http.Get("http://localhost:8080/greeting")
  data, _ := ioutil.ReadAll(httpResp.Body)
  httpResp.Body.Close()
  fmt.Println("greeting:", string(data))

  httpResp, _ = http.Get("http://localhost:8080/greeting?name=dj")
  data, _ = ioutil.ReadAll(httpResp.Body)
  httpResp.Body.Close()
  fmt.Println("greeting:", string(data))
}

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

$ go run main.go
echo: Hello World
greeting: hi,world
greeting: hi,dj

发送自定义的 Header

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

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

type Server struct{}

func (s *Server) Say(ctx context.Context, request *proto.Request) (*proto.Response, error) {
  token := ctx.Value("token").(string)
  fmt.Println("token:", token)

  err := twirp.SetHTTPResponseHeader(ctx, "Token-Lifecycle", "60")
  if err != nil {
    return nil, twirp.InternalErrorWith(err)
  }
  return &proto.Response{Text: request.GetText()}, nil
}

func WithTwirpToken(h http.Handler) http.Handler {
  return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    ctx := r.Context()
    token := r.Header.Get("Twirp-Token")
    ctx = context.WithValue(ctx, "token", token)
    r = r.WithContext(ctx)

    h.ServeHTTP(w, r)
  })
}

func main() {
  server := &Server{}
  twirpHandler := proto.NewEchoServer(server, nil)
  wrapped := WithTwirpToken(twirpHandler)

  http.ListenAndServe(":8080", wrapped)
}

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

func main() {
  client := proto.NewEchoProtobufClient("http://localhost:8080", &http.Client{})

  header := make(http.Header)
  header.Set("Twirp-Token", "test-twirp-token")

  ctx := context.Background()
  ctx, err := twirp.WithHTTPRequestHeaders(ctx, header)
  if err != nil {
    log.Fatalf("twirp error setting headers: %v", err)
  }

  response, err := client.Say(ctx, &proto.Request{Text: "Hello World"})
  if err != nil {
    log.Fatalf("call say failed: %v", err)
  }
  fmt.Printf("response:%s\n", response.GetText())
}

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

请求路由

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

$ curl --request "POST" \
  --location "http://localhost:8080/twirp/Echo/Say" \
  --header "Content-Type:application/json" \
  --data '{"text":"hello world"}'\
  --verbose
{"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/darjun/go-daily-lib

相关推荐

一个基于.Net Core遵循Clean Architecture原则开源架构

今天给大家推荐一个遵循CleanArchitecture原则开源架构。项目简介这是基于Asp.netCore6开发的,遵循CleanArchitecture原则,可以高效、快速地构建基于Ra...

AI写代码翻车无数次,我发现只要提前做好这3步,bug立减80%

写十万行全是bug之后终于找到方法了开发"提示词管理助手"新版本那会儿,我差点被bug整崩溃。刚开始两周,全靠AI改代码架构,结果十万行程序漏洞百出。本来以为AI说没问题就稳了,结果...

OneCode低代码平台的事件驱动设计:架构解析与实践

引言:低代码平台的事件驱动范式在现代软件开发中,事件驱动架构(EDA)已成为构建灵活、松耦合系统的核心范式。OneCode低代码平台通过创新性的注解驱动设计,将事件驱动理念深度融入平台架构,实现了业务...

国内大厂AI插件评测:根据UI图生成Vue前端代码

在IDEA中安装大厂的AI插件,打开ruoyi增强项目:yudao-ui-admin-vue31.CodeBuddy插件登录腾讯的CodeBuddy后,大模型选择deepseek-v3,输入提示语:...

AI+低代码技术揭秘(二):核心架构

本文档介绍了为VTJ低代码平台提供支持的基本架构组件,包括Engine编排层、Provider服务系统、数据模型和代码生成管道。有关UI组件库和widget系统的信息,请参阅UI...

GitDiagram用AI把代码库变成可视化架构图

这是一个名为gitdiagram的开源工具,可将GitHub仓库实时转换为交互式架构图,帮助开发者快速理解代码结构。核心功能一键可视化:替换GitHubURL中的"hub...

30天自制操作系统:第六天:代码架构整理与中断处理

1.拆开bootpack.c文件。根据设计模式将对应的功能封装成独立的文件。2.初始化pic:pic(可编程中断控制器):在设计上,cpu单独只能处理一个中断。而pic是将8个中断信号集合成一个中断...

AI写代码越帮越忙?2025年研究揭露惊人真相

近年来,AI工具如雨后春笋般涌现,许多人开始幻想程序员的未来就是“对着AI说几句话”,就能轻松写出完美的代码。然而,2025年的一项最新研究却颠覆了这一期待,揭示了一个令人意外的结果。研究邀请了16位...

一键理解开源项目:两个自动生成GitHub代码架构图与说明书工具

一、GitDiagram可以一键生成github代码仓库的架构图如果想要可视化github开源项目:https://github.com/luler/reflex_ai_fast,也可以直接把域名替换...

5分钟掌握 c# 网络通讯架构及代码示例

以下是C#网络通讯架构的核心要点及代码示例,按协议类型分类整理:一、TCP协议(可靠连接)1.同步通信//服务器端usingSystem.Net.Sockets;usingTcpListene...

从复杂到优雅:用建造者和责任链重塑代码架构

引用设计模式是软件开发中的重要工具,它为解决常见问题提供了标准化的解决方案,提高了代码的可维护性和可扩展性,提升了开发效率,促进了团队协作,提高了软件质量,并帮助开发者更好地适应需求变化。通过学习和应...

低代码开发当道,我还需要学习LangChain这些框架吗?| IT杂谈

专注LLM深度应用,关注我不迷路前两天有位兄弟问了个问题:当然我很能理解这位朋友的担忧:期望效率最大化,时间用在刀刃上,“不要重新发明轮子”嘛。铺天盖地的AI信息轰炸与概念炒作,很容易让人浮躁与迷茫。...

框架设计并不是简单粗暴地写代码,而是要先弄清逻辑

3.框架设计3.框架设计本节我们要开发一个UI框架,底层以白鹭引擎为例。框架设计的第一步并不是直接撸代码,而是先想清楚设计思想,抽象。一个一个的UI窗口是独立的吗?不是的,...

大佬用 Avalonia 框架开发的 C# 代码 IDE

AvalonStudioAvalonStudio是一个开源的跨平台的开发编辑器(IDE),AvalonStudio的目标是成为一个功能齐全,并且可以让开发者快速使用的IDE,提高开发的生产力。A...

轻量级框架Lagent 仅需20行代码即可构建自己的智能代理

站长之家(ChinaZ.com)8月30日消息:Lagent是一个专注于基于LLM模型的代理开发的轻量级框架。它的设计旨在简化和提高这种模型下代理的开发效率。LLM模型是一种强大的工具,可以...

取消回复欢迎 发表评论: