rpc/protocol/json/server.go
crusader 6aa5c1536d ing
2017-11-29 01:19:03 +09:00

49 lines
1.5 KiB
Go

package json
import (
"encoding/json"
"io"
"git.loafle.net/commons_go/rpc/codec"
"git.loafle.net/commons_go/rpc/protocol"
)
var null = json.RawMessage([]byte("null"))
// ----------------------------------------------------------------------------
// Codec
// ----------------------------------------------------------------------------
// NewCustomServerCodec returns a new JSON Codec based on passed encoder selector.
func NewCustomServerCodec(codecSel codec.CodecSelector) protocol.ServerCodec {
return &ServerCodec{codecSel: codecSel}
}
// NewServerCodec returns a new JSON Codec.
func NewServerCodec() protocol.ServerCodec {
return NewCustomServerCodec(codec.DefaultCodecSelector)
}
// ServerCodec creates a ServerRequestCodec to process each request.
type ServerCodec struct {
codecSel codec.CodecSelector
}
// NewRequest returns a ServerRequestCodec.
func (sc *ServerCodec) NewRequest(r io.Reader) (protocol.ServerRequestCodec, error) {
return newServerRequestCodec(r, sc.codecSel.SelectByReader(r))
}
// WriteNotification send a notification from server to client.
func (sc *ServerCodec) WriteNotification(w io.Writer, method string, args interface{}) error {
noti := &serverNotification{Method: method, Params: args}
res := &serverResponse{Version: Version, Result: noti}
encoder := json.NewEncoder(sc.codecSel.SelectByWriter(w).Encode(w))
// Not sure in which case will this happen. But seems harmless.
if err := encoder.Encode(res); nil != err {
return err
}
return nil
}