-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.go
67 lines (62 loc) · 1.63 KB
/
common.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
package spec
import (
"github.com/mitchellh/mapstructure"
)
// Convert byte slice to T object. Returns nil if JrpcType = TypeNone.
func fromBytes[T any](data []byte, tp JrpcType) *T {
obj, t := GetJrpcType(data)
if t == tp {
return fromMap[T](obj)
}
return nil
}
// Converts map to T object
func fromMap[T any](m interface{}) *T {
var obj = new(T)
mapstructure.Decode(m, obj)
return obj
}
// This function is more as an example and its own implementation is preferred.
/* // Example for own implementation:
obj, tp := GetJrpcType(byteSlice) // would be wise to use switch{} on tp
req := spec.Request{}
mapstructure.Decode(obj, &req)
*/
//
// Decodes byte slice to one of JsonRpc types and returns data and JsonRpc type.
// for the working project.
/* // Example using Array:
dataArray := []byte(`[{"jsonrpc":"2.0","method":"calc_add","params":[7,3],"id":4418}]`)
ob, tp := spec.GetObject(dataArray)
if tp == spec.TypeBatchRequest {
request := ob.(spec.Request)
fmt.Println(request)
}
// Example using Object:
dataObject := []byte(`{"jsonrpc":"2.0","method":"calc_add","params":[7,3],"id":4418}`)
ob, tp := spec.GetObject(dataArray)
if tp == spec.TypeRequest {
request := ob.(spec.Request)
fmt.Println(request)
}
*/
func Parse(data []byte) (interface{}, JrpcType) {
obj, tp := GetJrpcType(data)
var res interface{}
switch tp {
case TypeBatchRequest:
res = BatchRequest{}
case TypeRequest:
res = Request{}
case TypeBatchResponse:
res = BatchResponse{}
case TypeResponse:
res = Response{}
case TypeError:
res = Error{}
case TypeNotification:
res = Notification{}
}
mapstructure.Decode(obj, &res)
return res, tp
}