-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoptional_marshaljson.go
35 lines (29 loc) · 1.02 KB
/
optional_marshaljson.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
package opt
import (
"encoding"
"fmt"
"reflect"
"github.com/reiver/go-erorr"
"github.com/reiver/go-json"
)
var _ json.Marshaler = Nothing[bool]()
var _ json.Marshaler = Nothing[string]()
// MarshalJSON makes it so json.Marshaler is implemented.
func (receiver Optional[T]) MarshalJSON() ([]byte, error) {
switch interface{}(receiver.value).(type) {
case json.Marshaler, encoding.TextMarshaler, bool, int, int8, int16, int32, int64, string, uint, uint8, uint16, uint32, uint64:
// these are OK.
default:
var reflectedType reflect.Type = reflect.TypeOf(receiver.value)
if nil == reflectedType {
return nil, errBadReflection
}
if reflect.Struct != reflectedType.Kind() {
return nil, erorr.Errorf("opt: cannot marshal something of type %T into JSON because parameterized type is ‘%T’ is not supported", receiver, receiver.value)
}
}
if receiver.IsNothing() {
return nil, json.ErrEmpty(fmt.Sprintf("opt: cannot marshal opt.Nothing[%T]() into JSON", receiver.value))
}
return json.Marshal(receiver.value)
}