二进制序列化binary库
package main
import (
"bytes"
"encoding/binary"
"fmt"
)
type Register struct {
ACTION int32
SID int32
}
func (r *Register) Write() []byte {
buf := new(bytes.Buffer)
var info Register
info.ACTION = 20004
info.SID = 6
err := binary.Write(buf, binary.LittleEndian, info)
if err != nil {
fmt.Println("binary.Write failed:", err)
}
fmt.Printf("% x\n", buf.Bytes())
return buf.Bytes()
}
func (r *Register) Read(b []byte) {
var info Register
buf := bytes.NewBuffer(b)
err := binary.Read(buf, binary.LittleEndian, &info)
if err != nil {
fmt.Println("binary.Read failed:", err)
}
fmt.Print(info)
}
func main() {
b := new(Register)
buf := b.Write()
b.Read(buf)
}
Go语言标准库除了提供了binary的之外,还提供了json、csv、xml、gob(类似于 Python 的 "pickle")、base64等序列化,第三方的也比较多,常见的序列化库如下:
https://github.com/golang/protobuf
https://github.com/apache/thrift
https://github.com/linkedin/goavro
https://github.com/youtube/vitess/go/bson
https://github.com/tinylib/msgp
https://github.com/andyleap/gencode
https://github.com/vmihailenco/msgpack
https://github.com/ugorji/go