Deserializing unknown Go's gob blob

1k Views Asked by At

I have gobs of unknown type. Is there way to print it to view inside?

There might be gob.Debug but it is not available for me https://golang.org/src/encoding/gob/debug.go

Googling advices to use DecodeValue but it requires initialised reflect.Value If I get unknown gob blob then I can't pass initialized value on unknown type

https://play.golang.org/p/OWxX1kPJ6Qa

package main

import (
    "bytes"
    "encoding/gob"
    "fmt"
    "reflect"
)


func encode1() []byte {

    x := "123"

    buf := &bytes.Buffer{}
    enc := gob.NewEncoder(buf)
    err := enc.Encode(x)
    if err != nil {
        panic(err)
    }
    return buf.Bytes()

}

func decode1(b1 []byte) {
    var x string
    dec := gob.NewDecoder(bytes.NewBuffer(b1))
    err := dec.Decode(&x)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%#v\n", x)
}

func decode2(b1 []byte) {
//  var x reflect.Value
    x := reflect.New(reflect.TypeOf(""))
    dec := gob.NewDecoder(bytes.NewBuffer(b1))
    err := dec.DecodeValue(x)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%#v\n", x)
    fmt.Printf("%#v\n", reflect.Indirect(x))
}

func main() {
    b1 := encode1()
    decode1(b1)
    decode2(b1)
}
1

There are 1 best solutions below

3
On

you need to Register your type before encode decoding

Register records a type, identified by a value for that type, under its internal type name. That name will identify the concrete type of a value sent or received as an interface variable. Only types that will be transferred as implementations of interface values need to be registered. Expecting to be used only during initialization, it panics if the mapping between types and names is not a bijection.