rpc-go/protocol/json/server.go

78 lines
1.9 KiB
Go
Raw Normal View History

2018-04-03 08:58:26 +00:00
package json
import (
"encoding/json"
2018-06-30 16:37:26 +00:00
"git.loafle.net/commons/rpc-go/codec"
2018-04-03 08:58:26 +00:00
"git.loafle.net/commons/rpc-go/protocol"
)
var null = json.RawMessage([]byte("null"))
// ----------------------------------------------------------------------------
// Codec
// ----------------------------------------------------------------------------
2018-06-30 16:37:26 +00:00
// NewCustomServerCodec returns a new JSON Codec.
func NewCustomServerCodec(codecSelector codec.CodecSelector) protocol.ServerCodec {
return &ServerCodec{
codecSelector: codecSelector,
}
}
2018-04-03 08:58:26 +00:00
// NewServerCodec returns a new JSON Codec.
func NewServerCodec() protocol.ServerCodec {
2018-06-30 16:37:26 +00:00
return NewCustomServerCodec(codec.DefaultCodecSelector)
2018-04-03 08:58:26 +00:00
}
// ServerCodec creates a ServerRequestCodec to process each request.
type ServerCodec struct {
2018-06-30 16:37:26 +00:00
codecSelector codec.CodecSelector
2018-04-03 08:58:26 +00:00
}
2018-06-30 16:37:26 +00:00
func (sc *ServerCodec) NewRequest(messageType int, message []byte) (protocol.ServerRequestCodec, error) {
buf, err := sc.codecSelector.Decode(messageType, message)
2018-04-06 07:50:10 +00:00
if nil != err {
return nil, err
}
2018-06-30 16:37:26 +00:00
return newServerRequestCodec(sc.codecSelector, buf)
2018-04-06 07:50:10 +00:00
}
2018-06-30 16:37:26 +00:00
// func (sc *ServerCodec) NewRequestWithString(method string, params []string, id interface{}) (protocol.ServerRequestCodec, error) {
// req := &clientRequest{
// Version: Version,
// Method: method,
// Params: params,
// ID: id,
// }
// buf, err := json.Marshal(req)
// if nil != err {
// return nil, err
// }
// return sc.NewRequest(buf)
// }
func (sc *ServerCodec) NewNotification(method string, args []interface{}) (messageType int, message []byte, err error) {
2018-04-03 08:58:26 +00:00
params, err := convertParamsToStringArray(args)
if nil != err {
2018-06-30 16:37:26 +00:00
return 0, nil, err
2018-04-03 08:58:26 +00:00
}
noti := &serverNotification{Method: method, Params: params}
res := &serverResponse{Version: Version, Result: noti}
2018-06-30 16:37:26 +00:00
buf, err := json.Marshal(res)
if nil != err {
return 0, nil, err
}
messageType, message, err = sc.codecSelector.Encode(buf)
if nil != err {
return 0, nil, err
}
return
2018-04-03 08:58:26 +00:00
}