golang 的MessagePack编解码包的试用

主要是对于golang messagepack 包的试用

项目代码

  • go.mod
module demoapp
go 1.15
require (
    github.com/davecgh/go-spew v1.1.1 // indirect
    github.com/kr/text v0.2.0 // indirect
    github.com/tinylib/msgp v1.1.5
    github.com/vmihailenco/msgpack/v5 v5.1.4
    gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
    gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776 // indirect
)
  • 项目结构
├── Makefile
├── README.md
├── go.mod
├── go.sum
├── main.go
└── pkg
    ├── person.go
  • 代码说明
    Makefile 使用make 进行代码生成
 
gen:
    go generate ./pkg

go.mod

module demoapp
go 1.15
require (
    github.com/davecgh/go-spew v1.1.1 // indirect
    github.com/kr/text v0.2.0 // indirect
    github.com/tinylib/msgp v1.1.5
    github.com/vmihailenco/msgpack/v5 v5.1.4
    gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
    gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776 // indirect
)

person.go 定义的person struct,同时集成了golang 的tag 能力方便进行序列化以及反序列话处理


//go:generate msgp
package pkg
// Person person for search
type Person struct {
    Name       string `msg:"name" msgpack:"name"`
    Address    string `msg:"address" msgpack:"address"`
    Age        int    `msg:"age" msgpack:"age"`
    Hidden     string `msg:"-" msgpack:"_"` // this field is ignored
    unexported bool   // this field is also ignored
}

main.go 集成了tinylib/msgp + vmihailenco/msgpack 进行互相转换处理

package main
import (
    "bytes"
    "demoapp/pkg"
    "log"
    "github.com/tinylib/msgp/msgp"
    "github.com/vmihailenco/msgpack/v5"
)
func main() {
    var buf bytes.Buffer
    myPerson := pkg.Person{
        Name:    "荣锋亮",
        Address: "beijing",
        Age:     33,
    }
    err := msgp.Encode(&buf, &myPerson)
    if err != nil {
        panic("encode some wrong" + err.Error())
    }
    var dstPerson pkg.Person
    var dstPerson2 *pkg.Person = &pkg.Person{}
    err = msgpack.Unmarshal(buf.Bytes(), &dstPerson)
    datas, err := dstPerson2.UnmarshalMsg(buf.Bytes())
    if err != nil {
        panic("uncode:" + err.Error())
    }
    if len(datas) > 0 {
        log.Panicf("%d bytes left over after UnmarshalMsg(): %q", len(datas), datas)
    }
    log.Println("from msgp: ", string(buf.Bytes()))
    log.Printf("msgpack:%v,msgp: %v", dstPerson, *dstPerson2)
    log.Println("from msgpack:", dstPerson.Name)
}

运行

  • 命令
make 
go run main.go
  • 效果

参考资料

https://github.com/tinylib/msgp
https://github.com/vmihailenco/msgpack
https://msgpack.uptrace.dev/
https://github.com/rongfengliang/messagepack-go-learning

原文地址:https://www.cnblogs.com/rongfengliang/p/14232022.html