1:安装依赖工具
go install \
github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-grpc-gateway \
github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2 \
google.golang.org/protobuf/cmd/protoc-gen-go \
google.golang.org/grpc/cmd/protoc-gen-go-grpc
2:添加依赖的proto文件到项目中,
google/api/annotations.proto
依赖文件仓库地址: https://github.com/googleapis/googleapis
3: 编写proto 文件:
syntax = "proto3";
package iam.v1;
option go_package = "/proto";
// 导入google/api/annotations.proto
import "google/api/annotations.proto";
message Permission {
string user_id = 1;
string tenant_id = 2;
string resource = 3;
string action = 4;
}
message HasPermissionReq {
Permission permission =1;
}
message HasPermissionRes {
bool ok =1;
}
service IamGrpcService {
rpc HasPermission (HasPermissionReq) returns (HasPermissionRes) {
option (google.api.http) = {
post: "/iam/v1/has_permission"
body: "*"
};
};
}
4: 生成go 文件:
#!/bin/bash
#protoc --go_out=:./ --go-grpc_out=. *.proto
protoc -I . --grpc-gateway_out ./proto \
--grpc-gateway_opt logtostderr=true \
--grpc-gateway_opt paths=source_relative \
*.proto
5: 编写反向代理服务:
func runGrpcGateway(config *conf.Config) error {
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
// Register gRPC server endpoint
// Note: Make sure the gRPC server is running properly and accessible
mux := runtime.NewServeMux()
opts := []grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())}
grpcServerEndpoint := fmt.Sprintf("localhost:%s", config.RpcServer.Port)
err := proto.RegisterIamGrpcServiceHandlerFromEndpoint(ctx, mux, grpcServerEndpoint, opts)
if err != nil {
log.Error("new grpc gateway reverse server error:" + err.Error())
return err
}
// Start HTTP server (and proxy calls to gRPC server endpoint)
return http.ListenAndServe(":18081", mux)
}