rpc-go/protocol/json/server.go
2018-08-22 18:04:25 +09:00

78 lines
1.9 KiB
Go

package json
import (
"encoding/json"
"git.loafle.net/overflow/rpc-go/codec"
"git.loafle.net/overflow/rpc-go/protocol"
)
var null = json.RawMessage([]byte("null"))
// ----------------------------------------------------------------------------
// Codec
// ----------------------------------------------------------------------------
// NewCustomServerCodec returns a new JSON Codec.
func NewCustomServerCodec(codecSelector codec.CodecSelector) protocol.ServerCodec {
return &ServerCodec{
codecSelector: codecSelector,
}
}
// 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 {
codecSelector codec.CodecSelector
}
func (sc *ServerCodec) NewRequest(messageType int, message []byte) (protocol.ServerRequestCodec, error) {
buf, err := sc.codecSelector.Decode(messageType, message)
if nil != err {
return nil, err
}
return newServerRequestCodec(sc.codecSelector, buf)
}
// 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) {
params, err := convertParamsToStringArray(args)
if nil != err {
return 0, nil, err
}
noti := &serverNotification{Method: method, Params: params}
res := &serverResponse{Version: Version, Result: noti}
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
}