diff options
author | Jeffrey Wilcke <jeffrey@ethereum.org> | 2015-06-11 22:41:43 +0800 |
---|---|---|
committer | Jeffrey Wilcke <jeffrey@ethereum.org> | 2015-06-11 22:41:43 +0800 |
commit | e2c2d8e15ebef85c77f7486f92c6430ca6f30785 (patch) | |
tree | 1cd237e5aba5453c641a8d631cffd96c9eb08757 /rpc/codec/json.go | |
parent | 6609d45ef48ce1c2d2b0e73fa8fe5190d36e3920 (diff) | |
parent | b3c07f167f8b82d1079abe6e15cd1f480712b030 (diff) | |
download | go-tangerine-e2c2d8e15ebef85c77f7486f92c6430ca6f30785.tar go-tangerine-e2c2d8e15ebef85c77f7486f92c6430ca6f30785.tar.gz go-tangerine-e2c2d8e15ebef85c77f7486f92c6430ca6f30785.tar.bz2 go-tangerine-e2c2d8e15ebef85c77f7486f92c6430ca6f30785.tar.lz go-tangerine-e2c2d8e15ebef85c77f7486f92c6430ca6f30785.tar.xz go-tangerine-e2c2d8e15ebef85c77f7486f92c6430ca6f30785.tar.zst go-tangerine-e2c2d8e15ebef85c77f7486f92c6430ca6f30785.zip |
Merge pull request #1239 from bas-vk/rpc-apis
RPC refactoring
Diffstat (limited to 'rpc/codec/json.go')
-rw-r--r-- | rpc/codec/json.go | 75 |
1 files changed, 75 insertions, 0 deletions
diff --git a/rpc/codec/json.go b/rpc/codec/json.go new file mode 100644 index 000000000..31024ee74 --- /dev/null +++ b/rpc/codec/json.go @@ -0,0 +1,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() +} |