dongshuo1856 2014-04-25 00:46
浏览 21
已采纳

无法使用goprotobuf解码邮件

I have the following proto file:

package dogs;

enum Breed {
    terrier = 0;
    shepherd = 1;
    hound = 2;
};

message Dog {
    required int64 nbLegs = 1;
    optional int64 nbTeeth = 2 [default=24];
    optional Breed breed = 3;
    optional string name = 4;
}

And the following Go program written using the goprotobuf package. The program

  1. reads a Varint from stdin in order to get the length of the encoded message,
  2. reads that number of bytes from stdin into a buffer, and
  3. attempts to unmarshal the buffer into a Dog.

--START CODE--

package main

import "bufio"
import "encoding/binary"
import "os"
import "log"
import "fmt"
import "dogs"
import "code.google.com/p/goprotobuf/proto"

func render(dog *dogs.Dog) string {
    return fmt.Sprintf("Dog: %v %v %v %v", dog.GetName(), dog.GetBreed(), dog.GetNbLegs(), dog.GetNbTeeth())
}

func main() {
    var dog = new(dogs.Dog)
    stdin := bufio.NewReader(os.Stdin)
    sz, _ := binary.ReadVarint(stdin)
    bytes := make([]byte, sz)
    os.Stdin.Read(bytes)
    buf := proto.NewBuffer(bytes)
    err := buf.Unmarshal(dog)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Fprintf(os.Stderr, "Receiving %s of length %d
", render(dog), sz)

}

--END CODE--

And the this encoded message (preceded by a Varint) (in hexdump form)

0000000: 1408 0418 0222 0446 6964 6f              .....".Fido

which i can successfully decode using c++ and libprotobuf as a Dog with

  • name: Fido
  • breed: hound
  • nbLegs: 4
  • nbTeeth: 24

Unmarshaling in the go program, however, always returns the error "illegal tag 0".

I suspect that I've misunderstood the decoding API but, so far, I can't see how.

  • 写回答

1条回答 默认 最新

  • drxv39706 2014-04-28 11:50
    关注

    Try just umarshalling the bytes instead of creating a buffer like this: You may also want to check to see if os.Stdin.Read(bytes) is actually reading sz.

    func main() {
        var dog = new(dogs.Dog)
        stdin := bufio.NewReader(os.Stdin)
        sz, _ := binary.ReadVarint(stdin)
        bytes := make([]byte, sz)
        stdin.Read(bytes)
        err := buf.Unmarshal(dog, bytes)
        if err != nil {
            log.Fatal(err)
        }
        fmt.Fprintf(os.Stderr, "Receiving %s of length %d
    ", render(dog), sz)
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题