gin/binding/yaml.go

48 lines
1.0 KiB
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"
"github.com/goccy/go-yaml"
)
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) BindNoValidate(req *http.Request, obj any) error {
return decodeYAMLNoValidate(req.Body, obj)
}
func (yamlBinding) BindBody(body []byte, obj any) error {
return decodeYAML(bytes.NewReader(body), obj)
}
func (yamlBinding) BindBodyNoValidate(body []byte, obj any) error {
return decodeYAMLNoValidate(bytes.NewReader(body), obj)
}
func decodeYAML(r io.Reader, obj any) error {
if err := decodeYAMLNoValidate(r, obj); err != nil {
return err
}
return validate(obj)
}
func decodeYAMLNoValidate(r io.Reader, obj any) error {
decoder := yaml.NewDecoder(r)
return decoder.Decode(obj)
}