我想测试一个示例 Twirp RPC 服务。示例服务来自Twirp 官方网站。
Protobuf 定义如下:
syntax = "proto3";
package helloservice;
option go_package = "helloservice";
service HelloWorld {
rpc Hello(HelloReq) returns (HelloResp);
}
message HelloReq {
string subject = 1;
}
message HelloResp {
string text = 1;
}
服务器实现:
type HelloWorldServer struct{}
func (s *HelloWorldServer) Hello(ctx context.Context, req *pb.HelloReq) (*pb.HelloResp, error) {
return &pb.HelloResp{Text: "Hello " + req.Subject}, nil
}
我尝试了这里建议的解决方案,但是 ClientConn 与 HTTPClient 之间存在一些混淆。到目前为止,我有这个
var Once sync.Once
const bufSize = 1024 * 1024
var listener *bufconn.Listener
func InitTestServer(t *testing.T) *gomock.Controller {
Once.Do(func(){
listener = bufconn.Listen(bufSize)
server := &server.HelloWorldServer{}
twirpHandler := pb.NewHelloWorldServer(server, nil)
mux := http.NewServeMux()
mux.Handle(twirpHandler.PathPrefix(), twirpHandler)
httpServer := http.Server{
Handler: mux,
}
go func() {
if err := httpServer.Serve(listener); err != nil {
if err != http.ErrServerClosed {
log.Fatalln("Failed to start http listener", "error", err)
}
}
}()
})
ctrl := gomock.NewController(t)
return ctrl
}
func bufDialer(context.Context, string) (net.Conn, error) {
return listener.Dial()
}
func TestCreate(t *testing.T) {
//ctrl := InitTestServer(t)
InitTestServer(t)
ctx := context.Background()
conn, err := grpc.DialContext(ctx, "", grpc.WithInsecure(), grpc.WithContextDialer(bufDialer))
// conn is of type *ClientConn
if err != nil {
t.Fatalf("Failed to dial bufnet: %v", err)
}
defer conn.Close()
//NewHelloWorldJSONClient accepts only HTTPClient
client := pb.NewHelloWorldJSONClient(conn)
response, err := client.Hello(ctx, &pb.HelloReq{
Subject: "sample",
})
t.Log(response, err)
}
有什么方法可以将一个转换成另一个,或者任何其他方法来测试 Twirp RPC?