本文主要介紹二進制協議gob及msgpack的基本使用。git
最近在寫一個gin框架的session服務時遇到了一個問題,Go語言中的json包在序列化空接口存放的數字類型(整型、浮點型等)都序列化成float64類型。github
咱們構造一個結構體以下:golang
type s struct { data map[string]interface{} }
func jsonDemo() { var s1 = s{ data: make(map[string]interface{}, 8), } s1.data["count"] = 1 ret, err := json.Marshal(s1.data) if err != nil { fmt.Println("marshal failed", err) } fmt.Printf("%#v\n", string(ret)) var s2 = s{ data: make(map[string]interface{}, 8), } err = json.Unmarshal(ret, &s2.data) if err != nil { fmt.Println("unmarshal failed", err) } fmt.Println(s2) for _, v := range s2.data { fmt.Printf("value:%v, type:%T\n", v, v) } }
輸出結果:json
"{\"count\":1}" {map[count:1]} value:1, type:float64
標準庫gob是golang提供的「私有」的編解碼方式,它的效率會比json,xml等更高,特別適合在Go語言程序間傳遞數據。bash
func gobDemo() { var s1 = s{ data: make(map[string]interface{}, 8), } s1.data["count"] = 1 // encode buf := new(bytes.Buffer) enc := gob.NewEncoder(buf) err := enc.Encode(s1.data) if err != nil { fmt.Println("gob encode failed, err:", err) return } b := buf.Bytes() fmt.Println(b) var s2 = s{ data: make(map[string]interface{}, 8), } // decode dec := gob.NewDecoder(bytes.NewBuffer(b)) err = dec.Decode(&s2.data) if err != nil { fmt.Println("gob decode failed, err", err) return } fmt.Println(s2.data) for _, v := range s2.data { fmt.Printf("value:%v, type:%T\n", v, v) } }
MessagePack是一種高效的二進制序列化格式。它容許你在多種語言(如JSON)之間交換數據。但它更快更小。session
go get -u github.com/vmihailenco/msgpack
package main import ( "fmt" "github.com/vmihailenco/msgpack" ) // msgpack demo type Person struct { Name string Age int Gender string } func main() { p1 := Person{ Name: "沙河娜扎", Age: 18, Gender: "男", } // marshal b, err := msgpack.Marshal(p1) if err != nil { fmt.Printf("msgpack marshal failed,err:%v", err) return } // unmarshal var p2 Person err = msgpack.Unmarshal(b, &p2) if err != nil { fmt.Printf("msgpack unmarshal failed,err:%v", err) return } fmt.Printf("p2:%#v\n", p2) // p2:main.Person{Name:"沙河娜扎", Age:18, Gender:"男"} }