4

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)
}
user3130782
  • 841
  • 1
  • 6
  • 15
  • This is an important feature if be possible. I have same problem and I don't know why previous data is not decode-able. so, I'm looking to another formats like JSON which causes easily debug-able. – S.M.Mousavi Dec 25 '21 at 19:28

1 Answers1

0

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.

CallMeLoki
  • 1,281
  • 10
  • 23
  • But I do not have serialized structures. Actually I am looking for tool that will list fields names, types, values. If I use hex viewer then it is possible to guess something. So information on Field names and types is there. – user3130782 Nov 25 '18 at 18:01
  • then it's whole another question. all you want is in reflect package – CallMeLoki Nov 26 '18 at 13:29
  • I have blob encoded with gob. I can't deserialize it in some object or structure to explorer it with reflect. – user3130782 Nov 26 '18 at 17:58