msgpack
MessagePack is an efficient binary serialization format. It allows you to exchange data between multiple languages, such as JSON. But it's faster and smaller.
golang efficiently serializes using msgpack
package main import ( "fmt" "/go-redis/redis" "reflect" "/vmihailenco/msgpack" ) // Declare a global rdb variablevar rdb * // Initialize the connectionfunc initClient() (err error) { rdb = (&{ Addr: "localhost:6379", Password: "", // no password set DB: 0, // use default DB }) _, err = ().Result() if err != nil { return err } return nil } type Test struct { name string } func main() { var countryCapitalMap map[string]string /*Create collection */ countryCapitalMap = make(map[string]string) /* map insert key - value pair, the corresponding capital of each country */ countryCapitalMap["France"] = "Paris" countryCapitalMap["Italy"] = "Rome" countryCapitalMap["Japan"] = "Tokyo" countryCapitalMap["India "] = "New Delhi" ("Original data-", countryCapitalMap) //in := map[string]interface{}{"foo": uint32(123456789), "hello": "world"} in := countryCapitalMap res, err := (in) if err != nil { ("Serialization failed") } //("Data type %T", b) ((res)) ("Serialized data--", res) //Connect redis initClient() //Save redis data type[]type can be saved bool := ("val", res, 0).Err() if bool != nil { ("set val failed, err:%v\n", err) return } //The return type is variable val, err := ("val").Bytes() if err != nil { ("get val failed, err:%v\n", err) return } ("redis fetch data--", val) var out map[string]string bool = (val, &out) if bool != nil { ("Deserialization failed") } ("Deserialize data--", out) }
Install
go get -u /vmihailenco/msgpack
Example
package main import ( "fmt" "/vmihailenco/msgpack" ) // msgpack demo type Person struct { Name string Age int Gender string } func main() { p1 := Person{ Name: "Shahe Nazha", Age: 18, Gender: "male", } // marshal b, err := (p1) // Convert structure into binary stream if err != nil { ("msgpack marshal failed,err:%v", err) return } // unmarshal var p2 Person err = (b, &p2) // Convert binary flow back to structure if err != nil { ("msgpack unmarshal failed,err:%v", err) return } ("p2:%#v\n", p2) // p2:{Name:"Shahe Nazha", Age:18, Gender:"Male"}}
This is the article about golang’s efficient serialization case using msgpack. For more related golang, msgpack serialization content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!