上一篇文章中,我使用net/rpc包實現了一個簡單的RPC接口,並嘗試了net/rpc自帶的Gob編碼和JSON編碼,學習了Golang的一些基礎知識遠端過程呼叫。在這篇文章中,我將結合 net/rpc 和 protobuf 並創建我的 protobuf 外掛程式來幫助我們產生程式碼,所以讓我們開始吧。
本文首發於Medium MPP計畫。如果您是 Medium 用戶,請在 Medium 上關注我。非常感謝。
我們在工作上肯定使用過gRPC和protobuf,但是它們並沒有綁定。 gRPC可以使用JSON編碼,protobuf可以使用其他語言實作。
協定緩衝區(Protobuf)是一種免費開源跨平台資料格式,用於序列化結構化資料。它對於開發透過網路相互通訊或儲存資料的程式很有用。該方法涉及一種描述某些資料結構的介面描述語言和一個根據該描述生成原始程式碼的程序,用於生成或解析表示結構化資料的位元組流。
使用 protobuf 的範例
首先我們寫一個原型檔案 hello-service.proto ,它定義了一則訊息「String」
syntax = "proto3"; package api; option go_package="api"; message String { string value = 1; }
然後使用 protoc 實用程式產生訊息字串的 Go 程式碼
protoc --go_out=. hello-service.proto
然後我們修改 Hello 函數的參數以使用 protobuf 檔案產生的字串。
type HelloServiceInterface = interface { Hello(request api.String, reply *api.String) error }
使用起來和以前沒有什麼不同,甚至不如直接使用string那麼方便。那我們為什麼要使用protobuf呢?如我前面所說,使用Protobuf定義與語言無關的RPC服務介面和訊息,然後使用protoc工具產生不同語言的程式碼,才是它真正的價值所在。例如使用官方插件protoc-gen-go產生gRPC程式碼。
protoc --go_out=plugins=grpc. hello-service.proto
protoc 的插件系統
要從 protobuf 檔案產生程式碼,我們必須安裝 protoc ,但是 protoc 不知道我們的目標語言是什麼,所以我們需要外掛程式來幫助我們產生程式碼。 protoc的插件系統如何運作?以上面的grpc為例。
這裡有一個--go_out參數。由於我們所呼叫的插件是protoc-gen-go,因此參數稱為go_out;如果名稱是 XXX,則該參數將被稱為 XXX_out。
protoc執行時,首先會解析protobuf文件,產生一組Protocol Buffers編碼的描述性資料。它首先會判斷protoc中是否包含go插件,然後會嘗試在$PATH中尋找protoc-gen-go,如果找不到就會報錯,然後將運行 protoc-gen-go。 protoc-gen-go 命令並透過 stdin 將描述資料傳送到插件命令。插件產生檔案內容後,會將 Protocol Buffers 編碼的資料輸入到 stdout,告訴 protoc 產生特定的檔案。
plugins=grpc 是 protoc-gen-go 附帶的插件,以便調用它。如果你不使用它,它只會在Go中產生一條訊息,但你可以使用這個插件來產生grpc相關的程式碼。
自訂協定插件
如果我們在protobuf中加入Hello介面計時,是不是可以自訂一個protoc外掛程式來直接產生程式碼?
syntax = "proto3"; package api; option go_package="./api"; service HelloService { rpc Hello (String) returns (String) {} } message String { string value = 1; }
客觀的
對於本文,我的目標是建立一個插件,然後用於產生 RPC 伺服器端和客戶端程式碼,如下所示。
// HelloService_rpc.pb.go type HelloServiceInterface interface { Hello(String, *String) error } func RegisterHelloService( srv *rpc.Server, x HelloServiceInterface, ) error { if err := srv.RegisterName("HelloService", x); err != nil { return err } return nil } type HelloServiceClient struct { *rpc.Client } var _ HelloServiceInterface = (*HelloServiceClient)(nil) func DialHelloService(network, address string) ( *HelloServiceClient, error, ) { c, err := rpc.Dial(network, address) if err != nil { return nil, err } return &HelloServiceClient{Client: c}, nil } func (p *HelloServiceClient) Hello( in String, out *String, ) error { return p.Client.Call("HelloService.Hello", in, out) }
這會將我們的業務代碼更改為如下所示
// service func main() { listener, err := net.Listen("tcp", ":1234") if err != nil { log.Fatal("ListenTCP error:", err) } _ = api.RegisterHelloService(rpc.DefaultServer, new(HelloService)) for { conn, err := listener.Accept() if err != nil { log.Fatal("Accept error:", err) } go rpc.ServeConn(conn) } } type HelloService struct{} func (p *HelloService) Hello(request api.String, reply *api.String) error { log.Println("HelloService.proto Hello") *reply = api.String{Value: "Hello:" + request.Value} return nil } // client.go func main() { client, err := api.DialHelloService("tcp", "localhost:1234") if err != nil { log.Fatal("net.Dial:", err) } reply := &api.String{} err = client.Hello(api.String{Value: "Hello"}, reply) if err != nil { log.Fatal(err) } log.Println(reply) }
從產生的程式碼來看,我們的工作量已經小很多了,出錯的機會也已經很小了。一個好的開始。
根據上面的api程式碼,我們可以拉出一個模板檔:
const tmplService = ` import ( "net/rpc") type {{.ServiceName}}Interface interface { func Register{{.ServiceName}}( if err := srv.RegisterName("{{.ServiceName}}", x); err != nil { return err } return nil} *rpc.Client} func Dial{{.ServiceName}}(network, address string) ( {{range $_, $m := .MethodList}} return p.Client.Call("{{$root.ServiceName}}.{{$m.MethodName}}", in, out)} `
整個模板很清晰,裡面有一些佔位符,像是MethodName、ServiceName等,我們稍後會介紹。
如何開發插件?
Google 發布了 Go 語言 API 1,引入了新的套件 google.golang.org/protobuf/compile R/protogen,大大降低了外掛程式開發的難度:
- First of all, we create a go language project, such as protoc-gen-go-spprpc
- Then we need to define a protogen.Options, then call its Run method, and pass in a func(*protogen.Plugin) error callback. This is the end of the main process code.
- We can also set the ParamFunc parameter of protogen.Options, so that protogen will automatically parse the parameters passed by the command line for us. Operations such as reading and decoding protobuf information from standard input, encoding input information into protobuf and writing stdout are all handled by protogen. What we need to do is to interact with protogen.Plugin to implement code generation logic.
The most important thing for each service is the name of the service, and then each service has a set of methods. For the method defined by the service, the most important thing is the name of the method, as well as the name of the input parameter and the output parameter type. Let's first define a ServiceData to describe the meta information of the service:
// ServiceData type ServiceData struct { PackageName string ServiceName string MethodList []Method } // Method type Method struct { MethodName string InputTypeName string OutputTypeName string }
Then comes the main logic, and the code generation logic, and finally the call to tmpl to generate the code.
func main() { protogen.Options{}.Run(func(gen *protogen.Plugin) error { for _, file := range gen.Files { if !file.Generate { continue } generateFile(gen, file) } return nil }) } // generateFile function definition func generateFile(gen *protogen.Plugin, file *protogen.File) { filename := file.GeneratedFilenamePrefix + "_rpc.pb.go" g := gen.NewGeneratedFile(filename, file.GoImportPath) tmpl, err := template.New("service").Parse(tmplService) if err != nil { log.Fatalf("Error parsing template: %v", err) } packageName := string(file.GoPackageName) // Iterate over each service to generate code for _, service := range file.Services { serviceData := ServiceData{ ServiceName: service.GoName, PackageName: packageName, } for _, method := range service.Methods { inputType := method.Input.GoIdent.GoName outputType := method.Output.GoIdent.GoName serviceData.MethodList = append(serviceData.MethodList, Method{ MethodName: method.GoName, InputTypeName: inputType, OutputTypeName: outputType, }) } // Perform template rendering err = tmpl.Execute(g, serviceData) if err != nil { log.Fatalf("Error executing template: %v", err) } } }
Debug plugin
Finally, we put the compiled binary execution file protoc-gen-go-spprpc in $PATH, and then run protoc to generate the code we want.
protoc --go_out=.. --go-spprpc_out=.. HelloService.proto
Because protoc-gen-go-spprpc has to depend on protoc to run, it's a bit tricky to debug. We can use
fmt.Fprintf(os.Stderr, "Fprintln: %v\n", err)
To print the error log to debug.
Summary
That's all there is to this article. We first implemented an RPC call using protobuf and then created a protobuf plugin to help us generate the code. This opens the door for us to learn protobuf + RPC, and is our path to a thorough understanding of gRPC. I hope everyone can master this technology.
Reference
- https://taoshu.in/go/create-protoc-plugin.html
- https://chai2010.cn/advanced-go-programming-book/ch4-rpc/ch4-02-pb-intro.html
以上是RPC 操作 EPU 使用 Protobuf 並建立自訂插件的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Go語言使用"encoding/binary"包進行二進制編碼與解碼。 1)該包提供binary.Write和binary.Read函數,用於數據的寫入和讀取。 2)需要注意選擇正確的字節序(如BigEndian或LittleEndian)。 3)數據對齊和錯誤處理也是關鍵,確保數據的正確性和性能。

1)usebybytes.joinforconcatenatinges,2)bytes.bufferforincrementalwriting,3)bytes.indexorbytes.indexorbytes.indexbyteforsearching bytes.bytes.readereforrednorederencretingnchunknunknchunknunk.sss.inc.softes.4)

theencoding/binarypackageingoiseforporptimizingBinaryBinaryOperationsDuetoitssupportforendiannessessandefficityDatahandling.toenhancePerformance:1)usebinary.nativeendiandiandiandiandiandiandiandian nessideendian toavoid avoidByteByteswapping.2)

Go的bytes包主要用於高效處理字節切片。 1)使用bytes.Buffer可以高效進行字符串拼接,避免不必要的內存分配。 2)bytes.Equal函數用於快速比較字節切片。 3)bytes.Index、bytes.Split和bytes.ReplaceAll函數可用於搜索和操作字節切片,但需注意性能問題。

字節包提供了多種功能來高效處理字節切片。 1)使用bytes.Contains檢查字節序列。 2)用bytes.Split分割字節切片。 3)通過bytes.Replace替換字節序列。 4)用bytes.Join連接多個字節切片。 5)利用bytes.Buffer構建數據。 6)結合bytes.Map進行錯誤處理和數據驗證。

Go的encoding/binary包是處理二進制數據的工具。 1)它支持小端和大端字節序,可用於網絡協議和文件格式。 2)可以通過Read和Write函數處理複雜結構的編碼和解碼。 3)使用時需注意字節序和數據類型的一致性,尤其在不同系統間傳輸數據時。該包適合高效處理二進制數據,但需謹慎管理字節切片和長度。

“字節”包裝封裝becapeitoffersefficerSoperationsOnbyteslices,cocialforbinarydatahandling,textPrococessing,andnetworkCommunications.byteslesalemutable,允許forforforforforformance-enhangingin-enhangingin-placemodifications,makaythisspackage

go'sstringspackageIncludeSessentialFunctionsLikeContains,trimspace,split,andreplaceAll.1)contunsefefitedsseffitedsfificeCheckSforSubStrings.2)trimspaceRemovesWhitespaceToeensuredity.3)splitparsentertparsentertparsentertparsentertparstructedtextlikecsv.4)report textlikecsv.4)


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!