-
Notifications
You must be signed in to change notification settings - Fork 1
/
payload.go
68 lines (55 loc) · 1.28 KB
/
payload.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
package asyncp
import (
"encoding/json"
"reflect"
)
// Payload represents interface of working with input data
type Payload interface {
// Encode payload data to the bytes
Encode() ([]byte, error)
// Decode payload data into the target
Decode(target any) error
}
func newPayload(val any) (Payload, error) {
switch b := (val).(type) {
case nil:
case []byte:
return dataPayload{bytes: b}, nil
default:
return &valuePayload{value: val}, nil
}
return dataPayload{}, nil
}
type dataPayload struct {
bytes []byte
}
func (p dataPayload) Decode(target any) error {
return json.Unmarshal(p.bytes, target)
}
func (p dataPayload) Encode() ([]byte, error) {
return p.bytes, nil
}
func (p dataPayload) MarshalJSON() ([]byte, error) {
return p.Encode()
}
type valuePayload struct {
value any
}
func (p *valuePayload) Decode(target any) error {
dst := valueFinal(reflect.ValueOf(target))
src := valueFinal(reflect.ValueOf(p.value))
dst.Set(src)
return nil
}
func (p *valuePayload) Encode() ([]byte, error) {
return json.Marshal(p.value)
}
func (p *valuePayload) MarshalJSON() ([]byte, error) {
return p.Encode()
}
func valueFinal(v reflect.Value) reflect.Value {
for v.IsValid() && (v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface) && !v.IsNil() {
v = v.Elem()
}
return v
}