2015-11-28 20:54:38 +02:00
|
|
|
package jsonrpc
|
2015-11-28 20:40:32 +02:00
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
2019-01-08 17:38:25 +02:00
|
|
|
"fmt"
|
2015-11-28 20:40:32 +02:00
|
|
|
"io"
|
|
|
|
|
2021-01-20 15:54:31 +02:00
|
|
|
"github.com/asim/go-micro/v3/codec"
|
2015-11-28 20:40:32 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
type serverCodec struct {
|
|
|
|
dec *json.Decoder // for reading JSON values
|
|
|
|
enc *json.Encoder // for writing JSON values
|
|
|
|
c io.Closer
|
|
|
|
|
|
|
|
// temporary work space
|
|
|
|
req serverRequest
|
|
|
|
resp serverResponse
|
|
|
|
}
|
|
|
|
|
|
|
|
type serverRequest struct {
|
|
|
|
Method string `json:"method"`
|
|
|
|
Params *json.RawMessage `json:"params"`
|
2019-01-08 17:38:25 +02:00
|
|
|
ID interface{} `json:"id"`
|
2015-11-28 20:40:32 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
type serverResponse struct {
|
2019-01-08 17:38:25 +02:00
|
|
|
ID interface{} `json:"id"`
|
|
|
|
Result interface{} `json:"result"`
|
|
|
|
Error interface{} `json:"error"`
|
2015-11-28 20:40:32 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func newServerCodec(conn io.ReadWriteCloser) *serverCodec {
|
|
|
|
return &serverCodec{
|
2019-01-08 17:38:25 +02:00
|
|
|
dec: json.NewDecoder(conn),
|
|
|
|
enc: json.NewEncoder(conn),
|
|
|
|
c: conn,
|
2015-11-28 20:40:32 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *serverRequest) reset() {
|
|
|
|
r.Method = ""
|
|
|
|
if r.Params != nil {
|
|
|
|
*r.Params = (*r.Params)[0:0]
|
|
|
|
}
|
|
|
|
if r.ID != nil {
|
2019-01-08 17:38:25 +02:00
|
|
|
r.ID = nil
|
2015-11-28 20:40:32 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *serverCodec) ReadHeader(m *codec.Message) error {
|
|
|
|
c.req.reset()
|
|
|
|
if err := c.dec.Decode(&c.req); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2019-01-18 12:12:57 +02:00
|
|
|
m.Method = c.req.Method
|
2019-01-08 17:38:25 +02:00
|
|
|
m.Id = fmt.Sprintf("%v", c.req.ID)
|
2015-11-28 20:40:32 +02:00
|
|
|
c.req.ID = nil
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *serverCodec) ReadBody(x interface{}) error {
|
|
|
|
if x == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
var params [1]interface{}
|
|
|
|
params[0] = x
|
|
|
|
return json.Unmarshal(*c.req.Params, ¶ms)
|
|
|
|
}
|
|
|
|
|
|
|
|
var null = json.RawMessage([]byte("null"))
|
|
|
|
|
|
|
|
func (c *serverCodec) Write(m *codec.Message, x interface{}) error {
|
|
|
|
var resp serverResponse
|
2019-01-08 17:38:25 +02:00
|
|
|
resp.ID = m.Id
|
2015-11-28 20:40:32 +02:00
|
|
|
resp.Result = x
|
|
|
|
if m.Error == "" {
|
|
|
|
resp.Error = nil
|
|
|
|
} else {
|
|
|
|
resp.Error = m.Error
|
|
|
|
}
|
|
|
|
return c.enc.Encode(resp)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *serverCodec) Close() error {
|
|
|
|
return c.c.Close()
|
|
|
|
}
|