搞定,可以在 $GO_PATH/bin下找到 protoc-gen-go 这个程序,那么就可以实用protoc-gen-go 进行go语言的proto文件的自动生成了。
go1.0 使用: protoc-gen-go --go_out=. hellowrold.proto
protoc --go_out=. hellowrold.proto
protoc-gen-go --go_out=. hellowrold.proto
// Code generated by protoc-gen-go.
// source: helloworld.proto
// DO NOT EDIT!
package lm
import proto "code.google.com/p/goprotobuf/proto"
import json "encoding/json"
import math "math"
// Reference proto, json, and math imports to suppress error if they are not otherwise used.
var _ = proto.Marshal
var _ = &json.SyntaxError{}
var _ = math.Inf
type Helloworld struct {
Id *int32 `protobuf:"varint,1,req,name=id" json:"id,omitempty"`
Str *string `protobuf:"bytes,2,req,name=str" json:"str,omitempty"`
Opt *int32 `protobuf:"varint,3,opt,name=opt" json:"opt,omitempty"`
XXX_unrecognized []byte `json:"-"`
}
func (this *Helloworld) Reset() { *this = Helloworld{} }
func (this *Helloworld) String() string { return proto.CompactTextString(this) }
func (*Helloworld) ProtoMessage() {}
func (this *Helloworld) GetId() int32 {
if this != nil && this.Id != nil {
return *this.Id
}
return 0
}
func (this *Helloworld) GetStr() string {
if this != nil && this.Str != nil {
return *this.Str
}
return ""
}
func (this *Helloworld) GetOpt() int32 {
if this != nil && this.Opt != nil {
return *this.Opt
}
return 0
}
func init() {
package main
import proto "code.google.com/p/goprotobuf/proto"
import (
"./lm"
"fmt"
"os"
)
func main() {
msg := &lm.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 (
"./lm"
"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 := &lm.Helloworld{}
err = proto.Unmarshal(buffer, msg) //unSerialize
CheckError(err)
fmt.Printf("read: %s\n", msg.String())