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

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

ccwgpt 2024-09-17 12:50 24 浏览 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

相关推荐

盲盒小程序背后的技术揭秘:如何打造个性化购物体验

在2025年的今天,盲盒小程序作为一种新兴的购物方式,正以其独特的魅力和个性化体验吸引着越来越多的消费者。这种将线上购物与盲盒概念相结合的应用,不仅为消费者带来了未知的惊喜,还通过一系列技术手段实现了...

小程序·云开发已支持单日亿级调用量,接口可用率高达99.99%

2019-10-1914:1210月19日,由腾讯云与微信小程序团队联合举办的“小程序·云开发”技术峰会在北京召开。会上,微信小程序团队相关负责人表示“小程序·云开发”系统架构已经支持每天亿级别的...

程序员副业开启模式:8个GitHub上可以赚钱的小程序

前言开源项目作者:JackonYang今天推荐的这个项目是「list-of-wechat-mini-program-list」,开源微信小程序列表的列表、有赚钱能力的小程序开源代码。这个项目分为两部分...

深度科普:盲盒小程序开发的底层逻辑

在当下的数字化浪潮中,盲盒小程序以其独特的趣味性和互动性,吸引着众多消费者的目光。无论是热衷于收集玩偶的年轻人,还是享受拆盒惊喜的上班族,都对盲盒小程序情有独钟。那么,这种备受欢迎的盲盒小程序,其开发...

微信小程序的制作步骤

SaaS小程序制作平台,作为数字化转型时代下的创新产物,不仅将易用性置于设计的核心位置,让非技术背景的用户也能轻松上手,快速制作出功能丰富、界面精美的小程序,更在性能和稳定性方面投入了大量精力,以确保...

携程开源--小程序构建工具,三分钟搞定

前言今天推荐的这个项目是「wean」,一个小程序构建打包工具。在wean之前,大量小程序工具使用webpack进行打包,各种loader、plugin导致整个开发链路变长。wean旨在解...

校园小程序的搭建以及营收模式校园外卖程序校园跑腿校园圈子系统

校园小程序的架构设计主要包括云端架构和本地架构两部分。云端架构方面,采用Serverless架构可以降低技术门槛,通过阿里云、腾讯云等平台提供的云服务,可以实现弹性扩容和快速部署。例如,使用云数据库、...

盲盒小程序开发揭秘:技术架构与实现原理全解析

在2025年的今天,盲盒小程序作为一种结合了线上购物与趣味性的创新应用,正受到越来越多用户的喜爱。其背后的技术架构与实现原理,对于想要了解或涉足这一领域的人来说,无疑充满了神秘与吸引力。本文将为大家科...

月活百万的小程序架构设计:流量暴增秘籍

从小程序到"大"程序的蜕变之路当你的小程序用户量从几千跃升至百万级别时,原有的架构就像一件不合身的衣服,处处紧绷。这个阶段最常遇到的噩梦就是服务器崩溃、接口超时、数据丢失。想象一下,在...

认知智能如何与产业结合?专家学者共探理论框架与落地实践

当前,以大模型为代表的生成式人工智能等前沿技术加速迭代,如何将认知智能与产业结合,成为摆在各行各业面前的一个问题。论坛现场。主办方供图7月4日,2024世界人工智能大会暨人工智能全球治理高级别会议在...

现代中医理论框架

...

认知行为(CBT)中的ABC情绪理论

情绪ABC理论是由美国心理学家阿尔伯特·艾利斯(AlbertEllis1913-2007)创建的理论,A表示诱发性事件(Activatingevent),B表示个体针对此诱发性事件产生的一些信...

说说卡伦霍妮的理论框架,对你调整性格和人际关系,价值很大

01自在今天我主要想说下霍妮的理论框架。主要说三本书,第一本是《我们时代的神经症人格》,第二本是《我们内心的冲突》,第三本是《神经症与人的成长》。根据我的经验,三本书价值巨大,但并不是每个人都能读进去...

供应链管理-理论框架

一个最佳价值的供应链,应该是一个具有敏捷性、适应性和联盟功能(3A)的供应链,其基本要素包括战略资源、物流管理、关系管理以及信息系统,目标是实现速度、质量、成本、柔性的竞争优势。篇幅有...

微信WeUI设计规范文件下载及使用方法

来人人都是产品经理【起点学院】,BAT实战派产品总监手把手系统带你学产品、学运营。WeUI是一套同微信原生视觉体验一致的基础样式库,由微信官方设计团队为微信Web开发量身设计,可以令用户的使用感知...

取消回复欢迎 发表评论: