Golang serialize and deserialize back

后端 未结 2 1688
面向向阳花
面向向阳花 2020-12-23 14:24

What\'s the best way (completeness and performance) in Golang to serialize and deserialize a struct to string and vice versa?

for example, if I have this struct:

相关标签:
2条回答
  • 2020-12-23 15:07

    Serialization of a struct generally uses the encoding package. However, that will work for public fields only. If you also need to serialize private fields, see this answer as an alternative.
    You have several encoding choices (binary, text, json as in this example for a struct, xml, etc.). For example, the project cupcake/rdb uses encoding/binary to implement parsing and encoding of the Redis RDB file format (a binary representation of the in-memory store). Another example is guregu/rediscache, a small library for caching data in Redis.

    0 讨论(0)
  • 2020-12-23 15:17

    Using gob and base64 could solve the problem, for example:

    import (
        "encoding/base64"
        "encoding/gob"
        "bytes"
    )
    
    type SX map[string]interface{}
    
    // go binary encoder
    func ToGOB64(m SX) string {
        b := bytes.Buffer{}
        e := gob.NewEncoder(&b)
        err := e.Encode(m)
        if err != nil { fmt.Println(`failed gob Encode`, err) }
        return base64.StdEncoding.EncodeToString(b.Bytes())
    }
    
    // go binary decoder
    func FromGOB64(str string) SX {
        m := SX{}
        by, err := base64.StdEncoding.DecodeString(str)
        if err != nil { fmt.Println(`failed base64 Decode`, err); }
        b := bytes.Buffer{}
        b.Write(by)
        d := gob.NewDecoder(&b)
        err = d.Decode(&m)
        if err != nil { fmt.Println(`failed gob Decode`, err); }
        return m
    }
    

    and when you need to serialize custom struct or type (for example Session struct), just add these lines:

    func init() {
        gob.Register(SX{})
        gob.Register(Session{}) 
    }
    
    0 讨论(0)
提交回复
热议问题