Encoding and decoding structs of

Issue

I’m trying to encode and decode structs, I’ve searched around quite a bit and a lot of the questions regarding this topic is usually people who want to encode primitives, or simple structs. What I want is to encode a struct that could look like this:

    Name string           
    Id   int               
    file *os.File          
    keys *ecdsa.PrivateKey 
}

The name and the ID is no problem, and I can encode them using either gob or json marshalling. However when I want to encode a file for example using gob, I’d usegob.Register(os.File{}) I get an error that file has no exported fields, due to the fields in the file struct being lower case. I would use a function like this

    buf := bytes.Buffer{}
    enc := gob.NewEncoder(&buf)
    gob.Register(big.Int{})
...
    err := enc.Encode(&p)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("uncompressed size (bytes): ", len(buf.Bytes()))
    return buf.Bytes()
}

I’m not sure if it’s correct to register within the encode function, however it seems odd that I have to register all structs that is being referenced to for the one specific struct i want to encode. For example with a file, I would have to register a ton of interfaces, it doesn’t seem to be the correct way to do it. Is there a simple way to encode and decode structs that have a bit more complexity.

If I use json marshalling to do this it will always return nil if I use a pointer to another struct. Is there a way to get all the information I want?

Thanks!

Solution

Imagine your struct ponts to a file in /foo/bar/baz.txt and you serialize your struct. The you send it to another computer (perhaps in a different operational system) and re-create the struct. What do you expect?

What if you serialize, delete the file (or update the content) and re-create the struct in the same computer?

One solution is store the content of the file.

Another solution is to store the path to the file and, when you deserialize the struct you can try to reopen the file. You can add a security layer by storing the hash of the content, size and other metadata to check if the file is the same.

The answer will guide you to the best implementation

Answered By – Tiago Peczenyj

Answer Checked By – Marilyn (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.