首页
/ Twirp 开源项目教程

Twirp 开源项目教程

2024-08-11 02:40:59作者:房伟宁

项目介绍

Twirp 是一个基于 Google Protobuf 的简单 RPC 框架。通过在 .proto 文件中定义服务,Twirp 会自动生成服务器和客户端的代码,使开发者可以将更多精力放在业务逻辑上。与 gRPC 不同,Twirp 使用标准库 net/http,并且支持 HTTP/1.1 协议,同时还可以使用 JSON 格式进行交互。

项目快速启动

安装 Twirp 和相关工具

首先,需要安装 Twirp 的代码生成插件和 protobuf 编译器:

# 安装 Twirp 代码生成插件
go get github.com/twitchtv/twirp/protoc-gen-twirp

# 安装 protobuf 编译器
# 下载地址:https://github.com/protocolbuffers/protobuf/releases

# 安装 Go 语言的 protobuf 生成插件
go get github.com/golang/protobuf/protoc-gen-go

定义 Proto 文件

创建一个 service.proto 文件,定义一个简单的服务:

syntax = "proto3";

package echo;

message EchoRequest {
  string text = 1;
}

message EchoResponse {
  string text = 1;
}

service Echo {
  rpc Say(EchoRequest) returns (EchoResponse);
}

生成代码

使用以下命令生成服务器和客户端代码:

protoc --twirp_out=. --go_out=. service.proto

编写服务器代码

创建一个 server.go 文件,实现生成的接口:

package main

import (
  "context"
  "net/http"

  "github.com/twitchtv/twirp"
  "path/to/generated"
)

type EchoServer struct{}

func (s *EchoServer) Say(ctx context.Context, req *generated.EchoRequest) (*generated.EchoResponse, error) {
  return &generated.EchoResponse{Text: req.Text}, nil
}

func main() {
  server := &EchoServer{}
  handler := generated.NewEchoServer(server, nil)
  http.ListenAndServe(":8080", handler)
}

编写客户端代码

创建一个 client.go 文件,调用服务器:

package main

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

  "path/to/generated"
)

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

  resp, err := client.Say(context.Background(), &generated.EchoRequest{Text: "Hello World"})
  if err != nil {
    fmt.Println("Error:", err)
    return
  }
  fmt.Println("Response:", resp.Text)
}

应用案例和最佳实践

提供其他 HTTP 服务

Twirp 的服务器实际上是一个 http.Handler,可以与其他 HTTP 服务一起使用:

func main() {
  server := &EchoServer{}
  twirpHandler := generated.NewEchoServer(server, nil)

  mux := http.NewServeMux()
  mux.Handle(generated.EchoPathPrefix, twirpHandler)
  mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("OK"))
  })

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

发送自定义的 Header

可以在客户端请求中添加自定义的 Header:

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

  ctx := context.Background()
  ctx = metadata.AppendToOutgoingContext(ctx, "Authorization", "Bearer token")

  resp, err := client.Say(ctx, &generated.EchoRequest{Text: "Hello World"})
  if err != nil {
    fmt.Println("Error:", err)
    return
  }
  fmt.Println("Response:", resp.Text)
}

典型生态项目

登录后查看全文
热门项目推荐
相关项目推荐