-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequest.go
65 lines (58 loc) · 1.45 KB
/
request.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
package gopherpc
import (
"encoding/json"
)
const (
ProtoVersion string = "2.0"
)
type Request struct {
Jsonrpc string `json:"jsonrpc"`
Method string `json:"method"`
Params interface{} `json:"params"`
ID interface{} `json:"id"`
isNotification bool
}
func ParseRequest(bts []byte) (*Request, IResponse, error) {
var (
request = new(Request)
)
if err := json.Unmarshal(bts, request); err != nil {
return nil, Error(ErrParse, err.Error()), err
}
if request.ID == nil {
request.isNotification = true
} else {
request.isNotification = false
}
return request, nil, nil
}
func (this *Request) ParseParams(userTypeParams interface{}) (IResponse, error) {
if paramsBytes, err := json.Marshal(this.Params); err != nil {
return Error(ErrParse, err.Error()), err
} else {
if this.Params != nil {
if err := json.Unmarshal([]byte(paramsBytes), userTypeParams); err != nil {
return Error(ErrParse, err.Error()), err
} else {
this.Params = userTypeParams
}
}
}
return nil, nil
}
func (this *Request) Response(result interface{}) (IResponse, error) {
if this.isNotification {
return nil, NotificationHasntResponse
}
return &response{
Jsonrpc: ProtoVersion,
Result: result,
ID: this.ID,
}, nil
}
func (this *Request) Error(code ErrCode, message string) (IResponse, error) {
if this.isNotification {
return nil, NotificationHasntResponse
}
return Error(code, message), nil
}