Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go: Reading and writing compressed gob to file

Tags:

go

This does not appear to work correctly and I'm not sure what I'm doing wrong. I'm attempting to convert a map into a gob, gzip the binary and save it to a file, then later read it back.

type Object struct {
mystruct map[string][]scorer
}

type scorer struct {
category int
score float64
}

func (t *Object) Load(filename string) error {

    fi, err := os.Open(filename)
    if err !=nil {
        return err
    }
    defer fi.Close()

    fz, err := gzip.NewReader(fi)
    if err !=nil {
        return err
    }
    defer fz.Close()

    decoder := gob.NewDecoder(fz)
    err = decoder.Decode(&t.mystruct)
    if err !=nil {
        return err
    }

    return nil
}

func (t *Object) Save(filename string) error {

    fi, err := os.Create(filename)
    if err !=nil {
        return err
    }
    defer fi.Close()

    fz := gzip.NewWriter(fi)
    defer fz.Close()

    encoder := gob.NewEncoder(fz)
    err = encoder.Encode(t.mystruct)
    if err !=nil {
        return err
    }

    return nil
}

Something is saved to a file and the gzip appears to be valid, but it is either saving nothing or not loading it back again.

I'm also not sure if I'm doing this correctly as I'm new to Go and I'm finding it difficult to get my head around the readers and writers, since I'm coming from PHP and not used to that.

Any ideas?

like image 945
Alasdair Avatar asked Jul 25 '14 09:07

Alasdair


1 Answers

Your problem has nothing to do with Readers and Writers: You just cannot encode/decode fields which are un-exported and all your fields are unexported (lowercase). You'll have to use Mystruct, Categoryand Score or write your own BinaryMarshal/BinaryUnmarshal as explained in http://golang.org/pkg/encoding/gob/#example__encodeDecode

like image 86
Volker Avatar answered Nov 15 '22 07:11

Volker