-
Notifications
You must be signed in to change notification settings - Fork 0
/
RPCOriginalParamsCodec.go
47 lines (42 loc) · 1.14 KB
/
RPCOriginalParamsCodec.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
package wsrpc
import (
"encoding/json"
"errors"
"reflect"
)
type RPCOriginalParamsCodec struct {
}
func NewRPCOriginalParamsCodec() *RPCOriginalParamsCodec {
return &RPCOriginalParamsCodec{}
}
func (*RPCOriginalParamsCodec) Encode(values []reflect.Value) (json.RawMessage, error) {
nParams := len(values)
if nParams == 0 {
return jsonNullValue, nil
} else if nParams != 0 {
return nil, errors.New("original codec should be applied to 0 or 1 param only")
}
return json.Marshal(values[0].Interface())
}
func (*RPCOriginalParamsCodec) Decode(rawValues json.RawMessage, valueTypes []reflect.Type) ([]reflect.Value, error) {
if len(valueTypes) == 0 {
return []reflect.Value{}, nil
} else if len(rawValues) != 0 {
return nil, errors.New("original codec should be applied to 0 or 1 param only")
}
var value reflect.Value
pType := valueTypes[0]
if pType.Kind() == reflect.Ptr {
value = reflect.New(pType.Elem())
} else {
value = reflect.New(pType)
}
err := json.Unmarshal(rawValues, value.Interface())
if err != nil {
return nil, err
}
if pType.Kind() != reflect.Ptr {
value = value.Elem()
}
return []reflect.Value{value}, nil
}