Home Backend Development Golang Using Google Protocol Buffers for data serialization in Go language

Using Google Protocol Buffers for data serialization in Go language

Jun 16, 2023 pm 02:13 PM
go language google protocol buffers Data serialization

Google Protocol Buffers (hereinafter referred to as ProtoBuf) is a lightweight and efficient data serialization format that is widely used for data transmission and storage in distributed systems. As a modern programming language, Go language is also very friendly in supporting ProtoBuf. This article will introduce how to use ProtoBuf for data serialization in Go language.

1. Install ProtoBuf

Before you start using ProtoBuf, you need to install it first. You can download the binary package corresponding to the operating system from the official website (https://developers.google.com/protocol-buffers/) for installation, or you can use the system package manager to install (such as Ubuntu: sudo apt-get install protobuf-compiler ).

After the installation is complete, you can use the following command to check whether the installation is successful:

$ protoc --version
libprotoc 3.6.1

2. Define the message format

Before using ProtoBuf for data serialization, the message format needs to be defined first. In ProtoBuf, the message format is defined through .proto files. For example, we define a message format named Person:

syntax = "proto3";

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

where syntax specifies the syntax version used by ProtoBuf, message defines a message type, and name, age, and address are fields in the message. Fields are specified by numeric identifiers, which must be unique.

It is worth noting that ProtoBuf supports nested message types, and one message type can be defined as a field of another message type.

3. Compile and generate Go code

ProtoBuf needs to compile the .proto file into the code of the corresponding language for use in the program. In the Go language, you can use the protoc-gen-go plug-in for compilation, or you can use the github.com/golang/protobuf/protoc-gen-go plug-in for compilation. This article takes the first method as an example to introduce.

First you need to install the plug-in:

$ go get -u github.com/golang/protobuf/protoc-gen-go

Then use the following command to compile the .proto file:

$ protoc --go_out=. *.proto

This will generate a Go file named person.pb.go, which contains the definition of the Person message type and serialization and deserialization ation related methods.

4. Use ProtoBuf for data serialization

It is very simple to use ProtoBuf for data serialization in the program. Taking the Person message as an example, we can use the following code to serialize a Person object into binary data:

package main

#import (

"log"

"github.com/golang/protobuf/proto"
Copy after login
Copy after login

)

func main() {

p := &Person{
    Name:    "Tom",
    Age:     20,
    Address: []string{"Shanghai", "Beijing"},
}

data, err := proto.Marshal(p)
if err != nil {
    log.Fatal("marshaling error: ", err)
}

log.Println(data)
Copy after login

}

In the above code, we first create a Person object p, then call the proto.Marshal method to serialize it into binary data and print it come out. Note that when using the proto.Marshal method, you need to pass in a pointer to the Person object.

5. Use ProtoBuf for data deserialization

Similar to data serialization, using ProtoBuf for data deserialization is also very simple. We can use the following code to deserialize the serialized binary data into a Person object:

package main

import (

"log"

"github.com/golang/protobuf/proto"
Copy after login
Copy after login

)

func main() {

data := []byte{10, 3, 84, 111, 109, 16, 20, 26, 8, 83, 104, 97, 110, 103, 104, 97, 105, 18, 7, 66, 101, 105, 106, 105, 110, 103}

p := &Person{}
err := proto.Unmarshal(data, p)

if err != nil {
    log.Fatal("unmarshaling error: ", err)
}

log.Println(p)
Copy after login

}

In the above code, we first define a binary data, then call the proto.Unmarshal method to deserialize it into a Person object and print it out .

6. Summary

In this article, we introduced how to use ProtoBuf for data serialization in Go language. It should be noted that when using ProtoBuf for data serialization and deserialization, the message format must be defined and compiled to generate code in the corresponding language. In addition, using ProtoBuf for data serialization and deserialization is very simple. You only need to call the corresponding method to complete.

The above is the detailed content of Using Google Protocol Buffers for data serialization in Go language. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

What is the difference between `var` and `type` keyword definition structure in Go language? What is the difference between `var` and `type` keyword definition structure in Go language? Apr 02, 2025 pm 12:57 PM

Two ways to define structures in Go language: the difference between var and type keywords. When defining structures, Go language often sees two different ways of writing: First...

Which libraries in Go are developed by large companies or provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

In Go programming, how to correctly manage the connection and release resources between Mysql and Redis? In Go programming, how to correctly manage the connection and release resources between Mysql and Redis? Apr 02, 2025 pm 05:03 PM

Resource management in Go programming: Mysql and Redis connect and release in learning how to correctly manage resources, especially with databases and caches...

See all articles