使用场景:
希望同时提供grpc接口和restful接口,又不想重复写两遍代码
获取资源:
1.安装grpc-gateway插件
go get github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-grpc-gateway
2.修改proto,首先在proto中导入googleapi的proto,然后在具体的方法中增加http相关注解
syntax = "proto3"; //语法声明
option go_package="./;pb";
package pb; //包名
import "google/api/annotations.proto";
// Greeter 微服务
service Greeter {
rpc SayHello(HelloRequest) returns (HelloResponse){
option (google.api.http)={
post : "/v1/pb/SayHello"
body : "*"
};
}
}
message HelloRequest{
string name=1;
}
message HelloResponse{
string message=1;
}
annotations.proto和http.proto,descriptor.proto的内容可以在github搜索googleapi去下载,路径为
googleapis/http.proto at master · googleapis/googleapis · GitHubhttps://github.com/googleapis/googleapis/blob/master/google/api/http.protogoogleapis/annotations.proto at master · googleapis/googleapis · GitHubPublic interface definitions of Google APIs. Contribute to googleapis/googleapis development by creating an account on GitHub.https://github.com/googleapis/googleapis/blob/master/google/api/annotations.proto
最终路径如下图:
生成代码:
protoc -I ./pb/google/api -I ./pb --grpc_gateway_out ./pb hello.proto
grpc-gateway代理:
package main
import (
"context"
"flag"
"fmt"
"net/http"
pb "seeker/grpcdemo/pb"
"github.com/golang/glog"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"google.golang.org/grpc"
)
var (
grpcServerEndpoint = flag.String("grpc-server-endpoint", "localhost:50051", "gRPC server endpoint")
)
func run() error {
fmt.Println("run")
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
mux := runtime.NewServeMux()
opts := []grpc.DialOption{grpc.WithInsecure()}
err := pb.RegisterGreeterHandlerFromEndpoint(ctx, mux, *grpcServerEndpoint, opts)
if err != nil {
return err
}
return http.ListenAndServe(":8081", mux)
}
func main() {
flag.Parse()
defer glog.Flush()
if err := run(); err != nil {
glog.Fatal(err)
}
fmt.Println("初始化代理成功")
}
运行效果: