【Gin-v1.9.0源码阅读】binding/msgpack.go

// Copyright 2017 Manu Martinez-Almeida. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.

//go:build !nomsgpack
// +build !nomsgpack

package binding

import (
	"bytes"
	"io"
	"net/http"

	"github.com/ugorji/go/codec"
)

type msgpackBinding struct{}

func (msgpackBinding) Name() string {
	return "msgpack"
}

func (msgpackBinding) Bind(req *http.Request, obj any) error {
	return decodeMsgPack(req.Body, obj)
}

func (msgpackBinding) BindBody(body []byte, obj any) error {
	return decodeMsgPack(bytes.NewReader(body), obj)
}

func decodeMsgPack(r io.Reader, obj any) error {
	// MsgpackHandle是Msgpack架构自由编码格式的句柄。
	cdc := new(codec.MsgpackHandle)
	// NewDecoder返回一个解码器,用于对io.Reader中的字节流进行解码。
	// Decode对来自读取器的流进行解码,并将结果存储在obj所指向的值中
	if err := codec.NewDecoder(r, cdc).Decode(&obj); err != nil {
		return err
	}
	return validate(obj)
}

猜你喜欢

转载自blog.csdn.net/qq2942713658/article/details/131017567
今日推荐