1
0
mirror of https://github.com/go-micro/go-micro.git synced 2024-12-24 10:07:04 +02:00
go-micro/codec/jsonrpc/server.go

88 lines
1.6 KiB
Go
Raw Normal View History

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-10-12 13:55:53 +02:00
"go-micro.dev/v4/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, &params)
}
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()
}