In Go,.proto
Files are file formats used to define Protocol Buffers data structures and services. Protocol Buffers is a language-independent, platform-independent, and extensible serialization mechanism.
Here is about Go.proto
Some important aspects of the document:
1. Define the data structure
- exist
.proto
In the file, you can use itmessage
Keywords define data structures. For example:
syntax = "proto3"; package example; message Person { string name = 1; int32 age = 2; }
Here is a name calledPerson
The message type contains two fields:name
(String type) andage
(Integer type).
2. Define services
- Available
service
Keyword definition RPC (Remote Procedure Call) service. For example:
syntax = "proto3"; package example; service Greeter { rpc SayHello (HelloRequest) returns (HelloReply) {} } message HelloRequest { string name = 1; } message HelloReply { string message = 1; }
Here is a name calledGreeter
service, including a service calledSayHello
The RPC method, which accepts aHelloRequest
type request and return aHelloReply
Type of response.
3. Generate Go code
useprotoc
Tools and corresponding Go plugins can.proto
The file is compiled into Go code. For example:
protoc --go_out=. --go_opt=paths=source_relative
This will generate.proto
The Go code file corresponding to the data structure and service defined in the file.
4. Use in Go code
The generated Go code can be imported and used in a Go project. For example:
package main import ( "context" "log" "example" ) func main() { client := (conn) resp, err := ((), &{Name: "world"}) if err!= nil { ("could not greet: %v", err) } ("Greeting: %s", ) }
Here it is assumed that a connection to the server has been established (conn
) and use the generatedGreeter
Client callsSayHello
method.
Anyway,.proto
Files provide a powerful way to define data structures and RPC services in the Go language, enabling efficient serialization and cross-language communication.
Next, let’s give a few more examples:
The following is one.proto
Examples of files generating multiple Go files.
Suppose we have a name calledThe content of the file is as follows:
syntax = "proto3"; package demo; message Product { string name = 1; float price = 2; } message Order { int32 id = 1; repeated Product products = 2; } service ProductService { rpc GetProduct(ProductRequest) returns (ProductResponse) {} } message ProductRequest { string name = 1; } message ProductResponse { Product product = 1; } service OrderService { rpc GetOrder(OrderRequest) returns (OrderResponse) {} } message OrderRequest { int32 id = 1; } message OrderResponse { Order order = 1; }
Use the following command to generate Go code:
protoc --go_out=. --go_opt=paths=source_relative
This will generate the following Go files:
-
:Include
Product
、Order
、ProductRequest
、ProductResponse
、OrderRequest
、OrderResponse
Definition of message types. -
demo_product_service.
:IncludeProductService
The client and server interface definitions of the service and related helper functions. -
demo_order_service.
:IncludeOrderService
The client and server interface definitions of the service and related helper functions.
In your Go code, you can use it like this:
package main import ( "context" "log" "demo" ) func main() { // Use ProductService productClient := (conn) productResp, err := ((), &{Name: "laptop"}) if err!= nil { ("could not get product: %v", err) } ("Product: %v", ) // Use OrderService orderClient := (conn) orderResp, err := ((), &{Id: 123}) if err!= nil { ("could not get order: %v", err) } ("Order: %v", ) }
Here it is assumed that a connection to the server has been established (conn
), the generatedProductService
andOrderService
client method.
The following is the above.proto
Explanation of Go code generated by various parts of the file:
message Product
Definition:
message Product { string name = 1; float price = 2; }
There will be a structure in the generated Go code to represent this message type. For example:
type Product struct { Name string Price float32 }
Note that in Go,float
Types are usually converted tofloat32
。
message Order
Definition:
message Order { int32 id = 1; repeated Product products = 2; }
The generated Go code is:
type Order struct { Id int32 Products []*Product }
hererepeated
The keyword represents a repeatable field, and a slice will be generated in Go.
service ProductService
Definition:
service ProductService { rpc GetProduct(ProductRequest) returns (ProductResponse) {} }
There will be an interface definition and implementation-related code between the client and server side in the generated code. For example:
type ProductServiceClient interface { GetProduct(ctx , in *ProductRequest, opts...) (*ProductResponse, error) } type ProductServiceServer interface { GetProduct(, *ProductRequest) (*ProductResponse, error) }
message ProductRequest
andmessage ProductResponse
Definition:
message ProductRequest { string name = 1; } message ProductResponse { Product product = 1; }
Generate the corresponding structure:
type ProductRequest struct { Name string } type ProductResponse struct { Product *Product }
service OrderService
Similar definitionProductService
, corresponding client and server interfaces and related code will be generated.
Overall,.proto
The file defines the data structure and service, throughprotoc
The Go code generated by the tool can be easily used in Go projects, achieving efficient data serialization and RPC communication.
Here is another example,.proto
The number of Go files generated by files mainly depends on which of the following factors
1. Message definition (Messages)
Each in.proto
Messages defined in the file (message
) will generate a corresponding Go structure. For example:
message Person { string name = 1; int32 age = 2; } message Address { string street = 1; string city = 2; }
This will generate two Go files, includingPerson
andAddress
Definition of structure.
2. Services definition (Services)
Each defined service (service
) generates a separate Go file containing the client and server interface definitions of the service and related helper functions. For example:
service UserService { rpc GetUser(UserRequest) returns (UserResponse) {} } service OrderService { rpc GetOrder(OrderRequest) returns (OrderResponse) {} }
This will generate two different Go files, one forUserService
, another forOrderService
。
3. Package Declaration
If.proto
There is a clear package declaration in the file, and the generated Go files will be organized by the package name. Multiple messages and services under the same package name may be generated into different files in the same directory, but they all belong to the same Go package. For example:
package mypackage; message Product { string name = 1; } service ProductService { rpc GetProduct(ProductRequest) returns (ProductResponse) {} }
The generated Go file will belong tomypackage
Package, and may generate the definitions of messages and services into different files according to specific generation rules and tool configurations, but they are all in the same package directory.
In summary,.proto
The number of Go files generated by a file depends on factors such as the number of messages, the number of services, and the package declaration. The generated files are usually organized in a clear structure for easy use and management in Go projects.
How many Go files are generated mainly look at.proto
The number of messages defined in the file, the number of services and whether there is a clear package declaration, these factors jointly determine the number and organization of the generated Go files.
for example:
Here is a simple one.proto
File example:
syntax = "proto3"; package example; message Book { string title = 1; string author = 2; } message Library { repeated Book books = 1; } service BookService { rpc GetBook(BookRequest) returns (BookResponse) {} } message BookRequest { string title = 1; } message BookResponse { Book book = 1; }
this.proto
The file will generate the following Go files:
- One contains
Book
andLibrary
A file for structure definition. - One contains
BookService
The client and server interface definitions of the service and the files of related helper functions. - One contains
BookRequest
andBookResponse
A file for structure definition.
So, there are three main parts in this simple example that generate three different Go files. The number of files generated depends on factors such as the number of messages and the number of services.
This is the article about the use of proto files in go language. For more related go language proto files, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!