micro/codec/jsonrpc/server.go

88 lines
1.6 KiB
Go
Raw Normal View History

2015-11-28 21:54:38 +03:00
package jsonrpc
2015-11-28 21:40:32 +03:00
import (
"encoding/json"
2019-01-08 18:38:25 +03:00
"fmt"
2015-11-28 21:40:32 +03:00
"io"
"github.com/micro/go-micro/codec"
)
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 18:38:25 +03:00
ID interface{} `json:"id"`
2015-11-28 21:40:32 +03:00
}
type serverResponse struct {
2019-01-08 18:38:25 +03:00
ID interface{} `json:"id"`
Result interface{} `json:"result"`
Error interface{} `json:"error"`
2015-11-28 21:40:32 +03:00
}
func newServerCodec(conn io.ReadWriteCloser) *serverCodec {
return &serverCodec{
2019-01-08 18:38:25 +03:00
dec: json.NewDecoder(conn),
enc: json.NewEncoder(conn),
c: conn,
2015-11-28 21:40:32 +03:00
}
}
func (r *serverRequest) reset() {
r.Method = ""
if r.Params != nil {
*r.Params = (*r.Params)[0:0]
}
if r.ID != nil {
2019-01-08 18:38:25 +03:00
r.ID = nil
2015-11-28 21:40:32 +03: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 13:12:57 +03:00
m.Method = c.req.Method
2019-01-08 18:38:25 +03:00
m.Id = fmt.Sprintf("%v", c.req.ID)
2015-11-28 21:40:32 +03: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, &params)
}
var null = json.RawMessage([]byte("null"))
func (c *serverCodec) Write(m *codec.Message, x interface{}) error {
var resp serverResponse
2019-01-08 18:38:25 +03:00
resp.ID = m.Id
2015-11-28 21:40:32 +03: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()
}