msgpack与json类似,只不过,保存的2进制文件,相比json来说,数据更小
用法与json一致,通常与redis一起使用
文档:https://godoc.org/github.com/vmihailenco/msgpack

func Marshal(v interface{}) ([]byte, error)
func Unmarshal(data []byte, v interface{}) error

type Marshaler

  1. type Marshaler interface {
  2. MarshalMsgpack() ([]byte, error)
  3. }

type Unmarshaler

  1. type Unmarshaler interface {
  2. UnmarshalMsgpack([]byte) error
  3. }

type Decoder

从输入流解码对象

  1. type Decoder struct {
  2. // contains filtered or unexported fields
  3. }

func NewDecoder(r io.Reader) Decoder
func (dec
Decoder) Decode(v interface{}) error

type Encoder

将对象写入输出流

  1. type Encoder struct {
  2. // contains filtered or unexported fields
  3. }

func NewEncoder(w io.Writer) Encoder
func (enc
Encoder) Encode(v interface{}) error

  1. import (
  2. "fmt"
  3. json "github.com/vmihailenco/msgpack"
  4. )
  5. type ConfigStruct struct {
  6. Host string `json:"host"`
  7. Port int `json:"port"`
  8. }
  9. func main() {
  10. var con =ConfigStruct{"127.0.0.1",8080}
  11. //struct 到json str
  12. b, err := json.Marshal(con);
  13. if err != nil{
  14. return
  15. }
  16. fmt.Println(string(b))
  17. //json str 转struct
  18. var config ConfigStruct
  19. if err := json.Unmarshal([]byte(b), &config); err == nil {
  20. fmt.Println(config)//{http://localhost:9090 9090}
  21. fmt.Println(config.Host)//http://localhost:9090
  22. }
  23. }
  24. ��Host127.0.0.1Port �
  25. {127.0.0.1 8080}
  26. 127.0.0.1