rpc/protocol/json/client.go

55 lines
1.4 KiB
Go
Raw Normal View History

2017-10-26 07:21:35 +00:00
package json
import (
"io"
2017-10-31 09:25:44 +00:00
2017-11-26 10:15:51 +00:00
"git.loafle.net/commons_go/rpc/codec"
2017-10-31 09:25:44 +00:00
"git.loafle.net/commons_go/rpc/protocol"
2018-03-23 02:28:59 +00:00
jsoniter "github.com/json-iterator/go"
2017-10-26 07:21:35 +00:00
)
2017-10-31 09:25:44 +00:00
// ----------------------------------------------------------------------------
// Codec
// ----------------------------------------------------------------------------
// NewCustomClientCodec returns a new JSON Codec based on passed encoder selector.
2017-11-26 10:15:51 +00:00
func NewCustomClientCodec(codecSel codec.CodecSelector) protocol.ClientCodec {
return &ClientCodec{codecSel: codecSel}
2017-10-26 07:21:35 +00:00
}
2017-10-31 09:25:44 +00:00
// NewClientCodec returns a new JSON Codec.
2017-11-26 10:15:51 +00:00
func NewClientCodec() protocol.ClientCodec {
return NewCustomClientCodec(codec.DefaultCodecSelector)
2017-10-31 09:25:44 +00:00
}
// ClientCodec creates a ClientCodecRequest to process each request.
type ClientCodec struct {
2017-11-26 10:15:51 +00:00
codecSel codec.CodecSelector
2017-10-31 09:25:44 +00:00
}
2018-03-20 06:31:54 +00:00
func (cc *ClientCodec) WriteRequest(w io.Writer, method string, args []interface{}, id interface{}) error {
params, err := convertParamsToStringArray(args)
if nil != err {
return err
}
2017-11-28 16:19:03 +00:00
req := &clientRequest{
Version: Version,
Method: method,
2018-03-20 06:31:54 +00:00
Params: params,
2017-11-28 16:19:03 +00:00
ID: id,
}
2017-10-31 09:25:44 +00:00
2018-03-23 03:22:16 +00:00
encoder := jsoniter.NewEncoder(cc.codecSel.SelectByWriter(w).Encode(w))
2017-10-31 09:25:44 +00:00
if err := encoder.Encode(req); nil != err {
2017-10-26 07:21:35 +00:00
return err
}
2017-10-31 09:25:44 +00:00
return nil
}
2017-11-26 10:15:51 +00:00
// NewMessage returns a ClientMessageCodec.
2017-11-28 16:19:03 +00:00
func (cc *ClientCodec) NewResponse(r io.Reader) (protocol.ClientResponseCodec, error) {
return newClientResponseCodec(r, cc.codecSel.SelectByReader(r))
2017-10-26 07:21:35 +00:00
}