rpc/protocol/json/server.go
crusader 08688dfb2f ing
2018-03-23 16:43:05 +09:00

51 lines
1.3 KiB
Go

package json
import (
"encoding/json"
"io"
"git.loafle.net/commons_go/rpc/protocol"
)
var null = json.RawMessage([]byte("null"))
// ----------------------------------------------------------------------------
// Codec
// ----------------------------------------------------------------------------
// NewServerCodec returns a new JSON Codec.
func NewServerCodec() protocol.ServerCodec {
return &ServerCodec{}
}
// ServerCodec creates a ServerRequestCodec to process each request.
type ServerCodec struct {
}
func (sc *ServerCodec) NewDecoder(r io.Reader) interface{} {
return json.NewDecoder(r)
}
// NewRequest returns a ServerRequestCodec.
func (sc *ServerCodec) NewRequest(decoder interface{}) (protocol.ServerRequestCodec, error) {
return newServerRequestCodec(decoder.(*json.Decoder))
}
// WriteNotification send a notification from server to client.
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}
res := &serverResponse{Version: Version, Result: noti}
encoder := json.NewEncoder(w)
// Not sure in which case will this happen. But seems harmless.
if err := encoder.Encode(res); nil != err {
return err
}
return nil
}