rpc/protocol/json/server.go

54 lines
1.6 KiB
Go
Raw Normal View History

2017-10-25 14:52:47 +00:00
package json
import (
"encoding/json"
2017-10-26 07:21:35 +00:00
"io"
2017-11-26 10:15:51 +00:00
"git.loafle.net/commons_go/rpc/codec"
2017-10-26 07:21:35 +00:00
"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
// NewCustomServerCodec returns a new JSON Codec based on passed encoder selector.
2017-11-26 10:15:51 +00:00
func NewCustomServerCodec(codecSel codec.CodecSelector) protocol.ServerCodec {
return &ServerCodec{codecSel: codecSel}
2017-10-25 14:52:47 +00:00
}
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 {
return NewCustomServerCodec(codec.DefaultCodecSelector)
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 {
2017-11-26 10:15:51 +00:00
codecSel codec.CodecSelector
2017-10-25 14:52:47 +00:00
}
2017-11-26 10:15:51 +00:00
// NewRequest returns a ServerRequestCodec.
func (sc *ServerCodec) NewRequest(r io.Reader) (protocol.ServerRequestCodec, error) {
return newServerRequestCodec(r, sc.codecSel.SelectByReader(r))
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}
2017-11-26 10:15:51 +00:00
encoder := json.NewEncoder(sc.codecSel.SelectByWriter(w).Encode(w))
// 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
}