rpc-go/protocol/json/client.go

60 lines
1.4 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"
)
// ----------------------------------------------------------------------------
// Codec
// ----------------------------------------------------------------------------
2018-06-30 16:37:26 +00:00
// NewClientCodec returns a new JSON Codec.
func NewCustomClientCodec(codecSelector codec.CodecSelector) protocol.ClientCodec {
return &ClientCodec{
codecSelector: codecSelector,
}
}
2018-04-03 08:58:26 +00:00
// NewClientCodec returns a new JSON Codec.
func NewClientCodec() protocol.ClientCodec {
2018-06-30 16:37:26 +00:00
return NewCustomClientCodec(codec.DefaultCodecSelector)
2018-04-03 08:58:26 +00:00
}
// ClientCodec creates a ClientCodecRequest to process each request.
type ClientCodec 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 (cc *ClientCodec) NewRequest(method string, args []interface{}, id 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
}
req := &clientRequest{
Version: Version,
Method: method,
Params: params,
ID: id,
}
2018-06-30 16:37:26 +00:00
buf, err := json.Marshal(req)
if nil != err {
return 0, nil, err
}
return cc.codecSelector.Encode(buf)
2018-04-03 08:58:26 +00:00
}
2018-04-06 07:50:10 +00:00
2018-06-30 16:37:26 +00:00
func (cc *ClientCodec) NewResponse(messageType int, message []byte) (protocol.ClientResponseCodec, error) {
buf, err := cc.codecSelector.Decode(messageType, message)
if nil != err {
return nil, err
}
2018-04-03 08:58:26 +00:00
return newClientResponseCodec(buf)
}