-
Notifications
You must be signed in to change notification settings - Fork 0
/
response.go
77 lines (69 loc) · 1.51 KB
/
response.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
69
70
71
72
73
74
75
76
77
package gopherpc
import (
"encoding/json"
"regexp"
)
type IResponse interface {
Marshall() ([]byte, error)
String() (string, error)
}
type response struct {
Jsonrpc string `json:"jsonrpc"`
Result interface{} `json:"result"`
ID interface{} `json:"id"`
//
bytesRepresentation []byte `json:"-"`
stringRepresentation string `json:"-"`
}
func (this *response) Marshall() ([]byte, error) {
if this.bytesRepresentation == nil ||
len(this.bytesRepresentation) == 0 {
bts, err := json.Marshal(this)
if err != nil {
return nil, err
}
this.bytesRepresentation = bts
}
return this.bytesRepresentation, nil
}
func (this *response) String() (string, error) {
if this.stringRepresentation == "" {
_, err := this.Marshall()
if err != nil {
return "", err
}
this.stringRepresentation = string(this.bytesRepresentation)
}
return this.stringRepresentation, nil
}
func IsResponse(bts []byte) bool {
isError, _ := regexp.Match(
errorRegexString,
bts,
)
return !isError
}
func ParseResponse(bts []byte) (*response, error) {
var (
resp = new(response)
)
err := json.Unmarshal(bts, resp)
if err != nil {
return nil, err
}
return resp, nil
}
func (this *response) ParseResult(userTypeResult interface{}) error {
if resultBytes, err := json.Marshal(this.Result); err != nil {
return err
} else {
if this.Result != nil {
if err := json.Unmarshal([]byte(resultBytes), userTypeResult); err != nil {
return err
} else {
this.Result = userTypeResult
}
}
}
return nil
}