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

// Copyright 2018 Gin Core Team. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.

package binding

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

	"gopkg.in/yaml.v3"
)

type yamlBinding struct{}

func (yamlBinding) Name() string {
	return "yaml"
}

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

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

func decodeYAML(r io.Reader, obj any) error {
	// NewDecoder返回一个从r中读取的新解码器。解码器引入其自己的缓冲,并且可以从r读取超出所请求的YAML值的数据。
	decoder := yaml.NewDecoder(r)
	// Decode从其输入中读取下一个YAML编码值,并将其存储在obj指向的值中。
	if err := decoder.Decode(obj); err != nil {
		return err
	}
	return validate(obj)
}

猜你喜欢

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