-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdiscarder.go
44 lines (38 loc) · 1.16 KB
/
discarder.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
package wrappers
import (
"encoding/json"
"reflect"
)
// Discarder is a generic type that proxies any WrapperProvider.
// It handles unmarshalling by suppressing errors of discarded invalid values.
type Discarder[W WrapperProvider] struct {
Proxy W
}
// MarshalJSON marshals the underlying wrapper to JSON.
func (discarder *Discarder[W]) MarshalJSON() ([]byte, error) {
if discarder.Proxy.IsDiscarded() {
return json.Marshal(nil)
}
return discarder.Proxy.MarshalJSON()
}
// UnmarshalJSON unmarshals JSON data into the underlying wrapper.
// If unmarshalling fails, it discards the value without returning an error.
func (discarder *Discarder[W]) UnmarshalJSON(data []byte) error {
err := discarder.Proxy.UnmarshalJSON(data)
if err != nil {
// Check if our proxy is nil via reflection.
if reflect.ValueOf(discarder.Proxy).IsNil() {
return nil
}
discarder.Proxy.Discard()
return nil // Suppress the error by Discarder
}
return nil
}
// NewDiscarder initializes a new Discarder wrapper with the provided underlying wrapper.
func NewDiscarder[W WrapperProvider](wrapper W) *Discarder[W] {
Discarder := &Discarder[W]{
Proxy: wrapper,
}
return Discarder
}