go语言protobuf使用

windows--------------------------------------------------------------------------------

1.下载 protoc.exe

2.

安装proto的go语言插件

go get code.google.com/p/goprotobuf/{proto,protoc-gen-go}

3.

package protodoc;

message RegMessage {
    required int32 id = 1; // 主键,唯一
    required string username = 2; // 帐号
    required string password = 3; // 密码
    optional string email = 4; // 邮箱(可选)
}



执行

执行:
protoc --cpp_out=. RegMessage.proto
protoc --go_out=. RegMessage.proto


package main

import proto "code.google.com/p/goprotobuf/proto"
import (
    "protodoc"
    "fmt"
    "os"
)

func main() {

    msg := &protodoc.Helloworld{
        Id:  proto.Int32(101),
        Str: proto.String("hello"),
    } //msg init

    path := string("./log.txt")
    f, err := os.Create(path)
    if err != nil {
        fmt.Printf("failed: %s\n", err)
        return
    }

    defer f.Close()
    buffer, err := proto.Marshal(msg) //SerializeToOstream
    f.Write(buffer)}



package main

import proto "code.google.com/p/goprotobuf/proto"
import (
    "protodoc"
    "fmt"
    "io"
    "os"
)

func CheckError(err error) {
    if err != nil {
        fmt.Println(err.Error())
        os.Exit(-1)
    }
}

func main() {
    path := string("./log.txt")
    file, err := os.Open(path)
    if err != nil {
        fmt.Printf("failed: %s\n", err)
        return
    }

    defer file.Close()
    fi, err := file.Stat()
    CheckError(err)
    buffer := make([]byte, fi.Size())
    _, err = io.ReadFull(file, buffer) //read all content
    CheckError(err)
    msg := &protodoc.Helloworld{}
    err = proto.Unmarshal(buffer, msg) //unSerialize
    CheckError(err)
    fmt.Printf("read: %s\n", msg.String())}



linux----------------------------------------------------------------------------------


你可能感兴趣的:(go语言protobuf使用)