-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathyaml.go
74 lines (59 loc) · 1.58 KB
/
yaml.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package requests
import (
"bytes"
"io"
"github.com/goccy/go-yaml"
)
// YAMLEncoder handles encoding of YAML data.
type YAMLEncoder struct {
MarshalFunc func(v any) ([]byte, error)
}
// Encode marshals the provided value into YAML format.
func (e *YAMLEncoder) Encode(v any) (io.Reader, error) {
var err error
var data []byte
if e.MarshalFunc != nil {
data, err = e.MarshalFunc(v)
} else {
// Use goccy/go-yaml for marshaling by default
data, err = yaml.Marshal(v)
}
if err != nil {
return nil, err
}
buf := GetBuffer()
_, err = buf.Write(data)
if err != nil {
PutBuffer(buf)
return nil, err
}
return &poolReader{Reader: bytes.NewReader(buf.B), poolBuf: buf}, nil
}
// ContentType returns the content type for YAML data.
func (e *YAMLEncoder) ContentType() string {
return "application/yaml;charset=utf-8"
}
// DefaultYAMLEncoder instance using the goccy/go-yaml Marshal function
var DefaultYAMLEncoder = &YAMLEncoder{
MarshalFunc: yaml.Marshal,
}
// YAMLDecoder handles decoding of YAML data.
type YAMLDecoder struct {
UnmarshalFunc func(data []byte, v any) error
}
// Decode reads the data from the reader and unmarshals it into the provided value.
func (d *YAMLDecoder) Decode(r io.Reader, v any) error {
data, err := io.ReadAll(r)
if err != nil {
return err
}
if d.UnmarshalFunc != nil {
return d.UnmarshalFunc(data, v)
}
// Fallback to standard YAML unmarshal using goccy/go-yaml
return yaml.Unmarshal(data, v)
}
// DefaultYAMLDecoder instance using the goccy/go-yaml Unmarshal function
var DefaultYAMLDecoder = &YAMLDecoder{
UnmarshalFunc: yaml.Unmarshal,
}