-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathjson.go
74 lines (60 loc) · 1.83 KB
/
json.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"
"encoding/json"
"io"
)
// JSONEncoder handles encoding of JSON data.
type JSONEncoder struct {
MarshalFunc func(v any) ([]byte, error)
}
// Encode marshals the provided value into JSON format.
func (e *JSONEncoder) Encode(v any) (io.Reader, error) {
var err error
var data []byte
if e.MarshalFunc == nil {
data, err = json.Marshal(v) // Fallback to standard JSON marshal if no custom function is provided
} else {
data, err = e.MarshalFunc(v)
}
if err != nil {
return nil, err
}
buf := GetBuffer()
_, err = buf.Write(data)
if err != nil {
PutBuffer(buf) // Ensure the buffer is returned to the pool in case of an error
return nil, err
}
// Here, we need to ensure the buffer will be returned to the pool after being read.
// One approach is to wrap the bytes.Reader in a custom type that returns the buffer on close.
reader := &poolReader{Reader: bytes.NewReader(buf.B), poolBuf: buf}
return reader, nil
}
// ContentType returns the content type for JSON data.
func (e *JSONEncoder) ContentType() string {
return "application/json;charset=utf-8"
}
// DefaultJSONEncoder instance using the standard json.Marshal function
var DefaultJSONEncoder = &JSONEncoder{
MarshalFunc: json.Marshal,
}
// JSONDecoder handles decoding of JSON data.
type JSONDecoder struct {
UnmarshalFunc func(data []byte, v any) error
}
// Decode reads the data from the reader and unmarshals it into the provided value.
func (d *JSONDecoder) 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)
}
return json.Unmarshal(data, v) // Fallback to standard JSON unmarshal
}
// DefaultJSONDecoder instance using the standard json.Unmarshal function
var DefaultJSONDecoder = &JSONDecoder{
UnmarshalFunc: json.Unmarshal,
}