雲原生 API 閘道器,gRPC-Gateway V2 初探

為少發表於2021-04-05

gRPC-Gateway 簡介

我們都知道 gRPC 並不是萬能的工具。 在某些情況下,我們仍然想提供傳統的 HTTP/JSON API。原因可能從保持向後相容性到支援程式語言或 gRPC 無法很好地支援的客戶端。但是僅僅為了公開 HTTP/JSON API 而編寫另一個服務是一項非常耗時且乏味的任務。

那麼,有什麼方法可以只編寫一次程式碼,卻可以同時在 gRPCHTTP/JSON 中提供 API

答案是 Yes

gRPC-GatewayGoogle protocol buffers compiler protoc 的外掛。 它讀取 protobuf service 定義並生成反向代理伺服器( reverse-proxy server) ,該伺服器將 RESTful HTTP API 轉換為 gRPC。 該伺服器是根據服務定義中的 google.api.http 批註(annotations)生成的。

這有助於你同時提供 gRPCHTTP/JSON 格式的 API

開始之前

在開始編碼之前,我們必須安裝一些工具。

在示例中,我們將使用 Go gRPC Server,因此請首先從 https://golang.org/dl/ 安裝 Go

安裝 Go 之後,請使用 go get 下載以下軟體包:

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

這將安裝我們生成存根所需的協議生成器外掛。確保將 $GOPATH/bin 新增到 $PATH 中,以便通過 go get 安裝的可執行檔案在 $PATH 中可用。

我們將在本教程的新模組中進行工作,因此,請立即在您選擇的資料夾中建立該模組:

建立 go.mod 檔案

使用 go mod init 命令啟動你的 module 以建立 go.mod 檔案。

執行 go mod init 命令,給它程式碼所在 module 的路徑。在這裡,使用 github.com/myuser/myrepo 作為 module 路徑—在生產程式碼中,這將是可以從其中下載 moduleURL

$ go mod init github.com/myuser/myrepo
go: creating new go.mod: module github.com/myuser/myrepo

go mod init 命令建立一個 go.mod 檔案,該檔案將您的程式碼標識為可以從其他程式碼中使用的 module。 您剛建立的檔案僅包含模組名稱和程式碼支援的 Go 版本。 但是,當您新增依賴項(即其他模組的軟體包)時,go.mod 檔案將列出要使用的特定 module 版本。 這樣可以使構建具有可複製性,並使您可以直接控制要使用的 module 版本。

用 gRPC 建立一個簡單的 hello world

為了瞭解 gRPC-Gateway,我們首先要製作一個 hello world gRPC 服務。

使用 protocol buffers 定義 gRPC service

在建立 gRPC 服務之前,我們應該建立一個 proto 檔案來定義我們需要的東西,這裡我們在 proto/helloworld/ 目錄下建立了一個名為 hello_world.proto 的檔案。

gRPC service 使用 Google Protocol Buffers 定義的。這裡定義如下:

syntax = "proto3";

package helloworld;

// The greeting service definition
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

// The request message containing the user's name
message HelloRequest {
  string name = 1;
}

// The response message containing the greetings
message HelloReply {
  string message = 1;
}

使用 buf 生成 stubs

Buf 是一個工具,它提供了各種 protobuf 實用程式,如 linting, breaking change detectiongeneration。請在 https://docs.buf.build/installation/ 上找到安裝說明。

它是通過 buf.yaml 檔案配置的,應將其檢入你儲存庫的根目錄中。 如果存在,Buf 將自動讀取此檔案。 也可以通過命令列標誌 --config 提供配置,該標誌接受 .json.yaml 檔案的路徑,或是直接 JSONYAML 資料。

所有使用本地 .proto 檔案作為輸入的 Buf 操作都依賴於有效的構建配置。這個配置告訴 Buf 在哪裡搜尋 .proto 檔案,以及如何處理匯入。與 protoc(所有 .proto 檔案都是在命令列上手動指定的)不同,buf 的操作方式是遞迴地發現配置下的所有 .proto 檔案並構建它們。

下面是一個有效配置的示例,假設您的 .proto 檔案根位於相對於儲存庫根的 proto 資料夾中。

version: v1beta1
name: buf.build/myuser/myrepo
build:
  roots:
    - proto

要為 Go 生成 typegRPC stubs,請在儲存庫的根目錄下建立檔案 buf.gen.yaml

version: v1beta1
plugins:
  - name: go
    out: proto
    opt: paths=source_relative
  - name: go-grpc
    out: proto
    opt: paths=source_relative

我們使用 gogo-grpc 外掛生成 Go typesgRPC service 定義。我們正在輸出相對於 proto 資料夾的生成檔案,並使用 path=source_relative 選項,這意味著生成的檔案將與源 .proto 檔案顯示在同一目錄中。

然後執行:

$ buf generate

這將為我們的 proto 檔案層次結構中的每個 protobuf 軟體包生成一個 *.pb.go*_grpc.pb.go 檔案。

使用 protoc 生成 stubs

這是一個 protoc 命令可能會生成 Go stubs 的示例,假設您位於儲存庫的根目錄,並且您的 proto 檔案位於一個名為 proto 的目錄中:

$ protoc -I ./proto \
   --go_out ./proto --go_opt paths=source_relative \
   --go-grpc_out ./proto --go-grpc_opt paths=source_relative \
   ./proto/helloworld/hello_world.proto

我們使用 gogo-grpc 外掛生成 Go typesgRPC service 定義。我們正在輸出相對於 proto 資料夾的生成檔案,並使用 path=source_relative 選項,這意味著生成的檔案將與源 .proto 檔案顯示在同一目錄中。

這將為 proto/helloworld/hello_world.proto 生成一個 *.pb.go*_grpc.pb.go 檔案。

建立 main.go

在建立 main.go 檔案之前,我們假設使用者已經建立了一個名為 github.com/myuser/myrepogo.mod。此處的 import 使用的是相對於儲存庫根目錄的 proto/helloworld 中生成的檔案的路徑。

package main

import (
	"context"
	"log"
	"net"

	"google.golang.org/grpc"

	helloworldpb "github.com/myuser/myrepo/proto/helloworld"
)

type server struct{}

func NewServer() *server {
	return &server{}
}

func (s *server) SayHello(ctx context.Context, in *helloworldpb.HelloRequest) (*helloworldpb.HelloReply, error) {
	return &helloworldpb.HelloReply{Message: in.Name + " world"}, nil
}

func main() {
	// Create a listener on TCP port
	lis, err := net.Listen("tcp", ":8080")
	if err != nil {
		log.Fatalln("Failed to listen:", err)
	}

	// Create a gRPC server object
	s := grpc.NewServer()
	// Attach the Greeter service to the server
	helloworldpb.RegisterGreeterServer(s, &server{})
	// Serve gRPC Server
	log.Println("Serving gRPC on 0.0.0.0:8080")
	log.Fatal(s.Serve(lis))
}

將 gRPC-Gateway 批註新增到現有的 proto 檔案中

現在,我們已經可以使用 Go gRPC 伺服器,我們需要新增 gRPC-Gateway 批註。

批註定義了 gRPC 服務如何對映到 JSON 請求和響應。 使用 protocol buffers 時,每個 RPC 必須使用 google.api.http 批註定義 HTTP 方法和路徑。

因此,我們需要將 google/api/http.proto 匯入新增到 proto 檔案中。我們還需要新增所需的 HTTP->gRPC 對映。在這種情況下,我們會將 POST /v1/example/echo 對映到我們的 SayHello RPC

syntax = "proto3";

package helloworld;

import "google/api/annotations.proto";

// Here is the overall greeting service definition where we define all our endpoints
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {
    option (google.api.http) = {
      post: "/v1/example/echo"
      body: "*"
    };
  }
}

// The request message containing the user's name
message HelloRequest {
  string name = 1;
}

// The response message containing the greetings
message HelloReply {
  string message = 1;
}

生成 gRPC-Gateway stubs

現在我們已經將 gRPC-Gateway 批註新增到了 proto 檔案中,我們需要使用 gRPC-Gateway 生成器來生成存根(stubs)。

使用 buf

我們需要將 gRPC-Gateway 生成器新增到生成配置中:

version: v1beta1
plugins:
  - name: go
    out: proto
    opt: paths=source_relative
  - name: go-grpc
    out: proto
    opt: paths=source_relative,require_unimplemented_servers=false
  - name: grpc-gateway
    out: proto
    opt: paths=source_relative

我們還需要將 googleapis 依賴項新增到我們的 buf.yaml 檔案中:

version: v1beta1
name: buf.build/myuser/myrepo
deps:
  - buf.build/beta/googleapis
build:
  roots:
    - proto

然後,我們需要執行 buf beta mod update 以選擇要使用的依賴項版本。

就是這樣!現在,如果您執行:

$ buf generate

它應該產生一個 *.gw.pb.go 檔案。

使用 protoc

在使用 protoc 生成 stubs 之前,我們需要將一些依賴項複製到我們的 proto 檔案結構中。將一部分 googleapis 從官方儲存庫複製到您本地的原始檔案結構中。之後看起來應該像這樣:

proto
├── google
│   └── api
│       ├── annotations.proto
│       └── http.proto
└── helloworld
    └── hello_world.proto

現在我們需要將 gRPC-Gateway 生成器新增到 protoc 呼叫中:

$ protoc -I ./proto \
  --go_out ./proto --go_opt paths=source_relative \
  --go-grpc_out ./proto --go-grpc_opt paths=source_relative \
  --grpc-gateway_out ./proto --grpc-gateway_opt paths=source_relative \
  ./proto/helloworld/hello_world.proto

這將生成一個 *.gw.pb.go 檔案。

我們還需要在 main.go 檔案中新增 gRPC-Gateway 多路複用器(mux)併為其提供服務。

package main

import (
	"context"
	"log"
	"net"
	"net/http"

	"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
	"google.golang.org/grpc"

	helloworldpb "github.com/myuser/myrepo/proto/helloworld"
)

type server struct{
	helloworldpb.UnimplementedGreeterServer
}

func NewServer() *server {
	return &server{}
}

func (s *server) SayHello(ctx context.Context, in *helloworldpb.HelloRequest) (*helloworldpb.HelloReply, error) {
	return &helloworldpb.HelloReply{Message: in.Name + " world"}, nil
}

func main() {
	// Create a listener on TCP port
	lis, err := net.Listen("tcp", ":8080")
	if err != nil {
		log.Fatalln("Failed to listen:", err)
	}

	// Create a gRPC server object
	s := grpc.NewServer()
	// Attach the Greeter service to the server
	helloworldpb.RegisterGreeterServer(s, &server{})
	// Serve gRPC server
	log.Println("Serving gRPC on 0.0.0.0:8080")
	go func() {
		log.Fatalln(s.Serve(lis))
	}()

	// Create a client connection to the gRPC server we just started
	// This is where the gRPC-Gateway proxies the requests
	conn, err := grpc.DialContext(
		context.Background(),
		"0.0.0.0:8080",
		grpc.WithBlock(),
		grpc.WithInsecure(),
	)
	if err != nil {
		log.Fatalln("Failed to dial server:", err)
	}

	gwmux := runtime.NewServeMux()
	// Register Greeter
	err = helloworldpb.RegisterGreeterHandler(context.Background(), gwmux, conn)
	if err != nil {
		log.Fatalln("Failed to register gateway:", err)
	}

	gwServer := &http.Server{
		Addr:    ":8090",
		Handler: gwmux,
	}

	log.Println("Serving gRPC-Gateway on http://0.0.0.0:8090")
	log.Fatalln(gwServer.ListenAndServe())
}

測試 gRPC-Gateway

現在我們可以啟動伺服器了:

$ go run main.go

然後,我們使用 cURL 傳送 HTTP 請求:

$ curl -X POST -k http://localhost:8090/v1/example/echo -d '{"name": " hello"}'
{"message":"hello world"}

Refs

我是為少
微信:uuhells123
公眾號:黑客下午茶
加我微信(互相學習交流),關注公眾號(獲取更多學習資料~)

相關文章