rpc/protocol/json/server.go

63 lines
1.6 KiB
Go
Raw Normal View History

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