本文整理匯總了Golang中goprotobuf/googlecode/com/hg/proto.Unmarshal函數的典型用法代碼示例。如果您正苦於以下問題:Golang Unmarshal函數的具體用法?Golang Unmarshal怎麽用?Golang Unmarshal使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了Unmarshal函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: main
func main() {
m1 := &test.Member{
Name: proto.String("Linus"),
Age: proto.Int32(99),
}
m1.Skills = []test.Skill{test.Skill_ASM, test.Skill_C}
m1_data, err := proto.Marshal(m1)
if err != nil {
log.Fatal("marshaling error: ", err)
os.Exit(1)
}
fmt.Println("m1: ", m1)
fmt.Println("m1.Skills: ", m1.Skills)
fmt.Println("actual data: ", m1_data)
println("=== unmarshalling m1 into m2 ===")
m2 := &test.Member{}
proto.Unmarshal(m1_data, m2)
fmt.Println("m2: ", m2)
port := 9090
fmt.Println("=== END EXAMPLES / SERVER STARTING at %d ===", port)
service := fmt.Sprintf(":%d", port)
tcpAddr, err := net.ResolveTCPAddr("ip4", service)
checkError(err)
listener, err := net.ListenTCP("tcp", tcpAddr)
checkError(err)
for {
conn, err := listener.Accept()
checkError(err)
input := make([]byte, 1024)
n, err := conn.Read(input)
input = input[:n]
fmt.Println("input: ", input)
club := &test.Club{}
err = proto.Unmarshal(input, club)
checkError(err)
sum := int32(0)
fmt.Println("len: ", len(club.Member))
for _, m := range club.Member {
sum += *m.Age
}
avg := float64(sum) / float64(len(club.Member))
fmt.Printf("avg age: %f (sum: %d)\n", avg, sum)
reply := &test.Reply{Average: proto.Float64(avg)}
out_data, err := proto.Marshal(reply)
conn.Write(out_data) // don't care about return value
conn.Close() // we're finished with this client
}
}
示例2: Main
func (this *InitProtoHandler) Main() {
defer this.Cleanup()
fmt.Printf("InitProtoHandler·Main\n")
header, data := this.Proxy.ReadMsg(0)
if header == nil || *header.Type != Client_JOIN {
fmt.Printf("Invalid data!\n")
return
}
//Player joins
joinmsg := NewClientJoin()
player := NewPlayer()
proto.Unmarshal(data, joinmsg)
player.Name = *joinmsg.Playername
worldhandler := GlobalRoutines["worldhandler"].(*WorldHandler)
coord := worldhandler.World.GetCoord(50, 50)
fmt.Printf("%d %d\n", coord.X, coord.Y)
pusher := NewPushProtoHandler(this.Proxy)
go pusher.Main()
player.ProtoHandlers[PORT_PUSH] = pusher
worldhandler.PlacePlayer(player, coord)
this.Acceptbool()
//Pass on to another handler
session := make(Session)
session["player"] = player
inworld := NewInWorldProtoHandler(this.Proxy)
player.ProtoHandlers[PORT_MAIN] = inworld
inworld.Main(&session)
}
示例3: handleCryptSetup
func (server *Server) handleCryptSetup(client *Client, msg *Message) {
cs := &mumbleproto.CryptSetup{}
err := proto.Unmarshal(msg.buf, cs)
if err != nil {
client.Panic(err.String())
return
}
// No client nonce. This means the client
// is requesting that we re-sync our nonces.
if len(cs.ClientNonce) == 0 {
log.Printf("Requested crypt-nonce resync")
cs.ClientNonce = make([]byte, cryptstate.AESBlockSize)
if copy(cs.ClientNonce, client.crypt.EncryptIV[0:]) != cryptstate.AESBlockSize {
return
}
client.sendProtoMessage(MessageCryptSetup, cs)
} else {
log.Printf("Received client nonce")
if len(cs.ClientNonce) != cryptstate.AESBlockSize {
return
}
client.crypt.Resync += 1
if copy(client.crypt.DecryptIV[0:], cs.ClientNonce) != cryptstate.AESBlockSize {
return
}
log.Printf("Crypt re-sync successful")
}
}
示例4: TestMarshalUnmarshalBase64
func TestMarshalUnmarshalBase64(t *testing.T) {
var encbuf []byte
var decbuf []byte
t.Logf("start with buf %s\n", proto.CompactTextString(&cr))
t.Log("marshalling protobuf")
buf, err := proto.Marshal(&cr)
if err != nil {
t.Error("marshal error: ", err)
}
t.Log("marshalled")
t.Log("urlencoding")
t.Logf("need %d size buffer\n", base64.URLEncoding.EncodedLen(len(buf)-1))
t.Log(buf)
t.Logf("%v %s\n", buf, buf)
encbuf = make([]byte, base64.URLEncoding.EncodedLen(len(buf)), base64.URLEncoding.EncodedLen(len(buf)))
base64.URLEncoding.Encode(encbuf, buf)
t.Log("urlencoded")
t.Log("urldecoding")
t.Logf("need %d size buffer\n", base64.URLEncoding.DecodedLen(len(encbuf)))
t.Logf("%v %s\n", encbuf, encbuf)
decbuf = make([]byte, base64.URLEncoding.DecodedLen(len(encbuf)), base64.URLEncoding.DecodedLen(len(encbuf)))
n, err := base64.URLEncoding.Decode(decbuf, encbuf)
t.Logf("wrote %d bytes from encbuf to decbuf. len(encbuf)=%d, len(buf)=%d\n", n, len(encbuf), len(buf))
if err != nil {
t.Error("urldecode error: ", err)
}
t.Log("urldecoded")
t.Log(buf, decbuf)
rcr := &CheckResult{}
t.Log("unmarshalling")
err = proto.Unmarshal(decbuf, rcr)
t.Logf("%s\n", proto.CompactTextString(rcr))
}
示例5: TestRunBroadcastThree
func TestRunBroadcastThree(t *testing.T) {
c := make(chan Packet, 100)
sentinel := Packet{Addr: "sentinel"}
var r run
r.seqn = 1
r.out = c
r.addrs = map[string]bool{
"x": true,
"y": true,
"z": true,
}
r.broadcast(newInvite(1))
c <- sentinel
exp := msg{
Seqn: proto.Int64(1),
Cmd: invite,
Crnd: proto.Int64(1),
}
addrs := map[string]bool{}
for i := 0; i < len(r.addrs); i++ {
p := <-c
addrs[p.Addr] = true
var got msg
err := proto.Unmarshal(p.Data, &got)
assert.Equal(t, nil, err)
assert.Equal(t, exp, got)
}
assert.Equal(t, sentinel, <-c)
assert.Equal(t, r.addrs, addrs)
}
示例6: TestRunBroadcastFive
func TestRunBroadcastFive(t *testing.T) {
c := make(chan Packet, 100)
var r run
r.seqn = 1
r.out = c
r.addr = []*net.UDPAddr{
&net.UDPAddr{net.IP{1, 2, 3, 4}, 5},
&net.UDPAddr{net.IP{2, 3, 4, 5}, 6},
&net.UDPAddr{net.IP{3, 4, 5, 6}, 7},
&net.UDPAddr{net.IP{4, 5, 6, 7}, 8},
&net.UDPAddr{net.IP{5, 6, 7, 8}, 9},
}
r.broadcast(newInvite(1))
c <- Packet{}
exp := msg{
Seqn: proto.Int64(1),
Cmd: invite,
Crnd: proto.Int64(1),
}
addr := make([]*net.UDPAddr, len(r.addr))
for i := 0; i < len(r.addr); i++ {
p := <-c
addr[i] = p.Addr
var got msg
err := proto.Unmarshal(p.Data, &got)
assert.Equal(t, nil, err)
assert.Equal(t, exp, got)
}
assert.Equal(t, Packet{}, <-c)
assert.Equal(t, r.addr, addr)
}
示例7: readMessage
func readMessage(r io.Reader) (msg *protocol.Message, err os.Error) {
start:
// Read length
length, err := readLength(r)
if err != nil {
if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
// Socket timed out on read, read again
goto start
} else {
return nil, err
}
}
// Read the message bytes
bs := make([]byte, length)
if n, err := io.ReadFull(r, bs); err != nil {
log.Println("Error reading message bytes:", err)
} else if n != len(bs) {
return nil, os.NewError(fmt.Sprintf("Read only %d bytes out of expected %d bytes!", n, length))
}
// Unmarshal
msg = new(protocol.Message)
if err := proto.Unmarshal(bs, msg); err != nil {
return nil, err
}
return msg, nil
}
示例8: TestRunBroadcastFive
func TestRunBroadcastFive(t *testing.T) {
c := make(chan Packet, 100)
sentinel := Packet{Addr: "sentinel"}
var r run
r.seqn = 1
r.out = c
r.addr = []string{"v", "w", "x", "y", "z"}
r.broadcast(newInvite(1))
c <- sentinel
exp := msg{
Seqn: proto.Int64(1),
Cmd: invite,
Crnd: proto.Int64(1),
}
addrs := make([]string, len(r.addr))
for i := 0; i < len(r.addr); i++ {
p := <-c
addrs[i] = p.Addr
var got msg
err := proto.Unmarshal(p.Data, &got)
assert.Equal(t, nil, err)
assert.Equal(t, exp, got)
}
assert.Equal(t, sentinel, <-c)
assert.Equal(t, r.addr, addrs)
}
示例9: handleTextMessage
// Broadcast text messages
func (server *Server) handleTextMessage(client *Client, msg *Message) {
txtmsg := &mumbleproto.TextMessage{}
err := proto.Unmarshal(msg.buf, txtmsg)
if err != nil {
client.Panic(err.String())
return
}
// fixme(mkrautz): Check text message length.
// fixme(mkrautz): Sanitize text as well.
clients := make(map[uint32]*Client)
// Tree
for _, chanid := range txtmsg.TreeId {
if channel, ok := server.Channels[int(chanid)]; ok {
if !server.HasPermission(client, channel, TextMessagePermission) {
client.sendPermissionDenied(client, channel, TextMessagePermission)
}
for _, target := range channel.clients {
clients[target.Session] = target
}
}
}
// Direct-to-channel
for _, chanid := range txtmsg.ChannelId {
if channel, ok := server.Channels[int(chanid)]; ok {
if !server.HasPermission(client, channel, TextMessagePermission) {
client.sendPermissionDenied(client, channel, TextMessagePermission)
return
}
for _, target := range channel.clients {
clients[target.Session] = target
}
}
}
// Direct-to-clients
for _, session := range txtmsg.Session {
if target, ok := server.clients[session]; ok {
if !server.HasPermission(client, target.Channel, TextMessagePermission) {
client.sendPermissionDenied(client, target.Channel, TextMessagePermission)
return
}
clients[session] = target
}
}
// Remove ourselves
clients[client.Session] = nil, false
for _, target := range clients {
target.sendProtoMessage(MessageTextMessage, &mumbleproto.TextMessage{
Actor: proto.Uint32(client.Session),
Message: txtmsg.Message,
})
}
}
示例10: mustUnmarshal
func mustUnmarshal(b []byte) (r *response) {
r = new(response)
err := proto.Unmarshal(b, r)
if err != nil {
panic(err)
}
return
}
示例11: mustUnmarshal
func mustUnmarshal(b []byte) (r *R) {
r = new(R)
err := proto.Unmarshal(b, r)
if err != nil {
panic(err)
}
return
}
示例12: Get
func (ds *PBSDataStore) Get(key string, value interface{}) (err os.Error) {
if ds.keys[key] != nil {
data, err := ds.datastore.Get(key)
if err == nil {
err = proto.Unmarshal(data, value)
}
}
return
}
示例13: handleUserStatsMessage
// User stats message. Shown in the Mumble client when a
// user right clicks a user and selects 'User Information'.
func (server *Server) handleUserStatsMessage(client *Client, msg *Message) {
stats := &mumbleproto.UserStats{}
err := proto.Unmarshal(msg.buf, stats)
if err != nil {
client.Panic(err.String())
}
log.Printf("UserStats")
}
示例14: root
func root(w http.ResponseWriter, r *http.Request) {
// check header
if *flagPassword != "" && *flagUsername != "" {
auth, ok := r.Header["Authorization"]
if ok && strings.HasPrefix(auth[0], "Basic ") {
str := strings.TrimLeft(auth[0], "Basic ")
decode, err := base64.StdEncoding.DecodeString(str)
if err != nil {
log.Print("cannot decode auth string: ", err)
return
}
user, pass, err := url.UnescapeUserinfo(string(decode))
if err != nil {
log.Print("auth: couldn't decode user/pass: ", err)
}
if !(user == *flagUsername && pass == *flagPassword) {
log.Print("auth: wrong user/pass: ", user+"/"+pass, *r)
return
}
/* log.Printf("auth: %#v, user: %s, pass: %s", auth, user, pass)*/
} else {
log.Print("auth: no authorization")
return
}
}
checkpb := new(CheckResultSet)
if r.Method == "POST" {
cout := new(bytes.Buffer)
if _, err := cout.ReadFrom(r.Body); err != nil {
log.Print("error! ", err)
return
}
switch r.Header["Content-Type"][0] {
case "application/x-protobuf":
err := proto.Unmarshal(cout.Bytes(), checkpb)
if err != nil {
log.Printf("unmarshalling error: ", err)
}
case "application/json", "text/plain", "application/x-www-form-urlencoded", "multipart/form-data":
err := json.Unmarshal(cout.Bytes(), checkpb)
if err != nil {
log.Printf("unmarshalling error: ", err)
}
}
logger.Printf("check returned! %s", proto.CompactTextString(checkpb))
for _, v := range checkpb.Results {
_, err := WriteCheck(v, *flagSpoolDir)
if err != nil {
logger.Print("writecheck failed: ", err)
}
}
} else {
/* logger.Printf("NOT POST!! %s", r.Method)*/
}
templ.Execute(w, nil)
}
示例15: Call
func (c *context) Call(service, method string, in, out interface{}) os.Error {
data, err := proto.Marshal(in)
if err != nil {
return err
}
res, err := call(service, method, data)
if err != nil {
return err
}
return proto.Unmarshal(res, out)
}