-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathsliceorsinglevalue.go
More file actions
57 lines (50 loc) · 1.23 KB
/
sliceorsinglevalue.go
File metadata and controls
57 lines (50 loc) · 1.23 KB
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
package oidfed
import (
"encoding/json"
"gopkg.in/yaml.v3"
)
// SliceOrSingleValue is a type that supports (un-)marshaling
// (json) of a slice where a single value might not be expressed as a slice
type SliceOrSingleValue[T any] []T
// UnmarshalJSON implements the json.Unmarshaler interface
func (v *SliceOrSingleValue[T]) UnmarshalJSON(data []byte) error {
var t T
if json.Unmarshal(data, &t) == nil {
*v = []T{t}
return nil
}
var tSlice []T
if err := json.Unmarshal(data, &tSlice); err != nil {
return err
}
*v = tSlice
return nil
}
// MarshalJSON implements the json.Marshaler interface
func (v SliceOrSingleValue[T]) MarshalJSON() ([]byte, error) {
if len(v) == 1 {
return json.Marshal(v[0])
}
return json.Marshal([]T(v))
}
// UnmarshalYAML implements the yaml.Unmarshaler interface
func (v *SliceOrSingleValue[T]) UnmarshalYAML(value *yaml.Node) error {
var t T
if err := value.Decode(&t); err == nil {
*v = []T{t}
return nil
}
var tSlice []T
if err := value.Decode(&tSlice); err != nil {
return err
}
*v = tSlice
return nil
}
// MarshalYAML implements the yaml.Marshaler interface
func (v SliceOrSingleValue[T]) MarshalYAML() (interface{}, error) {
if len(v) == 1 {
return v[0], nil
}
return []T(v), nil
}