七、Golang gRPC-Gateway 使用

61 阅读1分钟

gRPC Gateway 是 protoc 的一个插件。它能读取 gRPC 服务的定义和生成一个反向代理服务,将 RESTful JSON API 翻译成 gRPC。 这个服务根据用户自定的 gRPC 服务的来生成。

image.png

代码实践

开发环境:
golang 1.20.1
protoc libprotoc 3.20.3

$ go install github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-grpc-gateway@latest
$ go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
$ go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest

google/api 文件在这里下载:github.com/googleapis/… 目录结构

.
├── com
│   └── example
│       ├── echo
│       │   ├── echo.go
│       │   ├── echo.pb.go
│       │   ├── echo.pb.gw.go
│       │   ├── echo.proto
│       │   ├── echo_grpc.pb.go
│       │   ├── login.go
│       │   └── utils.go
│       ├── google
│       │   └── api
│       │       ├── annotations.proto
│       │       └── http.proto
│       └── http
│           ├── client.go
│           └── server.go
├── go.mod
└── go.sum

echo.proto

syntax = "proto3";

package echo;

option go_package = "com/example/echo";

import "google/api/annotations.proto";

import "google/protobuf/empty.proto";

service EchoService{
  rpc UnaryEchoWithHttp(google.protobuf.Empty) returns(EchoResponse){
    option (google.api.http) = {
      get:"/hello"
    };
  }
}

server.go

package main

import (
 "context"
 "example.com/com/example/echo"
 "github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
 "google.golang.org/grpc"
 "google.golang.org/grpc/credentials/insecure"
 "log"
 "net"
 "net/http"
)

func main() {
 server := grpc.NewServer()
 echo.RegisterEchoServiceServer(server, &echo.EchoService{})
 listen, err := net.Listen("tcp", ":8080")
 if err != nil {
  log.Print(err.Error())
 }
 log.Print("listen on port:8080 >>>>")

 go func() {
  log.Fatalln(server.Serve(listen))
 }()

 // gRPC-Gateway 将HTTP请求转为RPC请求
 conn, err := grpc.DialContext(
  context.Background(),
  "0.0.0.0:8080",
  grpc.WithBlock(),
  grpc.WithTransportCredentials(insecure.NewCredentials()),
 )
 if err != nil {
  log.Fatalln("Failed to dial server:", err)
 }

 gwmux := runtime.NewServeMux()
 // 注册 Echo
 err = echo.RegisterEchoServiceHandler(context.Background(), gwmux, conn)
 if err != nil {
  log.Fatalln("Failed to register gateway:", err)
 }

 gwServer := &http.Server{
  Addr:    ":8090",
  Handler: gwmux,
 }
 
 // 提供gRPC-Gateway服务
 log.Println("Serving gRPC-Gateway on http://0.0.0.0:8090")
 log.Fatalln(gwServer.ListenAndServe())
}

启动服务,通过curl来访问正常。

 > curl http://localhost:8090/hello
{"message":"hello world"}%

gRPC-Gateway 还有一些细节和其他的内容,可以通过阅读官方文档来学习。 grpc-ecosystem.github.io/grpc-gatewa…