1.安装protobuf complier
链接:https://pan.baidu.com/s/1HcCTttxZHJYopu-YwUl6PQ 提取码:3rub
把下载好的protoc.exe文件放到你的$GOPATH/bin下,并且保证你的$GOPATH/bin目录已经导入到环境变量中
2.安装protoc-gen-go
到https://github.com/golang/protobuf 把库文件克隆下来,再执行下面的命令生成protoc-gen-go.exe到$GOPATH/bin中
go get -u github.com/golang/protobuf/protoc-gen-go
3.安装protoc-gen-twirp
到https://github.com/twitchtv/twirp 把库文件克隆下来,再执行下面的命令生成protoc-gen-twirp.exe到$GOPATH/bin中
go get -u github.com/twitchtv/twirp/protoc-gen-twirp
4.编写protobuf服务的定义
在刚刚克隆下来的twitch文件夹下创建一个twirpexample文件夹,在twirpexample文件夹下创建rpc/haberdasher/service.proto,编写service.proto
syntax = "proto3";
package twirp.example.haberdasher;
option go_package = "haberdasher";
// Haberdasher service makes hats for clients.
service Haberdasher {
// MakeHat produces a hat of mysterious, randomly-selected color!
rpc MakeHat(Size) returns (Hat);
}
// Size of a Hat, in inches.
message Size {
int32 inches = 1; // must be > 0
}
// A Hat is a piece of headwear made by a Haberdasher.
message Hat {
int32 inches = 1;
string color = 2; // anything but "invisible"
string name = 3; // i.e. "bowler"
}
5.生成*.pb.go和*.twirp.go
切换到rpc目录,执行下面的命令
protoc --go_out=. --proto_path=. ./rpc/haberdasher/service.proto --twirp_out=.
解释一下,--go_out就是生成的*.pb.go文件存放的位置,--proto_path就是待转换的*.proto文件存放的位置,--twirp_out就是生成的*.twirp.go文件存放的位置
6.实现服务器的业务逻辑(接口的方法)
在twirpexample文件夹下,创建internal/haberdasherserver/server.go,编写server.go
package haberdasherserver
import (
"context"
"math/rand"
"github.com/twitchtv/twirp"
pb "github.com/twitchtv/twirpexample/rpc/haberdasher"
)
// Server implements the Haberdasher service
type Server struct {}
func (s *Server) MakeHat(ctx context.Context, size *pb.Size) (hat *pb.Hat, err error) {
if size.Inches <= 0 {
return nil, twirp.InvalidArgumentError("inches", "I can't make a hat that small!")
}
return &pb.Hat{
Inches: size.Inches,
Color: []string{"white", "black", "brown", "red", "blue"}[rand.Intn(4)],
Name: []string{"bowler", "baseball cap", "top hat", "derby"}[rand.Intn(3)],
}, nil
}
7.创建提供服务的服务器
在twirpexample文件夹下,创建cmd/server/main.go,编写main.go
package main
import (
"net/http"
"github.com/twitchtv/twirpexample/internal/haberdasherserver"
"github.com/twitchtv/twirpexample/rpc/haberdasher"
)
func main() {
server := &haberdasherserver.Server{} // implements Haberdasher interface
twirpHandler := haberdasher.NewHaberdasherServer(server, nil)
http.ListenAndServe(":8080", twirpHandler)
}
8.创建客户端
在twirpexample文件夹下,创建cmd/client/main.go,编写main.go
package main
import (
"context"
"net/http"
"os"
"fmt"
"github.com/twitchtv/twirpexample/rpc/haberdasher"
)
func main() {
client := haberdasher.NewHaberdasherProtobufClient("http://localhost:8080", &http.Client{})
hat, err := client.MakeHat(context.Background(), &haberdasher.Size{Inches: 12})
if err != nil {
fmt.Printf("oh no: %v", err)
os.Exit(1)
}
fmt.Printf("I have a nice new hat: %+v", hat)
}
9.测试
在cmd/server/main.go中执行go run main.go开启服务器,在cmd/client/main.go中执行go run main.go开启客户端访问相应的服务