Use of Protocolbuff in Golang

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Protocolbuff is an open-source serialization protocol from Google that almost supports all the mainstream languages on the market. The network transport protocol used as a server or server or a client-server is no more appropriate. Simply write a demo.
Project structure:

ProtocolBuff    ----Makefile    ----src           ----github.com/golang/protobuf           ----main           ----protocol

Configuration Protocol:
Protocol/protocol.proto

package protocol;enum ItemType{        USERITEM  = 1;        EQUIPMENT = 2;};message ItemInfo{        optional int32 ID = 1;        optional int32 Type = 2;        optional string Name = 3;        optional int32 Amount = 4;};

Executes PROTOC--go_out=./Protocol.proto automatically generates PROTOCOL.PB.GO, generating the directory as the current directory. PROTOC supports the generation of multiple languages, with protoc-h viewing.

Main/main.go

package mainimport (    "github.com/golang/protobuf/proto"    "fmt"    "protocol")func main() {    item := protocol.ItemInfo{        ID : proto.Int32(10),        Type : proto.Int32(1),        Name : proto.String("item_0"),        Amount: proto.Int32(99),    }    data := EncodeMsg(&item)//封包    fmt.Printf("Encode Data %v \n", data)    res := DecodeMsg(data)//解包    fmt.Printf("Decode Data %v \n", res.String())}func EncodeMsg(pb proto.Message) []byte{    data, err := proto.Marshal(pb)    if err != nil{        fmt.Errorf("%v \n",err.Error())    }    return data}func DecodeMsg(data []byte)  (result protocol.ItemInfo){    proto.Unmarshal(data, &result)    return}

Makefile

GOPATH := $(shell pwd)all:        GOPATH=${GOPATH} go install main

After make, the executable file is generated in the Bin directory, main, and the results are executed:
Encode Data [8 10 16 1 26 6 105 116 101 109 95 48 32 99]
Decode Data id:10 type:1 Name: "Item_0" amount:99

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.