Domanda

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\n", 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.

È stato utile?

Soluzione

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\n", render(dog), sz)

}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top