optimize code

Signed-off-by: yxxhero <aiopsclub@163.com>
This commit is contained in:
yxxhero 2025-05-15 10:45:20 +08:00
parent 04ec28993e
commit 4d0ba2043f
2 changed files with 14 additions and 23 deletions

View File

@ -18,7 +18,16 @@ type Encoder interface {
// NewEncoder creates and returns a function that is used to encode a Go object to a YAML document
func NewEncoder(w io.Writer) Encoder {
if runtime.GoccyGoYaml {
return yaml.NewEncoder(w)
yamlEncoderOpts := []yaml.EncodeOption{
yaml.Indent(2),
yaml.UseSingleQuote(true),
yaml.UseLiteralStyleIfMultiline(true),
}
yamlEncoder := yaml.NewEncoder(
w,
yamlEncoderOpts...,
)
return yamlEncoder
}
v3Encoder := v3.NewEncoder(w)
@ -28,16 +37,7 @@ func NewEncoder(w io.Writer) Encoder {
func Marshal(v any) ([]byte, error) {
var b bytes.Buffer
if runtime.GoccyGoYaml {
yamlEncoderOpts := []yaml.EncodeOption{
yaml.Indent(2),
yaml.UseSingleQuote(true),
yaml.UseLiteralStyleIfMultiline(true),
}
yamlEncoder := yaml.NewEncoder(
&b,
yamlEncoderOpts...,
)
yamlEncoder := NewEncoder(&b)
err := yamlEncoder.Encode(v)
defer func() {
_ = yamlEncoder.Close()
@ -45,15 +45,6 @@ func Marshal(v any) ([]byte, error) {
return b.Bytes(), err
}
v3Encoder := v3.NewEncoder(&b)
v3Encoder.SetIndent(2)
err := v3Encoder.Encode(v)
defer func() {
_ = v3Encoder.Close()
}()
return b.Bytes(), err
}
// NewDecoder creates and returns a function that is used to decode a YAML document
// contained within the YAML document stream per each call.
// When strict is true, this function ensures that every field found in the YAML document