SoFunction
Updated on 2025-03-02

Use of proto files in go language

In Go,.protoFiles 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.protoSome important aspects of the document:

1. Define the data structure

  • exist.protoIn the file, you can use itmessageKeywords define data structures. For example:
syntax = "proto3";

package example;

message Person {
  string name = 1;
  int32 age = 2;
}

Here is a name calledPersonThe message type contains two fields:name(String type) andage(Integer type).

2. Define services

  • AvailableserviceKeyword 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 calledGreeterservice, including a service calledSayHelloThe RPC method, which accepts aHelloRequesttype request and return aHelloReplyType of response.

3. Generate Go code

useprotocTools and corresponding Go plugins can.protoThe file is compiled into Go code. For example:

protoc --go_out=. --go_opt=paths=source_relative 

This will generate.protoThe 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 generatedGreeterClient callsSayHellomethod.

Anyway,.protoFiles 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.protoExamples 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:

  • :IncludeProductOrderProductRequestProductResponseOrderRequestOrderResponseDefinition of message types.
  • demo_product_service.:IncludeProductServiceThe client and server interface definitions of the service and related helper functions.
  • demo_order_service.:IncludeOrderServiceThe 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 generatedProductServiceandOrderServiceclient method.

The following is the above.protoExplanation of Go code generated by various parts of the file:

message ProductDefinition:

   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,floatTypes are usually converted tofloat32

message OrderDefinition:

   message Order {
       int32 id = 1;
       repeated Product products = 2;
   }

The generated Go code is:

   type Order struct {
       Id       int32
       Products []*Product
   }

hererepeatedThe keyword represents a repeatable field, and a slice will be generated in Go.

service ProductServiceDefinition:

   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 ProductRequestandmessage ProductResponseDefinition:

   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 OrderServiceSimilar definitionProductService, corresponding client and server interfaces and related code will be generated.

Overall,.protoThe file defines the data structure and service, throughprotocThe Go code generated by the tool can be easily used in Go projects, achieving efficient data serialization and RPC communication.

Here is another example,.protoThe number of Go files generated by files mainly depends on which of the following factors

1. Message definition (Messages)

Each in.protoMessages 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, includingPersonandAddressDefinition 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.protoThere 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 tomypackagePackage, 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,.protoThe 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.protoThe 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.protoFile 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.protoThe file will generate the following Go files:

  • One containsBookandLibraryA file for structure definition.
  • One containsBookServiceThe client and server interface definitions of the service and the files of related helper functions.
  • One containsBookRequestandBookResponseA 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!