rpc/protocol/json/server.go

51 lines
1.3 KiB
Go
Raw Normal View History

2017-10-25 14:52:47 +00:00
package json
import (
2018-03-23 03:22:16 +00:00
"encoding/json"
2017-10-26 07:21:35 +00:00
"io"
"git.loafle.net/commons_go/rpc/protocol"
2017-10-25 14:52:47 +00:00
)
var null = json.RawMessage([]byte("null"))
// ----------------------------------------------------------------------------
// Codec
// ----------------------------------------------------------------------------
2017-10-31 09:25:44 +00:00
// NewServerCodec returns a new JSON Codec.
2017-11-26 10:15:51 +00:00
func NewServerCodec() protocol.ServerCodec {
2018-03-23 07:43:05 +00:00
return &ServerCodec{}
2017-10-25 14:52:47 +00:00
}
2017-11-26 10:15:51 +00:00
// ServerCodec creates a ServerRequestCodec to process each request.
2017-10-31 09:25:44 +00:00
type ServerCodec struct {
2018-03-23 07:43:05 +00:00
}
func (sc *ServerCodec) NewDecoder(r io.Reader) interface{} {
return json.NewDecoder(r)
2017-10-25 14:52:47 +00:00
}
2017-11-26 10:15:51 +00:00
// NewRequest returns a ServerRequestCodec.
2018-03-23 07:43:05 +00:00
func (sc *ServerCodec) NewRequest(decoder interface{}) (protocol.ServerRequestCodec, error) {
return newServerRequestCodec(decoder.(*json.Decoder))
2017-10-25 14:52:47 +00:00
}
2017-11-26 10:15:51 +00:00
// WriteNotification send a notification from server to client.
2018-03-20 06:31:54 +00:00
func (sc *ServerCodec) WriteNotification(w io.Writer, method string, args []interface{}) error {
params, err := convertParamsToStringArray(args)
if nil != err {
return err
}
noti := &serverNotification{Method: method, Params: params}
2017-11-28 16:19:03 +00:00
res := &serverResponse{Version: Version, Result: noti}
2018-03-23 07:43:05 +00:00
encoder := json.NewEncoder(w)
2017-11-26 10:15:51 +00:00
// Not sure in which case will this happen. But seems harmless.
2017-11-28 16:19:03 +00:00
if err := encoder.Encode(res); nil != err {
2017-11-26 10:15:51 +00:00
return err
2017-10-25 14:52:47 +00:00
}
2017-10-26 07:21:35 +00:00
return nil
2017-10-25 14:52:47 +00:00
}