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
|
package codec
import (
"encoding/json"
"net"
"github.com/ethereum/go-ethereum/rpc/shared"
)
const (
MAX_RESPONSE_SIZE = 64 * 1024
)
// Json serialization support
type JsonCodec struct {
c net.Conn
d *json.Decoder
e *json.Encoder
}
// Create new JSON coder instance
func NewJsonCoder(conn net.Conn) ApiCoder {
return &JsonCodec{
c: conn,
d: json.NewDecoder(conn),
e: json.NewEncoder(conn),
}
}
// Serialize obj to JSON and write it to conn
func (self *JsonCodec) ReadRequest() (*shared.Request, error) {
req := shared.Request{}
err := self.d.Decode(&req)
if err == nil {
return &req, nil
}
return nil, err
}
func (self *JsonCodec) ReadResponse() (interface{}, error) {
var err error
buf := make([]byte, MAX_RESPONSE_SIZE)
n, _ := self.c.Read(buf)
var failure shared.ErrorResponse
if err = json.Unmarshal(buf[:n], &failure); err == nil && failure.Error != nil {
return failure, nil
}
var success shared.SuccessResponse
if err = json.Unmarshal(buf[:n], &success); err == nil {
return success, nil
}
return nil, err
}
// Encode response to encoded form in underlying stream
func (self *JsonCodec) Decode(data []byte, msg interface{}) error {
return json.Unmarshal(data, msg)
}
func (self *JsonCodec) Encode(msg interface{}) ([]byte, error) {
return json.Marshal(msg)
}
// Parse JSON data from conn to obj
func (self *JsonCodec) WriteResponse(res interface{}) error {
return self.e.Encode(&res)
}
// Close decoder and encoder
func (self *JsonCodec) Close() {
self.c.Close()
}
|