gin 上使用 Grpc 入門
要在 Go 中使用基於 Gin 的 gRPC,你需要執行以下步驟:
- 安裝 gRPC:使用以下命令安裝 gRPC:
go get -u google.golang.org/grpc
- 安裝 protoc-gen-go:使用以下命令安裝 protoc-gen-go 插件,它用於將 protocol buffer 文件生成 Go 代碼:
go get -u github.com/golang/protobuf/protoc-gen-go
- 創建一個 protocol buffer 文件:創建一個
.proto
文件,定義你的 gRPC 服務和消息類型。例如,創建一個名爲example.proto
的文件,並在其中定義你的服務和消息類型:
syntax = "proto3";
package example;
service HelloService {
rpc SayHello (HelloRequest) returns (HelloResponse);
}
message HelloRequest {
string name = 1;
}
message HelloResponse {
string message = 1;
}
上述文件中的內容定義了一個名爲example
的包,幷包含一個HelloService
服務。在這個服務中,定義了一個名爲SayHello
的 RPC 方法,它接收一個HelloRequest
消息作爲輸入,並返回一個HelloResponse
消息作爲輸出。
HelloRequest
消息包含一個name
字段,類型爲字符串,用於傳遞一個名稱。
HelloResponse
消息包含一個message
字段,類型爲字符串,用於傳遞一個消息。
- 生成 Go 代碼:使用
protoc
命令生成 Go 代碼。在命令行中運行以下命令:
protoc --go_out=plugins=grpc:. example.proto
這將生成一個名爲example.pb.go
的 Go 文件,其中包含生成的 gRPC 代碼。
- 創建一個基於 Gin 的 gRPC 服務器:創建一個 Go 文件,並使用以下代碼創建一個基於 Gin 的 gRPC 服務器:
package main
import (
"context"
"example" //引入生成的Go代碼
"github.com/gin-gonic/gin"
"google.golang.org/grpc"
"net/http"
"strconv"
)
func main() {
r := gin.Default()
// 創建一個gRPC連接
conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())
if err != nil {
panic(err)
}
defer conn.Close()
// 創建一個gRPC客戶端
client := example.NewHelloServiceClient(conn)
// 定義一個Gin路由
r.POST("/say-hello", func(c *gin.Context) {
name := c.PostForm("name")
// 調用gRPC服務
req := &example.HelloRequest{Name: name}
res, err := client.SayHello(context.Background(), req)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err})
return
}
c.JSON(http.StatusOK, gin.H{"message": res.Message})
})
// 啓動Gin服務器
if err := r.Run(":8080"); err != nil {
panic(err)
}
}
此代碼創建了一個名爲say-hello
的 POST 路由,它通過調用 gRPC 服務將請求轉發到HelloService.SayHello
方法,並返回響應。
- 啓動服務器:在命令行中執行以下命令啓動服務器:
go run main.go
現在,你可以發送一個 POST 請求到http://localhost:8080/say-hello
,並在請求的主體中包含一個name
參數,服務器將將其轉發到 gRPC 服務,並返回相應的消息。
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/SW6JHacWuNAPuB0ge1fv0w