[go] use protobuf for serialization and deserialization

Time:2021-1-24

Define the message type first

orders.proto

syntax = "proto2";
package message;
message Orders {
required int32 order_id=1;
required string title=2;
}

Create a directory in gopath, compile the message type and output it to the directory. The package name is message

mkdir $GOPATH/src/message;protoc --go_out $GOPATH/src/message orders.proto 

Write go file to serialize and deserialize the type structure data in the package just generated

package main

import "message"

import "github.com/golang/protobuf/proto"

import "fmt"

func main() {
    orders := &message.Orders{
        OrderId: proto.Int32(1),
        Title:    proto.String (the "first order"),
    }
    //Serialization into binary data
    ordersBytes, _ := proto.Marshal(orders)
    //Deserializing binary data
    twoOrders := &message.Orders{}
    proto.Unmarshal(ordersBytes, twoOrders)
    fmt.Println(twoOrders.GetTitle())
    fmt.Println(twoOrders.GetOrderId())

}

Recommended Today

Use of Android WebView (super detailed usage)

1.1 overview of WebView Android WebView is a special view on the Android platform. It can be used to display web pages. This WebView class can be used to display only one online web page in the app. Of course, it can also be used to develop browsers. The internal implementation of WebView uses WebKit […]