dimanche 25 novembre 2018

Deserializing unknown Go's gob blob

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)
}





Aucun commentaire:

Enregistrer un commentaire